77 #define DEBUG_TYPE "dagcombine" 79 STATISTIC(NodesCombined ,
"Number of dag nodes combined");
80 STATISTIC(PreIndexedNodes ,
"Number of pre-indexed nodes created");
81 STATISTIC(PostIndexedNodes,
"Number of post-indexed nodes created");
82 STATISTIC(OpsNarrowed ,
"Number of load/op/store narrowed");
83 STATISTIC(LdStFP2Int ,
"Number of fp load/store pairs transformed to int");
84 STATISTIC(SlicedLoads,
"Number of load sliced");
85 STATISTIC(NumFPLogicOpsConv,
"Number of logic ops converted to fp ops");
89 cl::desc(
"Enable DAG combiner's use of IR alias analysis"));
93 cl::desc(
"Enable DAG combiner's use of TBAA"));
98 cl::desc(
"Only use DAG-combiner alias analysis in this" 106 cl::desc(
"Bypass the profitability model of load slicing"),
111 cl::desc(
"DAG combiner may split indexing from loads"));
115 cl::desc(
"DAG combiner enable merging multiple stores " 116 "into a wider store"));
120 cl::desc(
"Limit the number of operands to inline for Token Factors"));
124 cl::desc(
"Limit the number of times for the same StoreNode and RootNode " 125 "to bail out in store merging dependence check"));
134 bool LegalDAG =
false;
135 bool LegalOperations =
false;
136 bool LegalTypes =
false;
178 void AddUsersToWorklist(
SDNode *
N) {
184 void AddToWorklistWithUsers(
SDNode *N) {
185 AddUsersToWorklist(N);
192 void clearAddedDanglingWorklistEntries() {
194 while (!PruningList.
empty()) {
197 recursivelyDeleteUnusedNodes(N);
201 SDNode *getNextWorklistEntry() {
203 clearAddedDanglingWorklistEntries();
207 while (!N && !Worklist.
empty()) {
212 bool GoodWorklistEntry = WorklistMap.
erase(N);
213 (void)GoodWorklistEntry;
214 assert(GoodWorklistEntry &&
215 "Found a worklist entry without a corresponding map entry!");
226 OptLevel(OL), AA(AA) {
229 MaximumLegalStoreInBits = 0;
235 VT.getSizeInBits().getKnownMinSize() >= MaximumLegalStoreInBits)
236 MaximumLegalStoreInBits = VT.getSizeInBits().getKnownMinSize();
239 void ConsiderForPruning(
SDNode *N) {
246 void AddToWorklist(
SDNode *N) {
248 "Deleted Node added to Worklist");
255 ConsiderForPruning(N);
257 if (WorklistMap.
insert(std::make_pair(N, Worklist.
size())).second)
262 void removeFromWorklist(
SDNode *N) {
263 CombinedNodes.
erase(N);
265 StoreRootCountMap.
erase(N);
267 auto It = WorklistMap.
find(N);
268 if (It == WorklistMap.
end())
272 Worklist[It->second] =
nullptr;
273 WorklistMap.
erase(It);
276 void deleteAndRecombine(
SDNode *N);
277 bool recursivelyDeleteUnusedNodes(
SDNode *N);
285 return CombineTo(N, &Res, 1, AddTo);
292 return CombineTo(N, To, 2, AddTo);
298 unsigned MaximumLegalStoreInBits;
306 return SimplifyDemandedBits(Op, DemandedBits);
313 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts);
319 bool SimplifyDemandedVectorElts(
SDValue Op) {
322 return SimplifyDemandedVectorElts(Op, DemandedElts);
325 bool SimplifyDemandedBits(
SDValue Op,
const APInt &DemandedBits,
326 const APInt &DemandedElts);
327 bool SimplifyDemandedVectorElts(
SDValue Op,
const APInt &DemandedElts,
328 bool AssumeSingleUse =
false);
330 bool CombineToPreIndexedLoadStore(
SDNode *N);
331 bool CombineToPostIndexedLoadStore(
SDNode *N);
333 bool SliceUpLoad(
SDNode *N);
492 bool reassociationCanBreakAddressingModePattern(
unsigned Opc,
510 bool NotExtCompare =
false);
511 SDValue convertSelectOfFPConstantsToLoadOffset(
521 const SDLoc &DL,
bool foldBooleans);
526 bool isOneUseSetCC(
SDValue N)
const;
535 SDValue combineInsertEltToShuffle(
SDNode *N,
unsigned InsIndex);
550 bool DemandHighBits =
true);
554 unsigned PosOpcode,
unsigned NegOpcode,
568 SDValue VecIn2,
unsigned LeftIdx,
603 int64_t OffsetFromBase;
606 : MemNode(N), OffsetFromBase(Offset) {}
613 bool isMulAddWithConstProfitable(
SDNode *MulNode,
621 EVT LoadResultTy,
EVT &ExtVT);
626 EVT &MemVT,
unsigned ShAmt = 0);
634 bool BackwardsPropagateMask(
SDNode *N);
647 EVT MemVT,
unsigned NumStores,
648 bool IsConstantSrc,
bool UseVector,
664 bool checkMergeStoreCandidatesForDependencies(
686 bool hasOperation(
unsigned Opcode,
EVT VT) {
700 EVT getShiftAmountTy(
EVT LHSTy) {
707 bool isTypeLegal(
const EVT &VT) {
708 if (!LegalTypes)
return true;
713 EVT getSetCCResultType(
EVT VT)
const {
728 explicit WorklistRemover(DAGCombiner &dc)
729 :
SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
732 DC.removeFromWorklist(N);
740 explicit WorklistInserter(DAGCombiner &dc)
741 :
SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
745 void NodeInserted(
SDNode *N)
override { DC.ConsiderForPruning(N); }
755 ((DAGCombiner*)DC)->AddToWorklist(N);
760 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.
size(), AddTo);
765 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
770 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
775 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
780 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
787 void DAGCombiner::deleteAndRecombine(
SDNode *N) {
788 removeFromWorklist(N);
843 bool DAGCombiner::isOneUseSetCC(
SDValue N)
const {
853 if (isa<ConstantFPSDNode>(N))
865 return !(Const->isOpaque() && NoOpaques);
889 bool DAGCombiner::reassociationCanBreakAddressingModePattern(
unsigned Opc,
910 const APInt &C1APIntVal = C1->getAPIntValue();
911 const APInt &C2APIntVal = C2->getAPIntValue();
915 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
918 const int64_t CombinedValue = CombinedValueIntVal.
getSExtValue();
928 AM.
BaseOffs = C2APIntVal.getSExtValue();
930 unsigned AS =
LoadStore->getAddressSpace();
947 SDValue DAGCombiner::reassociateOpsCommutative(
unsigned Opc,
const SDLoc &DL,
991 if (
SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1))
993 if (
SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0))
1004 dbgs() <<
" and " << NumTo - 1 <<
" other values\n");
1005 for (
unsigned i = 0,
e = NumTo; i !=
e; ++i)
1006 assert((!To[i].getNode() ||
1008 "Cannot combine value to value of different type!");
1010 WorklistRemover DeadNodes(*
this);
1014 for (
unsigned i = 0,
e = NumTo; i !=
e; ++i) {
1015 if (To[i].getNode()) {
1016 AddToWorklist(To[i].getNode());
1017 AddUsersToWorklist(To[i].getNode());
1026 deleteAndRecombine(N);
1034 WorklistRemover DeadNodes(*
this);
1049 bool DAGCombiner::SimplifyDemandedBits(
SDValue Op,
const APInt &DemandedBits,
1050 const APInt &DemandedElts) {
1065 CommitTargetLoweringOpt(TLO);
1072 bool DAGCombiner::SimplifyDemandedVectorElts(
SDValue Op,
1073 const APInt &DemandedElts,
1074 bool AssumeSingleUse) {
1076 APInt KnownUndef, KnownZero;
1078 TLO, 0, AssumeSingleUse))
1090 CommitTargetLoweringOpt(TLO);
1094 void DAGCombiner::ReplaceLoadWithPromotedLoad(
SDNode *
Load,
SDNode *ExtLoad) {
1101 WorklistRemover DeadNodes(*
this);
1104 deleteAndRecombine(Load);
1105 AddToWorklist(Trunc.
getNode());
1136 return DAG.
getNode(ExtOpc, DL, PVT, Op);
1150 bool Replace =
false;
1151 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1154 AddToWorklist(NewOp.
getNode());
1165 bool Replace =
false;
1166 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1169 AddToWorklist(NewOp.
getNode());
1180 if (!LegalOperations)
1197 assert(PVT != VT &&
"Don't know what type to promote to!");
1201 bool Replace0 =
false;
1203 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1205 bool Replace1 =
false;
1207 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1216 Replace1 &= (N0 != N1) && !N1->
hasOneUse();
1245 if (!LegalOperations)
1262 assert(PVT != VT &&
"Don't know what type to promote to!");
1266 bool Replace =
false;
1270 N0 = SExtPromoteOperand(N0, PVT);
1272 N0 = ZExtPromoteOperand(N0, PVT);
1274 N0 = PromoteOperand(N0, PVT, Replace);
1294 if (!LegalOperations)
1311 assert(PVT != VT &&
"Don't know what type to promote to!");
1321 bool DAGCombiner::PromoteLoad(
SDValue Op) {
1322 if (!LegalOperations)
1342 assert(PVT != VT &&
"Don't know what type to promote to!");
1357 WorklistRemover DeadNodes(*
this);
1360 deleteAndRecombine(N);
1361 AddToWorklist(Result.
getNode());
1373 bool DAGCombiner::recursivelyDeleteUnusedNodes(
SDNode *N) {
1386 Nodes.
insert(ChildN.getNode());
1388 removeFromWorklist(N);
1393 }
while (!Nodes.
empty());
1408 WorklistInserter AddNodes(*
this);
1412 AddToWorklist(&Node);
1420 while (
SDNode *N = getNextWorklistEntry()) {
1424 if (recursivelyDeleteUnusedNodes(N))
1427 WorklistRemover DeadNodes(*
this);
1433 bool NIsValid = DAG.
LegalizeOp(N, UpdatedNodes);
1435 for (
SDNode *LN : UpdatedNodes)
1436 AddToWorklistWithUsers(LN);
1449 if (!CombinedNodes.
count(ChildN.getNode()))
1450 AddToWorklist(ChildN.getNode());
1463 if (RV.getNode() ==
N)
1468 "Node was deleted but visit returned new node!");
1481 AddToWorklist(RV.getNode());
1482 AddUsersToWorklist(RV.getNode());
1488 recursivelyDeleteUnusedNodes(N);
1537 case ISD::OR:
return visitOR(N);
1545 case ISD::FSHR:
return visitFunnelShift(N);
1636 "Node was deleted but visit returned NULL!");
1643 DagCombineInfo(DAG, Level,
false,
this);
1659 RV = PromoteIntBinOp(
SDValue(N, 0));
1664 RV = PromoteIntShiftOp(
SDValue(N, 0));
1669 RV = PromoteExtend(
SDValue(N, 0));
1672 if (PromoteLoad(
SDValue(N, 0)))
1686 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1706 for (
unsigned i = 1; i < NumOps-1; ++i)
1736 bool Changed =
false;
1743 for (
unsigned i = 0; i < TFs.
size(); ++i) {
1748 for (
unsigned j = i; j < TFs.
size(); j++)
1788 for (
unsigned i = 1,
e = TFs.
size(); i <
e; i++)
1789 AddToWorklist(TFs[i]);
1801 bool DidPruneOps =
false;
1803 unsigned NumLeftToConsider = 0;
1804 for (
const SDValue &Op : Ops) {
1809 auto AddToWorklist = [&](
unsigned CurIdx,
SDNode *
Op,
unsigned OpNumber) {
1812 if (SeenOps.
count(Op) != 0) {
1815 unsigned OrigOpNumber = 0;
1816 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() !=
Op)
1818 assert((OrigOpNumber != Ops.size()) &&
1819 "expected to find TokenFactor Operand");
1821 for (
unsigned i = CurIdx + 1; i < Worklist.
size(); ++i) {
1822 if (Worklist[i].
second == OrigOpNumber) {
1823 Worklist[i].second = OpNumber;
1826 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1827 OpWorkCount[OrigOpNumber] = 0;
1828 NumLeftToConsider--;
1831 if (SeenChains.
insert(Op).second) {
1832 OpWorkCount[OpNumber]++;
1833 Worklist.
push_back(std::make_pair(Op, OpNumber));
1837 for (
unsigned i = 0; i < Worklist.
size() && i < 1024; ++i) {
1839 if (NumLeftToConsider <= 1)
1841 auto CurNode = Worklist[i].first;
1842 auto CurOpNumber = Worklist[i].second;
1843 assert((OpWorkCount[CurOpNumber] > 0) &&
1844 "Node should not appear in worklist");
1845 switch (CurNode->getOpcode()) {
1851 NumLeftToConsider++;
1855 AddToWorklist(i, Op.getNode(), CurOpNumber);
1861 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1864 if (
auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1865 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1868 OpWorkCount[CurOpNumber]--;
1869 if (OpWorkCount[CurOpNumber] == 0)
1870 NumLeftToConsider--;
1883 for (
const SDValue &Op : Ops) {
1884 if (SeenChains.
count(Op.getNode()) == 0)
1899 WorklistRemover DeadNodes(*
this);
1905 AddUsersToWorklist(N);
1913 deleteAndRecombine(N);
1921 return Const !=
nullptr && !Const->
isOpaque() ? Const :
nullptr;
1926 "Unexpected binary operator");
1931 unsigned SelOpNo = 0;
1957 bool CanFoldNonConst =
1963 if (!CanFoldNonConst &&
1983 SDValue NewCT = SelOpNo ? DAG.
getNode(BinOpcode, DL, VT, CBO, CT)
1984 : DAG.
getNode(BinOpcode, DL, VT, CT, CBO);
1985 if (!CanFoldNonConst && !NewCT.
isUndef() &&
1990 SDValue NewCF = SelOpNo ? DAG.
getNode(BinOpcode, DL, VT, CBO, CF)
1991 : DAG.
getNode(BinOpcode, DL, VT, CF, CBO);
1992 if (!CanFoldNonConst && !NewCF.
isUndef() &&
2004 "Expecting add or sub");
2045 "Expecting add or sub");
2090 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
2126 assert(Sub &&
"Constant folding failed");
2135 assert(Add &&
"Constant folding failed");
2146 if ((!LegalOperations ||
2165 if (
SDValue NewSel = foldBinOpIntoSelect(N))
2169 if (!reassociationCanBreakAddressingModePattern(
ISD::ADD, DL, N0, N1)) {
2191 N0.getOperand(0) == N1.getOperand(1))
2197 N0.getOperand(1) == N1.getOperand(0))
2202 if (N1.getOpcode() ==
ISD::SUB && N1.getOperand(1).getOpcode() ==
ISD::ADD &&
2203 N0 == N1.getOperand(1).getOperand(0))
2205 N1.getOperand(1).getOperand(1));
2208 if (N1.getOpcode() ==
ISD::SUB && N1.getOperand(1).getOpcode() ==
ISD::ADD &&
2209 N0 == N1.getOperand(1).getOperand(1))
2211 N1.getOperand(1).getOperand(0));
2215 N1.getOperand(0).getOpcode() ==
ISD::SUB &&
2216 N0 == N1.getOperand(0).getOperand(1))
2217 return DAG.
getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2236 return (!Max && !Op) ||
2237 (Max && Op && Max->
getAPIntValue() == (-Op->getAPIntValue()));
2245 if (SimplifyDemandedBits(
SDValue(N, 0)))
2285 if (N0.hasOneUse() && N0.getOpcode() ==
ISD::SUB &&
2291 if (
SDValue Combined = visitADDLikeCommutative(N0, N1, N))
2294 if (
SDValue Combined = visitADDLikeCommutative(N1, N0, N))
2306 if (
SDValue Combined = visitADDLike(N))
2348 return DAG.
getNode(Opcode, DL, VT, N1, N0);
2367 bool Masked =
false;
2429 SDLoc DL(LocReference);
2499 DAG.
getVTList(VT, Carry.getValueType()), N0,
2563 if (Force && isa<ConstantSDNode>(V))
2575 bool IsFlip =
false;
2578 IsFlip = Const->
isOne();
2616 return CombineTo(N, N0, DAG.
getConstant(0, DL, CarryVT));
2628 return CombineTo(N, Sub,
2632 if (
SDValue Combined = visitUADDOLike(N0, N1, N))
2635 if (
SDValue Combined = visitUADDOLike(N1, N0, N))
2699 if (!LegalOperations ||
2706 EVT VT = N0.getValueType();
2709 AddToWorklist(CarryExt.
getNode());
2715 if (
SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2718 if (
SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2776 Combiner.AddToWorklist(NewY.
getNode());
2859 unsigned CarryInOperandNum =
2861 if (Opcode ==
ISD::USUBO && CarryInOperandNum != 1)
2909 return CombineTo(N, Sub,
2959 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
2978 if (
SDValue NewSel = foldBinOpIntoSelect(N))
2997 if (ShiftAmt && ShiftAmt->
getAPIntValue() == (BitWidth - 1)) {
3032 if (N0.getOpcode() ==
ISD::ADD && N0.getOperand(0) == N1)
3036 if (N0.getOpcode() ==
ISD::ADD && N0.getOperand(1) == N1)
3045 assert(NewC &&
"Constant folding failed");
3056 assert(NewC &&
"Constant folding failed");
3067 assert(NewC &&
"Constant folding failed");
3077 assert(NewC &&
"Constant folding failed");
3083 (N0.getOperand(1).getOpcode() ==
ISD::SUB ||
3084 N0.getOperand(1).getOpcode() ==
ISD::ADD) &&
3085 N0.getOperand(1).getOperand(0) == N1)
3086 return DAG.
getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
3087 N0.getOperand(1).getOperand(1));
3090 if (N0.getOpcode() ==
ISD::ADD && N0.getOperand(1).getOpcode() ==
ISD::ADD &&
3091 N0.getOperand(1).getOperand(1) == N1)
3093 N0.getOperand(1).getOperand(0));
3096 if (N0.getOpcode() ==
ISD::SUB && N0.getOperand(1).getOpcode() ==
ISD::SUB &&
3097 N0.getOperand(1).getOperand(1) == N1)
3099 N0.getOperand(1).getOperand(0));
3172 if (N0.hasOneUse() && N0.getOpcode() ==
ISD::ADD &&
3185 if (N0.hasOneUse() && N0.getOpcode() ==
ISD::SUB &&
3191 if (N0.hasOneUse() && N0.getOpcode() ==
ISD::SUB &&
3213 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) {
3214 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3216 if (
C->getAPIntValue() == (OpSizeInBits - 1))
3232 if (GA->getGlobal() == GB->getGlobal())
3233 return DAG.
getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
3266 DAG.
getVTList(VT, Carry.getValueType()), NegX, Zero,
3361 if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) {
3368 return CombineTo(N, N0, DAG.
getConstant(0, DL, CarryVT));
3397 if (!LegalOperations ||
3438 bool N0IsConst =
false;
3439 bool N1IsConst =
false;
3440 bool N1IsOpaqueConst =
false;
3441 bool N0IsOpaqueConst =
false;
3442 APInt ConstValue0, ConstValue1;
3445 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
3452 "Splat APInt should be element width");
3455 "Splat APInt should be element width");
3457 N0IsConst = isa<ConstantSDNode>(N0);
3459 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
3460 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
3462 N1IsConst = isa<ConstantSDNode>(N1);
3464 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
3465 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
3470 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
3485 if (
SDValue NewSel = foldBinOpIntoSelect(N))
3499 SDValue LogBase2 = BuildLogBase2(N1, DL);
3505 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
3506 unsigned Log2Val = (-ConstValue1).logBase2();
3530 if ((MulC - 1).isPowerOf2())
3532 else if ((MulC + 1).isPowerOf2())
3537 MathOp ==
ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
3539 "multiply-by-constant generated out of bounds shift");
3562 SDValue Sh(
nullptr, 0),
Y(
nullptr, 0);
3585 isMulAddWithConstProfitable(N, N0, N1))
3607 default:
return false;
3608 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8;
break;
3609 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16;
break;
3610 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32;
break;
3611 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64;
break;
3612 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128;
break;
3642 unsigned OtherOpcode = 0;
3666 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
3670 if (UserOpc == OtherOpcode) {
3672 combined = DAG.
getNode(DivRemOpc,
SDLoc(Node), VTs, Op0, Op1);
3673 }
else if (UserOpc == DivRemOpc) {
3676 assert(UserOpc == Opcode);
3681 CombineTo(User, combined);
3683 CombineTo(User, combined.
getValue(1));
3704 if (DAG.
isUndef(Opc, {N0, N1}))
3739 EVT CCVT = getSetCCResultType(VT);
3743 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
3765 if (
SDValue NewSel = foldBinOpIntoSelect(N))
3773 if (
SDValue V = visitSDIVLike(N0, N1, N)) {
3782 CombineTo(RemNode, Sub);
3801 EVT CCVT = getSetCCResultType(VT);
3807 if (
C->isNullValue() ||
C->isOpaque())
3809 if (
C->getAPIntValue().isPowerOf2())
3811 if ((-
C->getAPIntValue()).isPowerOf2())
3822 if (
SDValue Res = BuildSDIVPow2(N))
3837 AddToWorklist(Sign.
getNode());
3841 AddToWorklist(Srl.getNode());
3843 AddToWorklist(Add.getNode());
3845 AddToWorklist(Sra.getNode());
3854 Sra = DAG.
getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
3873 if (
SDValue Op = BuildSDIV(N))
3883 EVT CCVT = getSetCCResultType(VT);
3887 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
3908 if (
SDValue NewSel = foldBinOpIntoSelect(N))
3911 if (
SDValue V = visitUDIVLike(N0, N1, N)) {
3920 CombineTo(RemNode, Sub);
3943 SDValue LogBase2 = BuildLogBase2(N1, DL);
3944 AddToWorklist(LogBase2.
getNode());
3948 AddToWorklist(Trunc.getNode());
3957 SDValue LogBase2 = BuildLogBase2(N10, DL);
3958 AddToWorklist(LogBase2.
getNode());
3962 AddToWorklist(Trunc.
getNode());
3964 AddToWorklist(Add.getNode());
3973 if (
SDValue Op = BuildUDIV(N))
3985 EVT CCVT = getSetCCResultType(VT);
4004 if (
SDValue NewSel = foldBinOpIntoSelect(N))
4040 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
4046 CombineTo(DivNode, OptimizedDiv);
4049 AddToWorklist(OptimizedDiv.
getNode());
4057 return DivRem.getValue(1);
4137 SDValue LogBase2 = BuildLogBase2(N1, DL);
4168 SDValue DAGCombiner::SimplifyNodeWithTwoResults(
SDNode *N,
unsigned LoOp,
4172 if (!HiExists && (!LegalOperations ||
4175 return CombineTo(N, Res, Res);
4180 if (!LoExists && (!LegalOperations ||
4183 return CombineTo(N, Res, Res);
4187 if (LoExists && HiExists)
4195 if (LoOpt.getNode() && LoOpt.getNode() != Lo.
getNode() &&
4196 (!LegalOperations ||
4198 return CombineTo(N, LoOpt, LoOpt);
4205 if (HiOpt.getNode() && HiOpt != Hi &&
4206 (!LegalOperations ||
4208 return CombineTo(N, HiOpt, HiOpt);
4238 return CombineTo(N, Lo, Hi);
4255 return CombineTo(N, Zero, Zero);
4281 return CombineTo(N, Lo, Hi);
4309 if (C2->getAPIntValue() == 2)
4323 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
4360 SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(
SDNode *N) {
4366 LogicOpcode ==
ISD::XOR) &&
"Expected logic opcode");
4392 if ((VT.
isVector() || LegalOperations) &&
4402 return DAG.
getNode(HandOpcode, DL, VT, Logic);
4424 return DAG.
getNode(HandOpcode, DL, VT, Logic);
4445 return DAG.
getNode(HandOpcode, DL, VT, Logic);
4462 return DAG.
getNode(HandOpcode, DL, VT, Logic);
4479 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
4480 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
4482 "Inputs to shuffles are not the same type");
4488 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
4489 !SVN0->getMask().equals(SVN1->getMask()))
4525 SDValue LL, LR, RL, RR, N0CC, N1CC;
4526 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
4527 !isSetCCEquivalent(N1, RL, RR, N1CC))
4531 "Unexpected operand types for bitwise logic op");
4534 "Unexpected operand types for setcc");
4541 if (LegalOperations || VT.getScalarType() !=
MVT::i1)
4542 if (VT != getSetCCResultType(OpVT))
4550 if (LR == RR && CC0 == CC1 && IsInteger) {
4555 bool AndEqZero = IsAnd && CC1 ==
ISD::SETEQ && IsZero;
4557 bool AndGtNeg1 = IsAnd && CC1 ==
ISD::SETGT && IsNeg1;
4559 bool OrNeZero = !IsAnd && CC1 ==
ISD::SETNE && IsZero;
4561 bool OrLtZero = !IsAnd && CC1 ==
ISD::SETLT && IsZero;
4567 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
4570 return DAG.
getSetCC(DL, VT, Or, LR, CC1);
4574 bool AndEqNeg1 = IsAnd && CC1 ==
ISD::SETEQ && IsNeg1;
4576 bool AndLtZero = IsAnd && CC1 ==
ISD::SETLT && IsZero;
4578 bool OrNeNeg1 = !IsAnd && CC1 ==
ISD::SETNE && IsNeg1;
4580 bool OrGtNeg1 = !IsAnd && CC1 ==
ISD::SETGT && IsNeg1;
4586 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
4589 return DAG.
getSetCC(DL, VT, And, LR, CC1);
4617 return DAG.
getSetCC(DL, VT, Or, Zero, CC1);
4634 if ((C0Val - C1Val).isPowerOf2()) {
4642 return DAG.
getSetCC(DL, VT, And, Zero, CC0);
4649 if (LL == RR && LR == RL) {
4656 if (LL == RL && LR == RR) {
4660 (!LegalOperations ||
4663 return DAG.
getSetCC(DL, VT, LL, LR, NewCC);
4681 if (
SDValue V = foldLogicOfSetCCs(
true, N0, N1, DL))
4693 APInt SRLC = SRLI->getAPIntValue();
4706 CombineTo(N0.
getNode(), NewAdd);
4723 const APInt &AndMask = CAnd->getAPIntValue();
4736 (ShiftBits + MaskBits <= Size / 2) &&
4748 assert(MaskBits <= Size);
4769 EVT LoadResultTy,
EVT &ExtVT) {
4778 if (ExtVT == LoadedVT &&
4779 (!LegalOperations ||
4792 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.
isRound())
4795 if (LegalOperations &&
4805 bool DAGCombiner::isLegalNarrowLdSt(
LSBaseSDNode *LDST,
4839 if (isa<LoadSDNode>(LDST)) {
4846 if (LegalOperations &&
4868 assert(isa<StoreSDNode>(LDST) &&
"It is not a Load nor a Store SDNode");
4874 if (LegalOperations &&
4881 bool DAGCombiner::SearchForAndLoads(
SDNode *N,
4893 if (
auto *
C = dyn_cast<ConstantSDNode>(Op)) {
4896 NodesWithConsts.
insert(N);
4905 auto *Load = cast<LoadSDNode>(
Op);
4907 if (isAndLoadExtLoad(Mask, Load, Load->
getValueType(0), ExtVT) &&
4912 ExtVT.bitsGE(Load->getMemoryVT()))
4916 if (ExtVT.bitsLE(Load->getMemoryVT()))
4940 if (!SearchForAndLoads(Op.
getNode(), Loads, NodesWithConsts,
Mask,
4954 for (
unsigned i = 0,
e = NodeToMask->
getNumValues(); i <
e; ++i) {
4958 NodeToMask =
nullptr;
4964 assert(HasValue &&
"Node to be masked has no data result?");
4970 bool DAGCombiner::BackwardsPropagateMask(
SDNode *N) {
4984 SDNode *FixupNode =
nullptr;
4985 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
4986 if (Loads.
size() == 0)
4998 SDValue(FixupNode, 0), MaskOp);
5005 for (
auto *LogicN : NodesWithConsts) {
5009 if (isa<ConstantSDNode>(Op0))
5019 for (
auto *Load : Loads) {
5027 SDValue NewLoad = ReduceLoadWidth(And.getNode());
5029 "Shouldn't be masking the load if it can't be narrowed");
5030 CombineTo(Load, NewLoad, NewLoad.
getValue(1));
5043 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(
SDNode *N) {
5054 unsigned OuterShift;
5055 unsigned InnerShift;
5057 auto matchMask = [&OuterShift, &InnerShift, &
Y](
SDValue M) ->
bool {
5060 OuterShift = M->getOpcode();
5069 Y = M->getOperand(1);
5076 else if (matchMask(N0))
5128 unsigned VTBitWidth = VT.getSizeInBits();
5129 if (ShiftAmt.
uge(VTBitWidth))
5156 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
5179 if (N0C && N1C && !N1C->
isOpaque())
5194 if (
SDValue NewSel = foldBinOpIntoSelect(N))
5203 if (
SDValue Shuffle = XformToShuffleWithZero(N))
5211 return RHS->getAPIntValue().isSubsetOf(LHS->
getAPIntValue());
5231 CombineTo(N0.
getNode(), Zext);
5255 Constant =
C->getAPIntValue();
5257 APInt SplatValue, SplatUndef;
5258 unsigned SplatBitSize;
5260 bool IsSplat =
Vector->isConstantSplat(SplatValue, SplatUndef,
5261 SplatBitSize, HasAnyUndefs);
5265 SplatValue |= SplatUndef;
5271 unsigned EltBitWidth =
Vector->getValueType(0).getScalarSizeInBits();
5276 if (EltBitWidth > SplatBitSize)
5277 for (SplatValue = SplatValue.
zextOrTrunc(EltBitWidth);
5278 SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2)
5279 SplatValue |= SplatValue.
shl(SplatBitSize);
5283 if ((SplatBitSize % EltBitWidth) == 0) {
5285 for (
unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
5286 Constant &= SplatValue.
extractBits(EltBitWidth, i * EltBitWidth);
5305 default: B =
false;
break;
5311 if (B && Constant.isAllOnesValue()) {
5317 CombineTo(N, (N0.
getNode() ==
Load) ? NewLoad : N0);
5330 CombineTo(Load, To, 3,
true);
5346 if (
SDValue Res = ReduceLoadWidth(N)) {
5348 ? cast<LoadSDNode>(N0.
getOperand(0)) : cast<LoadSDNode>(N0);
5360 if (BackwardsPropagateMask(N))
5364 if (
SDValue Combined = visitANDLike(N0, N1, N))
5369 if (
SDValue V = hoistLogicOpWithSameOpcodeHands(N))
5393 if (SimplifyDemandedBits(
SDValue(N, 0)))
5406 unsigned MemBitSize = MemVT.getScalarSizeInBits();
5409 ((!LegalOperations && LN0->
isSimple()) ||
5427 if (
SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
5439 bool DemandHighBits) {
5440 if (!LegalOperations)
5450 bool LookPassAnd0 =
false;
5451 bool LookPassAnd1 =
false;
5466 LookPassAnd0 =
true;
5476 LookPassAnd1 =
true;
5490 if (N01C->
getZExtValue() != 8 || N11C->getZExtValue() != 8)
5502 LookPassAnd0 =
true;
5516 LookPassAnd1 =
true;
5525 if (DemandHighBits && OpSizeInBits > 16) {
5534 if (!LookPassAnd1 &&
5541 if (OpSizeInBits > 16) {
5545 getShiftAmountTy(VT)));
5578 unsigned MaskByteOffset;
5582 case 0xFF: MaskByteOffset = 0;
break;
5583 case 0xFF00: MaskByteOffset = 1;
break;
5592 case 0xFF0000: MaskByteOffset = 2;
break;
5593 case 0xFF000000: MaskByteOffset = 3;
break;
5598 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
5618 if (MaskByteOffset != 0 && MaskByteOffset != 2)
5626 if (MaskByteOffset != 1 && MaskByteOffset != 3)
5633 if (Parts[MaskByteOffset])
5664 if (!LegalOperations)
5696 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
5725 if (
SDValue V = foldLogicOfSetCCs(
false, N0, N1, DL))
5740 const APInt &LHSMask = N0O1C->getAPIntValue();
5741 const APInt &RHSMask = N1O1C->getAPIntValue();
5796 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
5815 if (isa<ShuffleVectorSDNode>(N0) &&
5816 isa<ShuffleVectorSDNode>(N1) &&
5824 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
5825 assert((!ZeroN00 || !ZeroN01) &&
"Both inputs zero!");
5826 assert((!ZeroN10 || !ZeroN11) &&
"Both inputs zero!");
5829 bool CanFold =
true;
5833 for (
int i = 0; i != NumElts; ++i) {
5835 int M1 = SV1->getMaskElt(i);
5838 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
5839 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
5843 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
5849 if (M0Zero == M1Zero) {
5854 assert((M0 >= 0 || M1 >= 0) &&
"Undef index!");
5860 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
5871 return LegalShuffle;
5880 if (N0C && N1C && !N1C->
isOpaque())
5893 if (
SDValue NewSel = foldBinOpIntoSelect(N))
5900 if (
SDValue Combined = visitORLike(N0, N1, N))
5907 if (
SDValue BSwap = MatchBSwapHWord(N, N0, N1))
5909 if (
SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
5938 if (
SDValue V = hoistLogicOpWithSameOpcodeHands(N))
5945 if (
SDValue Load = MatchLoadCombine(N))
5949 if (SimplifyDemandedBits(
SDValue(N, 0)))
5955 if (
SDValue Combined = visitADDLike(N))
6008 assert(OppShift && ExtractFrom &&
"Empty SDValue");
6011 "Existing shift must be valid as a rotate half");
6036 bool IsMulOrDiv =
false;
6039 auto SelectOpcode = [&](
unsigned NeededShift,
unsigned MulOrDivVariant) {
6040 IsMulOrDiv = ExtractFrom.
getOpcode() == MulOrDivVariant;
6041 if (!IsMulOrDiv && ExtractFrom.
getOpcode() != NeededShift)
6043 Opcode = NeededShift;
6068 !ExtractFromCst || !ExtractFromCst->getAPIntValue())
6077 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
6093 if (Rem != 0 || ResultAmt != OppLHSAmt)
6099 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.
zextOrTrunc(
6108 return DAG.
getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
6153 unsigned MaskLoBits = 0;
6158 if (NegC->getAPIntValue().getActiveBits() <= Bits &&
6179 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits &&
6219 return Width.
getLoBits(MaskLoBits) == 0;
6220 return Width == EltSize;
6230 SDValue InnerNeg,
unsigned PosOpcode,
6231 unsigned NegOpcode,
const SDLoc &DL) {
6242 return DAG.
getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
6243 HasPos ? Pos : Neg);
6259 bool HasROTL = hasOperation(
ISD::ROTL, VT);
6260 bool HasROTR = hasOperation(
ISD::ROTR, VT);
6261 if (!HasROTL && !HasROTR)
6283 if (!LHSShift && !RHSShift)
6298 RHSShift = NewRHSShift;
6303 LHSShift = NewLHSShift;
6306 if (!RHSShift || !LHSShift)
6334 return (LHS->
getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
6338 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
6368 SDValue LExtOp0 = LHSShiftAmt;
6369 SDValue RExtOp0 = RHSShiftAmt;
6382 SDValue TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
6387 SDValue TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
6399 struct ByteProvider {
6404 unsigned ByteOffset = 0;
6406 ByteProvider() =
default;
6409 return ByteProvider(Load, ByteOffset);
6412 static ByteProvider getConstantZero() {
return ByteProvider(
nullptr, 0); }
6414 bool isConstantZero()
const {
return !
Load; }
6415 bool isMemory()
const {
return Load; }
6418 return Other.Load == Load && Other.ByteOffset == ByteOffset;
6422 ByteProvider(
LoadSDNode *Load,
unsigned ByteOffset)
6423 :
Load(Load), ByteOffset(ByteOffset) {}
6441 bool Root =
false) {
6451 if (BitWidth % 8 != 0)
6453 unsigned ByteWidth = BitWidth / 8;
6454 assert(Index < ByteWidth &&
"invalid index requested");
6466 if (LHS->isConstantZero())
6468 if (RHS->isConstantZero())
6477 uint64_t BitShift = ShiftOp->getZExtValue();
6478 if (BitShift % 8 != 0)
6480 uint64_t ByteShift = BitShift / 8;
6482 return Index < ByteShift
6483 ? ByteProvider::getConstantZero()
6492 if (NarrowBitWidth % 8 != 0)
6494 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
6496 if (Index >= NarrowByteWidth)
6506 auto L = cast<LoadSDNode>(Op.
getNode());
6507 if (!L->isSimple() || L->isIndexed())
6510 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
6511 if (NarrowBitWidth % 8 != 0)
6513 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
6515 if (Index >= NarrowByteWidth)
6538 int64_t FirstOffset) {
6544 bool BigEndian =
true, LittleEndian =
true;
6545 for (
unsigned i = 0; i <
Width; i++) {
6546 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
6549 if (!BigEndian && !LittleEndian)
6553 assert((BigEndian != LittleEndian) &&
"It should be either big endian or" 6601 Chain =
Store->getChain();
6621 for (
auto Store : Stores) {
6650 CombinedValue =
Value;
6659 CombinedValue = Value;
6667 int64_t ByteOffsetFromBase = 0;
6674 if (ByteOffsetFromBase < FirstOffset) {
6676 FirstOffset = ByteOffsetFromBase;
6680 if (Offset < 0 || Offset >= Width || ByteOffsets[Offset] !=
INT64_MAX)
6682 ByteOffsets[
Offset] = ByteOffsetFromBase;
6686 assert(FirstStore &&
"First store must be set");
6711 if (!Allowed || !Fast)
6716 "Get unexpected store value to combine");
6765 "Can only match load combining against OR nodes");
6771 unsigned ByteWidth = VT.getSizeInBits() / 8;
6774 auto MemoryByteOffset = [&] (ByteProvider
P) {
6775 assert(
P.isMemory() &&
"Must be a memory byte provider");
6776 unsigned LoadBitWidth =
P.Load->getMemoryVT().getSizeInBits();
6777 assert(LoadBitWidth % 8 == 0 &&
6778 "can only analyze providers for individual bytes not bit");
6779 unsigned LoadByteWidth = LoadBitWidth / 8;
6780 return IsBigEndianTarget
6795 unsigned ZeroExtendedBytes = 0;
6796 for (
int i = ByteWidth - 1; i >= 0; --i) {
6801 if (
P->isConstantZero()) {
6804 if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i)))
6808 assert(
P->isMemory() &&
"provenance should either be memory or zero");
6811 assert(L->hasNUsesOfValue(1, 0) && L->isSimple() &&
6813 "Must be enforced by calculateByteProvider");
6814 assert(L->getOffset().isUndef() &&
"Unindexed load must have undef offset");
6817 SDValue LChain = L->getChain();
6820 else if (Chain != LChain)
6825 int64_t ByteOffsetFromBase = 0;
6832 ByteOffsetFromBase += MemoryByteOffset(*
P);
6833 ByteOffsets[i] = ByteOffsetFromBase;
6836 if (ByteOffsetFromBase < FirstOffset) {
6837 FirstByteProvider =
P;
6838 FirstOffset = ByteOffsetFromBase;
6843 assert(!Loads.
empty() &&
"All the bytes of the value must be loaded from " 6844 "memory, so there must be at least one load which produces the value");
6845 assert(Base &&
"Base address of the accessed memory location must be set");
6848 bool NeedsZext = ZeroExtendedBytes > 0;
6859 if (LegalOperations &&
6867 makeArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset);
6871 assert(FirstByteProvider &&
"must be set");
6875 if (MemoryByteOffset(*FirstByteProvider) != 0)
6877 LoadSDNode *FirstLoad = FirstByteProvider->Load;
6884 bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
6891 if (NeedsBswap && (LegalOperations || NeedsZext) &&
6897 if (NeedsBswap && NeedsZext && LegalOperations &&
6906 if (!Allowed || !Fast)
6925 SDLoc(N), LegalOperations))
6956 if (And.getOpcode() !=
ISD::AND || !And.hasOneUse())
6978 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
6979 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
6985 if (isa<ConstantSDNode>(M.
getNode()))
7019 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
7051 if (
SDValue NewSel = foldBinOpIntoSelect(N))
7064 if (!LegalOperations ||
7080 isSetCCEquivalent(N0.
getOperand(0), LHS, RHS, CC)){
7093 if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) {
7097 AddToWorklist(N00.
getNode()); AddToWorklist(N01.getNode());
7098 return DAG.
getNode(NewOpcode, DL, VT, N00, N01);
7105 if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) {
7109 AddToWorklist(N00.
getNode()); AddToWorklist(N01.getNode());
7110 return DAG.
getNode(NewOpcode, DL, VT, N00, N01);
7134 AddToWorklist(NotX.
getNode());
7142 if (XorC && ShiftC) {
7146 if (ShiftAmt < BitWidth) {
7148 Ones = N0Opcode ==
ISD::SHL ? Ones.
shl(ShiftAmt) : Ones.
lshr(ShiftAmt);
7167 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) {
7170 if (
C->getAPIntValue() == (OpSizeInBits - 1))
7206 if (
SDValue V = hoistLogicOpWithSameOpcodeHands(N))
7210 if (
SDValue MM = unfoldMaskedMerge(N))
7214 if (SimplifyDemandedBits(
SDValue(N, 0)))
7233 unsigned LogicOpcode = LogicOp.
getOpcode();
7239 unsigned ShiftOpcode = Shift->
getOpcode();
7242 assert(C1Node &&
"Expected a shift with constant operand");
7245 const APInt *&ShiftAmtVal) {
7259 if (ShiftAmtVal->getBitWidth() != C1Val.
getBitWidth())
7272 if (matchFirstShift(LogicOp.
getOperand(0),
X, C0Val))
7274 else if (matchFirstShift(LogicOp.
getOperand(1),
X, C0Val))
7284 SDValue NewShift1 = DAG.
getNode(ShiftOpcode, DL, VT, X, ShiftSumC);
7286 return DAG.
getNode(LogicOpcode, DL, VT, NewShift1, NewShift2);
7344 isa<ConstantSDNode>(BinOpLHSVal.
getOperand(1));
7348 if (!IsShiftByConstant && !IsCopyOrSelect)
7359 assert(isa<ConstantSDNode>(NewRHS) &&
"Folding was not successful!");
7366 SDValue DAGCombiner::distributeTruncateThroughAnd(
SDNode *N) {
7380 AddToWorklist(Trunc00.
getNode());
7381 AddToWorklist(Trunc01.
getNode());
7410 if (Cst->getAPIntValue().uge(Bitsize)) {
7411 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
7431 bool SameSide = (N->
getOpcode() == NextOp);
7437 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
7459 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
7487 if (N0C && N1C && !N1C->
isOpaque())
7490 if (
SDValue NewSel = foldBinOpIntoSelect(N))
7506 if (N1C && SimplifyDemandedBits(
SDValue(N, 0)))
7514 APInt c2 = RHS->getAPIntValue();
7516 return (c1 + c2).uge(OpSizeInBits);
7524 APInt c2 = RHS->getAPIntValue();
7526 return (c1 + c2).ult(OpSizeInBits);
7549 auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](
ConstantSDNode *LHS,
7551 APInt c1 = LHS->getAPIntValue();
7552 APInt c2 = RHS->getAPIntValue();
7554 return c2.
uge(OpSizeInBits - InnerBitwidth) &&
7555 (c1 + c2).uge(OpSizeInBits);
7562 auto MatchInRange = [OpSizeInBits, InnerBitwidth](
ConstantSDNode *LHS,
7564 APInt c1 = LHS->getAPIntValue();
7565 APInt c2 = RHS->getAPIntValue();
7567 return c2.
uge(OpSizeInBits - InnerBitwidth) &&
7568 (c1 + c2).ult(OpSizeInBits);
7591 APInt c2 = RHS->getAPIntValue();
7602 AddToWorklist(NewSHL.
getNode());
7613 uint64_t C1 = N0C1->getZExtValue();
7633 if (N0C1->getAPIntValue().ult(OpSizeInBits)) {
7634 uint64_t c1 = N0C1->getZExtValue();
7676 AddToWorklist(Shl0.
getNode());
7677 AddToWorklist(Shl1.
getNode());
7691 if (
SDValue NewSHL = visitShiftByConstant(N))
7714 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
7722 if (N0C && N1C && !N1C->
isOpaque())
7725 if (
SDValue NewSel = foldBinOpIntoSelect(N))
7736 if (!LegalOperations ||
7747 EVT ShiftVT = N1.getValueType();
7753 APInt c2 = RHS->getAPIntValue();
7755 APInt Sum = c1 + c2;
7766 ShiftValue = ShiftValues[0];
7794 if ((ShiftAmt > 0) &&
7844 N1.getOperand(0).getOpcode() ==
ISD::AND) {
7845 if (
SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
7862 if (LargeShift->getAPIntValue() == TruncBits) {
7865 getShiftAmountTy(LargeVT));
7875 if (N1C && SimplifyDemandedBits(
SDValue(N, 0)))
7883 if (
SDValue NewSRA = visitShiftByConstant(N))
7900 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
7908 if (N0C && N1C && !N1C->
isOpaque())
7911 if (
SDValue NewSel = foldBinOpIntoSelect(N))
7924 APInt c2 = RHS->getAPIntValue();
7926 return (c1 + c2).uge(OpSizeInBits);
7934 APInt c2 = RHS->getAPIntValue();
7936 return (c1 + c2).ult(OpSizeInBits);
7951 uint64_t c1 = N001C->getZExtValue();
7958 if (c1 + OpSizeInBits == InnerShiftSize) {
7960 if (c1 + c2 >= InnerShiftSize)
7970 c1 + c2 < InnerShiftSize) {
7991 AddToWorklist(Mask.
getNode());
8010 getShiftAmountTy(SmallVT)));
8011 AddToWorklist(SmallShift.
getNode());
8074 if (N1C && SimplifyDemandedBits(
SDValue(N, 0)))
8078 if (
SDValue NewSRL = visitShiftByConstant(N))
8082 if (
SDValue NarrowLoad = ReduceLoadWidth(N))
8130 return IsFSHL ? N0 : N1;
8132 auto IsUndefOrZero = [](
SDValue V) {
8141 if (Cst->getAPIntValue().uge(BitWidth)) {
8142 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
8147 unsigned ShAmt = Cst->getZExtValue();
8149 return IsFSHL ? N0 : N1;
8155 if (IsUndefOrZero(N0))
8157 DAG.
getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt,
8158 SDLoc(N), ShAmtTy));
8159 if (IsUndefOrZero(N1))
8161 DAG.
getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt,
8162 SDLoc(N), ShAmtTy));
8182 if (N0 == N1 && hasOperation(RotOpc, VT))
8186 if (SimplifyDemandedBits(
SDValue(N, 0)))
8316 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
8332 return DAG.
getNode(IEEEOpcode, DL, VT, LHS, RHS);
8336 return DAG.
getNode(Opcode, DL, VT, LHS, RHS);
8347 return DAG.
getNode(IEEEOpcode, DL, VT, LHS, RHS);
8351 return DAG.
getNode(Opcode, DL, VT, LHS, RHS);
8366 "Expected select-of-constants");
8416 if (CondVT ==
MVT::i1 && !LegalOperations) {
8417 if (C1->isNullValue() && C2->isOne()) {
8424 if (C1->isNullValue() && C2->isAllOnesValue()) {
8431 if (C1->isOne() && C2->isNullValue()) {
8437 if (C1->isAllOnesValue() && C2->isNullValue()) {
8449 const APInt &C1Val = C1->getAPIntValue();
8450 const APInt &C2Val = C2->getAPIntValue();
8451 if (C1Val - 1 == C2Val) {
8457 if (C1Val + 1 == C2Val) {
8493 C1->isNullValue() && C2->isOne()) {
8521 if (
SDValue V = foldSelectOfConstants(N))
8527 AddToWorklist(NOTNode.
getNode());
8533 AddToWorklist(NOTNode.
getNode());
8542 if (SimplifySelectOps(N, N1, N2))
8554 bool normalizeToSequence =
8563 if (normalizeToSequence || !InnerSelect.
use_empty())
8565 InnerSelect, N2, Flags);
8567 if (InnerSelect.use_empty())
8568 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
8575 Cond1, N1, N2, Flags);
8576 if (normalizeToSequence || !InnerSelect.
use_empty())
8578 InnerSelect, Flags);
8580 if (InnerSelect.use_empty())
8581 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
8591 if (!normalizeToSequence) {
8597 if (
SDValue Combined = visitANDLike(N0, N1_0, N)) {
8610 if (!normalizeToSequence) {
8616 if (
SDValue Combined = visitORLike(N0, N2_0, N))
8654 if (
C && NotC &&
C->getAPIntValue() == ~NotC->getAPIntValue()) {
8674 (!LegalOperations &&
8685 return SimplifySelect(DL, N0, N1, N2);
8715 for (
int i = 0; i < NumElems / 2; ++i) {
8719 if (BottomHalf ==
nullptr)
8720 BottomHalf = cast<ConstantSDNode>(Cond.
getOperand(i));
8727 for (
int i = NumElems / 2; i < NumElems; ++i) {
8731 if (TopHalf ==
nullptr)
8732 TopHalf = cast<ConstantSDNode>(Cond.
getOperand(i));
8737 assert(TopHalf && BottomHalf &&
8738 "One half of the selector was all UNDEFs and the other was all the " 8739 "same value. This should have been addressed before this function.");
8770 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8798 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8820 bool AllAddOne =
true;
8821 bool AllSubOne =
true;
8823 for (
unsigned i = 0; i != Elts; ++i) {
8829 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
8830 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
8840 if (AllAddOne || AllSubOne) {
8906 DL, getShiftAmountTy(VT)));
8908 AddToWorklist(Shift.
getNode());
8939 SetCCWidth != 1 && SetCCWidth < WideWidth &&
8949 EVT WideSetCCVT = getSetCCResultType(WideVT);
8950 SDValue WideSetCC = DAG.
getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
8951 return DAG.
getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
8956 if (SimplifySelectOps(N, N1, N2))
8976 if (
SDValue V = foldVSelectOfConstants(N))
8996 CC,
SDLoc(N),
false)) {
8997 AddToWorklist(SCC.getNode());
8999 if (
ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
9000 if (!SCCC->isNullValue())
9004 }
else if (SCC->isUndef()) {
9012 SCC.getOperand(1), N2, N3, SCC.
getOperand(2));
9013 SelectOp->
setFlags(SCC->getFlags());
9019 if (SimplifySelectOps(N, N2, N3))
9023 return SimplifySelectCC(
SDLoc(N), N0, N1, N2, N3, CC);
9033 SDValue Combined = SimplifySetCC(
9035 cast<CondCodeSDNode>(N->
getOperand(2))->
get(),
SDLoc(N), !PreferSetCC);
9043 SDValue NewSetCC = rebuildSetCC(Combined);
9085 &&
"Expected EXTEND dag node in input!");
9090 if (isa<ConstantSDNode>(N0))
9091 return DAG.
getNode(Opcode, DL, VT, N0);
9099 if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
9110 unsigned FoldOpc = Opcode;
9114 DAG.
getNode(FoldOpc, DL, VT, Op1),
9115 DAG.
getNode(FoldOpc, DL, VT, Op2));
9138 for (
unsigned i = 0; i != NumElts; ++i) {
9148 APInt C = cast<ConstantSDNode>(
Op)->getAPIntValue().zextOrTrunc(EVTBits);
9166 bool HasCopyToRegUses =
false;
9174 if (UI.getUse().getResNo() != N0.
getResNo())
9183 for (
unsigned i = 0; i != 2; ++i) {
9187 if (!isa<ConstantSDNode>(UseOp))
9201 HasCopyToRegUses =
true;
9204 if (HasCopyToRegUses) {
9205 bool BothLiveOut =
false;
9217 return ExtendNodes.
size();
9227 for (
SDNode *SetCC : SetCCs) {
9230 for (
unsigned j = 0; j != 2; ++j) {
9232 if (SOp == OrigLoad)
9251 "Unexpected node type (not an extend)!");
9289 EVT SplitSrcVT = SrcVT;
9290 EVT SplitDstVT = DstVT;
9303 const unsigned NumSplits =
9310 for (
unsigned Idx = 0; Idx < NumSplits; Idx++) {
9311 const unsigned Offset = Idx * Stride;
9322 Chains.
push_back(SplitLoad.getValue(1));
9329 AddToWorklist(NewChain.
getNode());
9331 CombineTo(N, NewValue);
9338 CombineTo(N0.
getNode(), Trunc, NewChain);
9344 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(
SDNode *N) {
9399 Mask = Mask.
zext(VT.getSizeInBits());
9411 CombineTo(Load, Trunc, ExtLoad.
getValue(1));
9415 recursivelyDeleteUnusedNodes(N0.
getNode());
9424 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(
SDNode *Cast) {
9425 unsigned CastOpcode = Cast->
getOpcode();
9429 "Unexpected opcode for vector select narrowing/widening");
9459 CastA = DAG.
getNode(CastOpcode, DL, VT, A);
9460 CastB = DAG.
getNode(CastOpcode, DL, VT, B);
9469 bool LegalOperations,
SDNode *N,
9480 if ((LegalOperations || !LN0->
isSimple() ||
9488 Combiner.CombineTo(N, ExtLoad);
9491 Combiner.recursivelyDeleteUnusedNodes(LN0);
9505 ((LegalOperations || VT.
isVector() ||
9506 !cast<LoadSDNode>(N0)->
isSimple()) &&
9510 bool DoXform =
true;
9523 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc);
9526 Combiner.CombineTo(N, ExtLoad);
9527 if (NoReplaceTrunc) {
9529 Combiner.recursivelyDeleteUnusedNodes(LN0);
9533 Combiner.CombineTo(LN0, Trunc, ExtLoad.
getValue(1));
9567 bool LegalOperations) {
9596 return DAG.
getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
9620 if (NarrowLoad.getNode() != N0.
getNode()) {
9621 CombineTo(N0.
getNode(), NarrowLoad);
9636 if (OpBits == DestBits) {
9639 if (NumSignBits > DestBits-MidBits)
9641 }
else if (OpBits < DestBits) {
9644 if (NumSignBits > OpBits-MidBits)
9649 if (NumSignBits > OpBits-MidBits)
9656 if (OpBits < DestBits)
9658 else if (OpBits > DestBits)
9678 if (
SDValue ExtLoad = CombineExtLoad(N))
9683 DAG, *
this, TLI, VT, LegalOperations, N, N0,
ISD::SEXTLOAD))
9710 bool NoReplaceTruncAnd = !N0.
hasOneUse();
9714 if (NoReplaceTruncAnd) {
9717 CombineTo(N0.
getNode(), TruncAnd);
9719 if (NoReplaceTrunc) {
9724 CombineTo(LN00, Trunc, ExtLoad.
getValue(1));
9742 if (VT.
isVector() && !LegalOperations &&
9748 EVT SVT = getSetCCResultType(N00VT);
9758 return DAG.
getSetCC(DL, VT, N00, N01, CC);
9764 if (SVT == MatchingVecType) {
9783 SDValue ExtTrueVal = (SetCCWidth == 1)
9788 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC,
true))
9792 EVT SetCCVT = getSetCCResultType(N00VT);
9800 return DAG.
getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
9810 if (
SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
9865 return (Known.
Zero | 1).isAllOnesValue();
9910 APInt TruncatedBits =
9927 if (NarrowLoad.getNode() != N0.
getNode()) {
9928 CombineTo(N0.
getNode(), NarrowLoad);
9994 if (
SDValue ExtLoad = CombineExtLoad(N))
10010 bool DoXform =
true;
10014 auto *AndC = cast<ConstantSDNode>(N0.
getOperand(1));
10017 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
10029 APInt Mask = cast<ConstantSDNode>(N0.
getOperand(1))->getAPIntValue();
10035 bool NoReplaceTruncAnd = !N0.
hasOneUse();
10039 if (NoReplaceTruncAnd) {
10042 CombineTo(N0.
getNode(), TruncAnd);
10044 if (NoReplaceTrunc) {
10049 CombineTo(LN00, Trunc, ExtLoad.
getValue(1));
10058 if (
SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
10063 DAG, *
this, TLI, VT, LegalOperations, N, N0,
ISD::ZEXTLOAD))
10071 if (!LegalOperations && VT.
isVector() &&
10104 if (
SDValue SCC = SimplifySelectCC(
10107 cast<CondCodeSDNode>(N0.
getOperand(2))->
get(),
true))
10123 if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits))
10138 if (
SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10167 if (NarrowLoad.getNode() != N0.
getNode()) {
10168 CombineTo(N0.
getNode(), NarrowLoad);
10170 AddToWorklist(oye);
10190 APInt Mask = cast<ConstantSDNode>(N0.
getOperand(1))->getAPIntValue();
10203 bool DoXform =
true;
10217 CombineTo(N, ExtLoad);
10218 if (NoReplaceTrunc) {
10220 recursivelyDeleteUnusedNodes(LN0);
10224 CombineTo(LN0, Trunc, ExtLoad.
getValue(1));
10238 if (!LegalOperations || TLI.
isLoadExtLegal(ExtType, VT, MemVT)) {
10242 CombineTo(N, ExtLoad);
10244 recursivelyDeleteUnusedNodes(LN0);
10255 if (VT.
isVector() && !LegalOperations) {
10268 cast<CondCodeSDNode>(N0.
getOperand(2))->
get());
10277 cast<CondCodeSDNode>(N0.
getOperand(2))->
get());
10283 if (
SDValue SCC = SimplifySelectCC(
10286 cast<CondCodeSDNode>(N0.
getOperand(2))->
get(),
true))
10300 EVT AssertVT = cast<VTSDNode>(N1)->getVT();
10304 AssertVT == cast<VTSDNode>(N0.
getOperand(1))->getVT())
10315 EVT BigA_AssertVT = cast<VTSDNode>(BigA.
getOperand(1))->getVT();
10317 "Asserting zero/sign-extended bits to a type larger than the " 10318 "truncated destination does not provide information");
10321 EVT MinAssertVT = AssertVT.
bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
10335 EVT BigA_AssertVT = cast<VTSDNode>(BigA.
getOperand(1))->getVT();
10337 "Asserting zero/sign-extended bits to a type larger than the " 10338 "truncated destination does not provide information");
10340 if (AssertVT.bitsLT(BigA_AssertVT)) {
10369 unsigned ShAmt = 0;
10370 bool HasShiftedOffset =
false;
10375 ExtVT = cast<VTSDNode>(N->
getOperand(1))->getVT();
10388 uint64_t ShiftAmt = N01->getZExtValue();
10389 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
10390 if (LN0->getExtensionType() !=
ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
10402 unsigned ActiveBits = 0;
10409 HasShiftedOffset =
true;
10419 if (
auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.
getOperand(1))) {
10420 ShAmt = ConstShift->getZExtValue();
10423 if ((ShAmt & (EVTBits-1)) == 0) {
10431 if (!isa<LoadSDNode>(N0))
return SDValue();
10433 auto *LN0 = cast<LoadSDNode>(N0);
10444 if (ShAmt >= LN0->getMemoryVT().getSizeInBits())
10452 const APInt &ShiftMask =
10453 cast<ConstantSDNode>(Mask->
getOperand(1))->getAPIntValue();
10454 if (ShiftMask.
isMask()) {
10468 unsigned ShLeftAmt = 0;
10472 ShLeftAmt = N01->getZExtValue();
10478 if (!isa<LoadSDNode>(N0))
10485 !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
10488 auto AdjustBigEndianShift = [&](
unsigned ShAmt) {
10491 return LVTStoreBits - EVTStoreBits - ShAmt;
10497 ShAmt = AdjustBigEndianShift(ShAmt);
10499 uint64_t PtrOff = ShAmt / 8;
10507 AddToWorklist(NewPtr.
getNode());
10521 WorklistRemover DeadNodes(*
this);
10526 if (ShLeftAmt != 0) {
10538 Result, DAG.
getConstant(ShLeftAmt, DL, ShImmTy));
10541 if (HasShiftedOffset) {
10545 ShAmt = AdjustBigEndianShift(ShAmt);
10564 EVT EVT = cast<VTSDNode>(N1)->getVT();
10592 if ((N00Bits <= EVTBits ||
10603 if (!LegalOperations ||
10624 if (SimplifyDemandedBits(
SDValue(N, 0)))
10629 if (
SDValue NarrowLoad = ReduceLoadWidth(N))
10636 if (
auto *ShAmt = dyn_cast<ConstantSDNode>(N0.
getOperand(1)))
10637 if (ShAmt->getAPIntValue().ule(VTBits - EVTBits)) {
10641 if (((VTBits - EVTBits) - ShAmt->getZExtValue()) < InSignBits)
10653 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
10654 ((!LegalOperations && cast<LoadSDNode>(N0)->
isSimple() &&
10662 CombineTo(N, ExtLoad);
10663 CombineTo(N0.
getNode(), ExtLoad, ExtLoad.getValue(1));
10664 AddToWorklist(ExtLoad.getNode());
10670 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
10671 ((!LegalOperations && cast<LoadSDNode>(N0)->
isSimple()) &&
10678 CombineTo(N, ExtLoad);
10679 CombineTo(N0.
getNode(), ExtLoad, ExtLoad.getValue(1));
10694 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(
SDNode *N) {
10704 if (SimplifyDemandedVectorElts(
SDValue(N, 0)))
10710 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(
SDNode *N) {
10720 if (SimplifyDemandedVectorElts(
SDValue(N, 0)))
10789 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
10790 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10792 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
10827 AddToWorklist(Amt.
getNode());
10859 if (BuildVectEltTy == TruncVecEltTy) {
10863 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
10865 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
10866 "Invalid number of elements");
10869 for (
unsigned i = 0,
e = BuildVecNumElts; i !=
e; i += TruncEltOffset)
10891 if (
SDValue Reduced = ReduceLoadWidth(N))
10916 unsigned NumDefs = 0;
10936 if (NumDefs == 1) {
10937 assert(V.
getNode() &&
"The single defined operand is empty!");
10939 for (
unsigned i = 0,
e = VTs.
size(); i !=
e; ++i) {
10946 Opnds.push_back(NV);
10960 (!LegalOperations ||
10973 SimplifyDemandedBits(
SDValue(N, 0)))
11007 if (
SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11021 if (!LegalOperations && N0.
hasOneUse() &&
11061 LD1->getAddressSpace() != LD2->getAddressSpace())
11063 EVT LD1VT = LD1->getValueType(0);
11067 unsigned Align = LD1->getAlignment();
11071 if (NewAlign <= Align &&
11073 return DAG.
getLoad(VT,
SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
11074 LD1->getPointerInfo(),
Align);
11130 NumFPLogicOpsConv++;
11158 return ConstantFoldBITCASTofBUILD_VECTOR(N0.
getNode(),
11162 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
11166 if (!LegalOperations ||
11192 ((!LegalOperations && cast<LoadSDNode>(N0)->
isSimple()) ||
11227 AddToWorklist(NewConv.
getNode());
11237 AddToWorklist(FlipBit.
getNode());
11244 AddToWorklist(Hi.getNode());
11246 AddToWorklist(FlipBit.getNode());
11250 AddToWorklist(FlipBits.getNode());
11278 if (isTypeLegal(IntXVT)) {
11284 if (OrigXWidth < VTWidth) {
11287 }
else if (OrigXWidth > VTWidth) {
11297 AddToWorklist(X.getNode());
11303 AddToWorklist(Cst.getNode());
11305 AddToWorklist(X.getNode());
11307 AddToWorklist(XorResult.getNode());
11311 SDLoc(XorResult)));
11312 AddToWorklist(XorResult64.getNode());
11316 AddToWorklist(FlipBit.getNode());
11319 AddToWorklist(FlipBits.getNode());
11325 AddToWorklist(X.getNode());
11330 AddToWorklist(Cst.getNode());
11338 if (
SDValue CombineLD = CombineConsecutiveLoads(N0.
getNode(), VT))
11353 auto PeekThroughBitcast = [&](
SDValue Op) {
11375 for (
int i = 0; i != MaskScale; ++i)
11376 NewMask.
push_back(M < 0 ? -1 : M * MaskScale + i);
11381 return LegalShuffle;
11389 return CombineConsecutiveLoads(N, VT);
11395 ConstantFoldBITCASTofBUILD_VECTOR(
SDNode *BV,
EVT DstEltVT) {
11399 if (SrcEltVT == DstEltVT)
return SDValue(BV, 0);
11406 if (SrcBitSize == DstBitSize) {
11414 AddToWorklist(Ops.
back().getNode());
11428 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
11436 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
11439 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
11447 if (SrcBitSize < DstBitSize) {
11448 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
11452 i += NumInputsPerOutput) {
11455 bool EltIsUndef =
true;
11456 for (
unsigned j = 0; j != NumInputsPerOutput; ++j) {
11458 NewBits <<= SrcBitSize;
11461 EltIsUndef =
false;
11463 NewBits |= cast<ConstantSDNode>(
Op)->getAPIntValue().
11464 zextOrTrunc(SrcBitSize).
zext(DstBitSize);
11479 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
11490 APInt OpVal = cast<ConstantSDNode>(
Op)->
11493 for (
unsigned j = 0; j != NumOutputsPerInput; ++j) {
11495 Ops.push_back(DAG.
getConstant(ThisVal, DL, DstEltVT));
11501 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
11530 if (!HasFMAD && !HasFMA)
11536 CanFuse || HasFMAD);
11551 auto isContractableFMUL = [AllowFusionGlobally](
SDValue N) {
11558 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
11564 if (isContractableFMUL(N0) && (Aggressive || N0->
hasOneUse())) {
11565 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11571 if (isContractableFMUL(N1) && (Aggressive || N1->
hasOneUse())) {
11572 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11581 if (isContractableFMUL(N00) &&
11584 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11596 if (isContractableFMUL(N10) &&
11599 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11611 N0.
getOpcode() == PreferredFusedOpcode &&
11614 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11616 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11619 N1, Flags), Flags);
11624 N1->
getOpcode() == PreferredFusedOpcode &&
11627 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11629 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11632 N0, Flags), Flags);
11638 auto FoldFAddFMAFPExtFMul = [&] (
11641 return DAG.
getNode(PreferredFusedOpcode, SL, VT, X, Y,
11642 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11647 if (N0.
getOpcode() == PreferredFusedOpcode) {
11651 if (isContractableFMUL(N020) &&
11666 auto FoldFAddFPExtFMAFMul = [&] (
11669 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11672 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11679 if (N00.
getOpcode() == PreferredFusedOpcode) {
11681 if (isContractableFMUL(N002) &&
11693 if (N1.
getOpcode() == PreferredFusedOpcode) {
11697 if (isContractableFMUL(N120) &&
11714 if (N10.
getOpcode() == PreferredFusedOpcode) {
11716 if (isContractableFMUL(N102) &&
11747 if (!HasFMAD && !HasFMA)
11753 CanFuse || HasFMAD);
11769 auto isContractableFMUL = [AllowFusionGlobally](
SDValue N) {
11776 if (isContractableFMUL(N0) && (Aggressive || N0->
hasOneUse())) {
11777 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11784 if (isContractableFMUL(N1) && (Aggressive || N1->
hasOneUse())) {
11785 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11796 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11807 if (isContractableFMUL(N00) &&
11810 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11824 if (isContractableFMUL(N10) &&
11827 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11847 if (isContractableFMUL(N000) &&
11851 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11871 if (isContractableFMUL(N000) &&
11875 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11889 if (CanFuse && N0.
getOpcode() == PreferredFusedOpcode &&
11892 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11894 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11898 N1), Flags), Flags);
11903 if (CanFuse && N1.
getOpcode() == PreferredFusedOpcode &&
11908 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11912 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11914 N21, N0, Flags), Flags);
11920 if (N0.
getOpcode() == PreferredFusedOpcode &&
11925 if (isContractableFMUL(N020) &&
11928 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11930 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11936 N1), Flags), Flags);
11949 if (N00.
getOpcode() == PreferredFusedOpcode) {
11951 if (isContractableFMUL(N002) &&
11954 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11959 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11965 N1), Flags), Flags);
11972 if (N1.
getOpcode() == PreferredFusedOpcode &&
11976 if (isContractableFMUL(N120) &&
11981 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
11984 DAG.
getNode(PreferredFusedOpcode, SL, VT,
11990 N0, Flags), Flags);
12006 if (isContractableFMUL(N102) &&
12011 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
12016 DAG.
getNode(PreferredFusedOpcode, SL, VT,
12022 N0, Flags), Flags);
12033 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(
SDNode *N) {
12046 if (!Options.NoInfsFPMath)
12057 bool HasFMAD = Options.UnsafeFPMath &&
12061 if (!HasFMAD && !HasFMA)
12073 if (
C->isExactlyValue(+1.0))
12076 if (
C->isExactlyValue(-1.0))
12096 if (C0->isExactlyValue(+1.0))
12097 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
12100 if (C0->isExactlyValue(-1.0))
12101 return DAG.
getNode(PreferredFusedOpcode, SL, VT,
12106 if (C1->isExactlyValue(+1.0))
12109 if (C1->isExactlyValue(-1.0))
12137 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
12141 if (N0CFP && N1CFP)
12145 if (N0CFP && !N1CFP)
12150 if (N1C && N1C->
isZero())
12154 if (
SDValue NewSel = foldBinOpIntoSelect(N))
12171 auto isFMulNegTwo = [](
SDValue FMul) {
12172 if (!FMul.hasOneUse() || FMul.getOpcode() !=
ISD::FMUL)
12175 return C &&
C->isExactlyValue(-2.0);
12179 if (isFMulNegTwo(N0)) {
12185 if (isFMulNegTwo(N1)) {
12228 if (CFP01 && !CFP00 && N0.
getOperand(0) == N1) {
12249 if (CFP11 && !CFP10 && N1.
getOperand(0) == N0) {
12297 if (
SDValue Fused = visitFADDForFMACombine(N)) {
12298 AddToWorklist(Fused.getNode());
12316 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
12320 if (N0CFP && N1CFP)
12323 if (
SDValue NewSel = foldBinOpIntoSelect(N))
12327 if (N1CFP && N1CFP->
isZero()) {
12345 if (N0CFP && N0CFP->
isZero()) {
12373 if (
SDValue Fused = visitFSUBForFMACombine(N)) {
12374 AddToWorklist(Fused.getNode());
12390 if (LHSNeg == 2 || RHSNeg == 2)
12409 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
12414 if (N0CFP && N1CFP)
12422 if (
SDValue NewSel = foldBinOpIntoSelect(N))
12428 if (N1CFP && N1CFP->
isZero())
12467 if (isCheaperToUseNegatedFPOps(N0, N1)) {
12488 if (TrueOpnd && FalseOpnd &&
12490 isa<ConstantFPSDNode>(Cond.
getOperand(1)) &&
12491 cast<ConstantFPSDNode>(Cond.
getOperand(1))->isExactlyValue(0.0)) {
12509 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
12513 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
12522 if (
SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
12523 AddToWorklist(Fused.getNode());
12545 if (isa<ConstantFPSDNode>(N0) &&
12546 isa<ConstantFPSDNode>(N1) &&
12547 isa<ConstantFPSDNode>(N2)) {
12552 if (isCheaperToUseNegatedFPOps(N0, N1)) {
12560 if (UnsafeFPMath) {
12561 if (N0CFP && N0CFP->
isZero())
12563 if (N1CFP && N1CFP->isZero())
12569 if (N1CFP && N1CFP->isExactlyValue(1.0))
12577 if (UnsafeFPMath) {
12602 if (N1CFP->isExactlyValue(1.0))
12606 if (N1CFP->isExactlyValue(-1.0) &&
12609 AddToWorklist(RHSNeg.
getNode());
12624 if (UnsafeFPMath) {
12626 if (N1CFP && N0 == N2) {
12649 LegalOperations, ForCodeSize),
12661 SDValue DAGCombiner::combineRepeatedFPDivisors(
SDNode *N) {
12683 unsigned NumElts = 1;
12688 if (!MinUses || (N1->
use_size() * NumElts) < MinUses)
12694 for (
auto *U : N1->
uses()) {
12695 if (U->getOpcode() ==
ISD::FDIV && U->getOperand(1) == N1) {
12698 if (UnsafeMath || U->getFlags().hasAllowReciprocal())
12705 if ((Users.
size() * NumElts) < MinUses)
12713 for (
auto *U : Users) {
12715 if (Dividend != FPOne) {
12717 Reciprocal, Flags);
12718 CombineTo(U, NewNode);
12719 }
else if (U != Reciprocal.
getNode()) {
12722 CombineTo(U, Reciprocal);
12740 if (
SDValue FoldedVOp = SimplifyVBinOp(N))
12744 if (N0CFP && N1CFP)
12747 if (
SDValue NewSel = foldBinOpIntoSelect(N))
12750 if (
SDValue V = combineRepeatedFPDivisors(N))
12757 const APFloat &N1APF = N1CFP->getValueAPF();
12763 (!LegalOperations ||
12783 AddToWorklist(RV.getNode());
12791 AddToWorklist(RV.getNode());
12811 AddToWorklist(RV.getNode());
12818 if (
SDValue RV = BuildDivEstimate(N0, N1, Flags))
12823 if (isCheaperToUseNegatedFPOps(N0, N1))
12840 if (N0CFP && N1CFP)
12843 if (
SDValue NewSel = foldBinOpIntoSelect(N))
12860 return buildSqrtEstimate(N0, Flags);
12875 return (N1VT == N1Op0VT || N1Op0VT !=
MVT::f128);
12887 if (N0CFP && N1CFP)
12891 const APFloat &V = N1C->getValueAPF();
12966 if (ExponentIs025 || ExponentIs075) {
13050 (!LegalOperations ||
13068 (!LegalOperations ||
13082 (!LegalOperations ||
13111 (!LegalOperations ||
13128 (!LegalOperations ||
13169 unsigned ActualSize = std::min(InputSize, OutputSize);
13262 AddToWorklist(Tmp.
getNode());
13267 if (
SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
13311 CombineTo(N, ExtLoad);
13320 if (
SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
13415 AddToWorklist(Int.
getNode());
13427 if (LegalDAG && (TLI.
isFPImmLegal(CVal, VT, ForCodeSize) ||
13447 if (N0CFP && N1CFP) {
13512 AddToWorklist(Int.
getNode());
13542 if (
SDValue NewN1 = rebuildSetCC(N1))
13582 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
13585 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.
logBase2()) {
13626 bool Equal =
false;
13635 SetCCVT = getSetCCResultType(SetCCVT);
13658 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
13659 CondLHS, CondRHS, CC->
get(),
SDLoc(N),
13682 if (
LD->isIndexed() ||
LD->getBasePtr().getNode() !=
N)
13684 VT =
LD->getMemoryVT();
13685 AS =
LD->getAddressSpace();
13687 if (
ST->isIndexed() ||
ST->getBasePtr().getNode() !=
N)
13689 VT =
ST->getMemoryVT();
13690 AS =
ST->getAddressSpace();
13692 if (
LD->isIndexed() ||
LD->getBasePtr().getNode() !=
N)
13694 VT =
LD->getMemoryVT();
13695 AS =
LD->getAddressSpace();
13697 if (
ST->isIndexed() ||
ST->getBasePtr().getNode() !=
N)
13699 VT =
ST->getMemoryVT();
13700 AS =
ST->getAddressSpace();
13706 AM.HasBaseReg =
true;
13715 AM.HasBaseReg =
true;
13734 if (
LD->isIndexed())
13736 EVT VT =
LD->getMemoryVT();
13739 Ptr =
LD->getBasePtr();
13741 if (
ST->isIndexed())
13743 EVT VT =
ST->getMemoryVT();
13746 Ptr =
ST->getBasePtr();
13749 if (
LD->isIndexed())
13751 EVT VT =
LD->getMemoryVT();
13755 Ptr =
LD->getBasePtr();
13758 if (
ST->isIndexed())
13760 EVT VT =
ST->getMemoryVT();
13764 Ptr =
ST->getBasePtr();
13778 bool DAGCombiner::CombineToPreIndexedLoadStore(
SDNode *N) {
13782 bool IsLoad =
true;
13805 bool Swapped =
false;
13806 if (isa<ConstantSDNode>(BasePtr)) {
13825 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
13830 SDValue Val = IsMasked ? cast<MaskedStoreSDNode>(
N)->getValue()
13831 : cast<StoreSDNode>(
N)->getValue();
13834 if (Val == BasePtr)
13851 if (isa<ConstantSDNode>(Offset))
13871 if (!isa<ConstantSDNode>(Op1)) {
13889 bool RealUse =
false;
13925 WorklistRemover DeadNodes(*
this);
13934 deleteAndRecombine(N);
13940 for (
unsigned i = 0,
e = OtherUses.
size(); i !=
e; ++i) {
13941 unsigned OffsetIdx = 1;
13942 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.
getNode())
13944 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
13945 BasePtr.
getNode() &&
"Expected BasePtr operand");
13959 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
13960 int X0, X1, Y0, Y1;
13961 const APInt &Offset0 = CN->getAPIntValue();
13962 APInt Offset1 = cast<ConstantSDNode>(
Offset)->getAPIntValue();
13964 X0 = (OtherUses[i]->getOpcode() ==
ISD::SUB && OffsetIdx == 1) ? -1 : 1;
13965 Y0 = (OtherUses[i]->getOpcode() ==
ISD::SUB && OffsetIdx == 0) ? -1 : 1;
13971 APInt CNV = Offset0;
13972 if (X0 < 0) CNV = -CNV;
13973 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
13974 else CNV = CNV - Offset1;
13976 SDLoc DL(OtherUses[i]);
13984 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
13986 deleteAndRecombine(OtherUses[i]);
13991 deleteAndRecombine(Ptr.
getNode());
13992 AddToWorklist(Result.
getNode());
14001 bool DAGCombiner::CombineToPostIndexedLoadStore(
SDNode *N) {
14005 bool IsLoad =
true;
14035 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
14039 bool TryNext =
false;
14047 bool RealUse =
false;
14077 BasePtr, Offset, AM);
14080 BasePtr, Offset, AM)
14082 BasePtr, Offset, AM);
14083 ++PostIndexedNodes;
14088 WorklistRemover DeadNodes(*
this);
14097 deleteAndRecombine(N);
14102 deleteAndRecombine(Op);
14122 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
14123 "Cannot split out indexing using opaque target constants");
14143 if (STType == STMemType)
14145 if (isTypeLegal(STMemType))
14168 "Attempting to extend value of non-matching type");
14169 if (LDType == LDMemType)
14230 SDValue Ops[] = {Val, Idx, Chain};
14231 return CombineTo(LD, Ops, 3);
14233 return CombineTo(LD, Val, Chain);
14240 if (Offset == 0 && LDType == STType && STMemType == LDMemType) {
14243 return ReplaceLd(LD, ST->
getValue(), Chain);
14251 SDLoc(ST), STType);
14253 return ReplaceLd(LD, Val, Chain);
14264 if (!getTruncatedStoreValue(ST, Val))
14266 if (!isTypeLegal(LDMemType))
14268 if (STMemType != LDMemType) {
14276 if (!extendLoadedValueToExtension(LD, Val))
14278 return ReplaceLd(LD, Val, Chain);
14283 deleteAndRecombine(Val.
getNode());
14307 dbgs() <<
"\nWith chain: "; Chain.getNode()->dump(&DAG);
14309 WorklistRemover DeadNodes(*
this);
14311 AddUsersToWorklist(Chain.getNode());
14313 deleteAndRecombine(N);
14326 cast<ConstantSDNode>(LD->
getOperand(2))->isOpaque();
14333 Index = SplitIndexingFromLoad(LD);
14336 AddUsersToWorklist(N);
14341 dbgs() <<
" and 2 other values\n");
14342 WorklistRemover DeadNodes(*
this);
14346 deleteAndRecombine(N);
14354 if (
auto V = ForwardStoreValueToDirectLoad(LD))
14374 SDValue BetterChain = FindBetterChain(LD, Chain);
14377 if (Chain != BetterChain) {
14396 return CombineTo(N, ReplLoad.
getValue(0), Token);
14401 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
14406 if (SliceUpLoad(N))
14426 struct LoadedSlice {
14430 bool ForCodeSize =
false;
14433 unsigned Loads = 0;
14434 unsigned Truncates = 0;
14435 unsigned CrossRegisterBanksCopies = 0;
14436 unsigned ZExts = 0;
14437 unsigned Shift = 0;
14439 explicit Cost(
bool ForCodeSize) : ForCodeSize(ForCodeSize) {}
14442 Cost(
const LoadedSlice &
LS,
bool ForCodeSize)
14443 : ForCodeSize(ForCodeSize), Loads(1) {
14444 EVT TruncType = LS.Inst->getValueType(0);
14445 EVT LoadedType = LS.getLoadedType();
14446 if (TruncType != LoadedType &&
14447 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
14455 void addSliceGain(
const LoadedSlice &LS) {
14459 LS.Inst->getValueType(0)))
14465 if (LS.canMergeExpensiveCrossRegisterBankCopy())
14466 ++CrossRegisterBanksCopies;
14470 Loads += RHS.Loads;
14471 Truncates += RHS.Truncates;
14472 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
14473 ZExts += RHS.ZExts;
14474 Shift += RHS.Shift;
14479 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
14480 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
14481 ZExts == RHS.ZExts && Shift == RHS.Shift;
14484 bool operator!=(
const Cost &RHS)
const {
return !(*
this == RHS); }
14486 bool operator<(
const Cost &RHS)
const {
14489 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
14490 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
14493 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
14494 return ExpensiveOpsLHS < ExpensiveOpsRHS;
14495 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
14496 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
14499 bool operator>(
const Cost &RHS)
const {
return RHS < *
this; }
14501 bool operator<=(
const Cost &RHS)
const {
return !(RHS < *
this); }
14503 bool operator>=(
const Cost &RHS)
const {
return !(*
this < RHS); }
14522 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
14527 APInt getUsedBits()
const {
14532 assert(Origin &&
"No original load to compare against.");
14534 assert(Inst &&
"This slice is not bound to an instruction");
14536 "Extracted slice is bigger than the whole type!");
14539 UsedBits = UsedBits.zext(BitWidth);
14540 UsedBits <<= Shift;
14545 unsigned getLoadedSize()
const {
14546 unsigned SliceSize = getUsedBits().countPopulation();
14547 assert(!(SliceSize & 0x7) &&
"Size is not a multiple of a byte.");
14548 return SliceSize / 8;
14553 EVT getLoadedType()
const {
14554 assert(DAG &&
"Missing context");
14562 uint64_t
Offset = getOffsetFromBase();
14564 Alignment =
MinAlign(Alignment, Alignment + Offset);
14569 bool isLegal()
const {
14571 if (!Origin || !Inst || !DAG)
14581 EVT SliceType = getLoadedType();
14605 if (TruncateType != SliceType &&
14615 uint64_t getOffsetFromBase()
const {
14616 assert(DAG &&
"Missing context.");
14618 assert(!(Shift & 0x7) &&
"Shifts not aligned on Bytes are not supported.");
14619 uint64_t
Offset = Shift / 8;
14622 "The size of the original loaded type is not a multiple of a" 14626 assert(TySizeInBytes > Offset &&
14627 "Invalid shift amount for given loaded size");
14629 Offset = TySizeInBytes - Offset - getLoadedSize();
14640 assert(Inst && Origin &&
"Unable to replace a non-existing slice.");
14642 SDValue BaseAddr = OldBaseAddr;
14644 int64_t
Offset =
static_cast<int64_t
>(getOffsetFromBase());
14645 assert(Offset >= 0 &&
"Offset too big to fit in int64_t!");
14655 EVT SliceType = getLoadedType();
14665 if (SliceType != FinalType)
14675 bool canMergeExpensiveCrossRegisterBankCopy()
const {
14681 assert(DAG &&
"Missing context");
14742 const LoadedSlice &Second) {
14743 assert(First.Origin == Second.Origin && First.Origin &&
14744 "Unable to match different memory origins.");
14745 APInt UsedBits = First.getUsedBits();
14746 assert((UsedBits & Second.getUsedBits()) == 0 &&
14747 "Slices are not supposed to overlap.");
14748 UsedBits |= Second.getUsedBits();
14757 LoadedSlice::Cost &GlobalLSCost) {
14758 unsigned NumberOfSlices = LoadedSlices.
size();
14760 if (NumberOfSlices < 2)
14765 llvm::sort(LoadedSlices, [](
const LoadedSlice &LHS,
const LoadedSlice &RHS) {
14766 assert(LHS.Origin == RHS.Origin &&
"Different bases not implemented.");
14767 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
14769 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
14772 const LoadedSlice *First =
nullptr;
14773 const LoadedSlice *Second =
nullptr;
14774 for (
unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
14777 Second = &LoadedSlices[CurrSlice];
14784 EVT LoadedType = First->getLoadedType();
14787 if (LoadedType != Second->getLoadedType())
14791 unsigned RequiredAlignment = 0;
14792 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
14798 if (RequiredAlignment > First->getAlignment())
14805 assert(GlobalLSCost.Loads > 0 &&
"We save more loads than we created!");
14806 --GlobalLSCost.Loads;
14823 const APInt &UsedBits,
bool ForCodeSize) {
14824 unsigned NumberOfSlices = LoadedSlices.
size();
14826 return NumberOfSlices > 1;
14829 if (NumberOfSlices != 2)
14837 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
14839 OrigCost.Loads = 1;
14840 for (
unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
14841 const LoadedSlice &
LS = LoadedSlices[CurrSlice];
14843 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
14844 GlobalSlicingCost += SliceCost;
14848 OrigCost.addSliceGain(LS);
14853 return OrigCost > GlobalSlicingCost;
14862 bool DAGCombiner::SliceUpLoad(
SDNode *N) {
14881 UI != UIEnd; ++UI) {
14883 if (UI.getUse().getResNo() != 0)
14887 unsigned Shift = 0;
14910 LoadedSlice
LS(User, LD, Shift, &DAG);
14911 APInt CurrentUsedBits = LS.getUsedBits();
14914 if ((CurrentUsedBits & UsedBits) != 0)
14917 UsedBits |= CurrentUsedBits;
14924 LoadedSlices.push_back(LS);
14939 LSIt = LoadedSlices.begin(),
14940 LSItEnd = LoadedSlices.end();
14941 LSIt != LSItEnd; ++LSIt) {
14942 SDValue SliceInst = LSIt->loadSlice();
14943 CombineTo(LSIt->Inst, SliceInst,
true);
14947 "It takes more than a zext to get to the loaded slice!!");
14954 AddToWorklist(Chain.
getNode());
14961 static std::pair<unsigned, unsigned>
14963 std::pair<unsigned, unsigned> Result(0, 0);
14984 uint64_t NotMask = ~cast<ConstantSDNode>(V->
getOperand(1))->getSExtValue();
14986 if (NotMaskLZ & 7)
return Result;
14988 if (NotMaskTZ & 7)
return Result;
14989 if (NotMaskLZ == 64)
return Result;
15000 switch (MaskedBytes) {
15004 default:
return Result;
15009 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes)
return Result;
15023 Result.first = MaskedBytes;
15024 Result.second = NotMaskTZ/8;
15035 unsigned NumBytes = MaskInfo.first;
15036 unsigned ByteShift = MaskInfo.second;
15042 ByteShift*8, (ByteShift+NumBytes)*8);
15050 if (!DC->isTypeLegal(VT))
15071 StOffset = ByteShift;
15079 NewAlign =
MinAlign(NewAlign, StOffset);
15116 std::pair<unsigned, unsigned> MaskedLoad;
15118 if (MaskedLoad.first)
15125 if (MaskedLoad.first)
15147 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
15158 while (NewBW < BitWidth &&
15165 if (NewBW >= BitWidth)
15171 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
15173 std::min(BitWidth, ShAmt + NewBW));
15174 if ((Imm & Mask) == Imm) {
15178 uint64_t PtrOff = ShAmt / 8;
15182 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
15201 AddToWorklist(NewPtr.
getNode());
15202 AddToWorklist(NewLD.
getNode());
15203 AddToWorklist(NewVal.
getNode());
15204 WorklistRemover DeadNodes(*
this);
15221 Value.hasOneUse()) {
15224 if (!VT.isFloatingPoint() ||
15243 if (LDAlign < ABIAlign || STAlign < ABIAlign)
15254 AddToWorklist(NewLD.
getNode());
15255 AddToWorklist(NewST.
getNode());
15256 WorklistRemover DeadNodes(*
this);
15278 bool DAGCombiner::isMulAddWithConstProfitable(
SDNode *MulNode,
15289 if (
Use == MulNode)
15297 if (
Use->getOperand(0) == ConstNode)
15298 OtherOp =
Use->getOperand(1).getNode();
15300 OtherOp =
Use->getOperand(0).getNode();
15312 if (OtherOp == MulVar)
15340 unsigned NumStores) {
15343 SDLoc StoreDL(StoreNodes[0].MemNode);
15345 for (
unsigned i = 0; i < NumStores; ++i) {
15346 Visited.
insert(StoreNodes[i].MemNode);
15350 for (
unsigned i = 0; i < NumStores; ++i) {
15351 if (Visited.
insert(StoreNodes[i].MemNode->getChain().getNode()).
second)
15352 Chains.
push_back(StoreNodes[i].MemNode->getChain());
15355 assert(Chains.
size() > 0 &&
"Chain should have generated a chain");
15359 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
15361 bool IsConstantSrc,
bool UseVector,
bool UseTrunc) {
15367 SDLoc DL(StoreNodes[0].MemNode);
15370 unsigned SizeInBits = NumStores * ElementSizeBits;
15375 unsigned Elts = NumStores * NumMemElts;
15383 if (IsConstantSrc) {
15385 for (
unsigned I = 0;
I != NumStores; ++
I) {
15386 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[
I].MemNode);
15389 if (MemVT != Val.getValueType()) {
15392 if (ElementSizeBits != Val.getValueSizeInBits()) {
15395 if (isa<ConstantFPSDNode>(Val)) {
15398 }
else if (
auto *
C = dyn_cast<ConstantSDNode>(Val))
15400 .zextOrTrunc(Val.getValueSizeInBits())
15401 .zextOrTrunc(ElementSizeBits),
15411 DL, StoreTy, BuildVector);
15414 for (
unsigned i = 0; i < NumStores; ++i) {
15415 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
15423 if ((MemVT != Val.getValueType()) &&
15449 assert(IsConstantSrc &&
"Merged vector elements should use vector store");
15451 APInt StoreInt(SizeInBits, 0);
15456 for (
unsigned i = 0; i < NumStores; ++i) {
15457 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
15458 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
15460 SDValue Val = St->getValue();
15462 StoreInt <<= ElementSizeBits;
15464 StoreInt |=
C->getAPIntValue()
15465 .zextOrTrunc(ElementSizeBits)
15466 .zextOrTrunc(SizeInBits);
15468 StoreInt |=
C->getValueAPF()
15470 .zextOrTrunc(ElementSizeBits)
15471 .zextOrTrunc(SizeInBits);
15481 StoredVal = DAG.
getConstant(StoreInt, DL, StoreTy);
15485 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
15494 EVT LegalizedStoredValTy =
15496 unsigned LegalizedStoreSize = LegalizedStoredValTy.
getSizeInBits();
15500 LegalizedStoredValTy);
15502 NewChain, DL, ExtendedStoreVal, FirstInChain->
getBasePtr(),
15509 for (
unsigned i = 0; i < NumStores; ++i)
15510 CombineTo(StoreNodes[i].MemNode, NewStore);
15512 AddToWorklist(NewChain.
getNode());
15516 void DAGCombiner::getStoreMergeCandidates(
15533 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
15536 bool IsLoadSrc = isa<LoadSDNode>(Val);
15541 auto *Ld = cast<LoadSDNode>(Val);
15543 LoadVT = Ld->getMemoryVT();
15545 if (MemVT != LoadVT)
15548 if (!Ld->hasNUsesOfValue(1, 0))
15552 if (!Ld->isSimple() || Ld->isIndexed())
15556 int64_t &
Offset) ->
bool {
15572 if (
LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(OtherBC)) {
15574 if (LoadVT != OtherLd->getMemoryVT())
15577 if (!OtherLd->hasNUsesOfValue(1, 0))
15581 if (!OtherLd->isSimple() ||
15582 OtherLd->isIndexed())
15585 if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal())
15587 if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
15592 if (IsConstantSrc) {
15595 if (!(isa<ConstantSDNode>(OtherBC) || isa<ConstantFPSDNode>(OtherBC)))
15598 if (IsExtractVecSrc) {
15614 auto OverLimitInDependenceCheck = [&](
SDNode *StoreNode,
15615 SDNode *RootNode) ->
bool {
15616 auto RootCount = StoreRootCountMap.
find(StoreNode);
15617 if (RootCount != StoreRootCountMap.
end() &&
15618 RootCount->second.first == RootNode &&
15642 unsigned NumNodesExplored = 0;
15643 if (
LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
15644 RootNode = Ldn->getChain().getNode();
15646 I !=
E && NumNodesExplored < 1024; ++
I, ++NumNodesExplored)
15647 if (
I.getOperandNo() == 0 && isa<LoadSDNode>(*I))
15648 for (
auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
15649 if (I2.getOperandNo() == 0)
15650 if (
StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
15653 if (CandidateMatch(OtherST, Ptr, PtrDiff) &&
15654 !OverLimitInDependenceCheck(OtherST, RootNode))
15655 StoreNodes.
push_back(MemOpLink(OtherST, PtrDiff));
15659 I !=
E && NumNodesExplored < 1024; ++
I, ++NumNodesExplored)
15660 if (
I.getOperandNo() == 0)
15661 if (
StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*
I)) {
15664 if (CandidateMatch(OtherST, Ptr, PtrDiff) &&
15665 !OverLimitInDependenceCheck(OtherST, RootNode))
15666 StoreNodes.
push_back(MemOpLink(OtherST, PtrDiff));
15675 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
15691 while (!Worklist.
empty()) {
15693 if (!Visited.
insert(N).second)
15702 unsigned int Max = 1024 + Visited.
size();
15704 for (
unsigned i = 0; i < NumStores; ++i) {
15705 SDNode *N = StoreNodes[i].MemNode;
15721 for (
unsigned i = 0; i < NumStores; ++i)
15727 if (Visited.
size() >= Max) {
15728 auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode];
15729 if (RootCount.first == RootNode)
15730 RootCount.second++;
15732 RootCount = {RootNode, 1};
15739 bool DAGCombiner::MergeConsecutiveStores(
StoreSDNode *St) {
15751 Attribute::NoImplicitFloat);
15754 if (ElementSizeBytes * 8 != (int64_t)MemVT.
getSizeInBits())
15763 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
15764 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
15765 isa<ConstantFPSDNode>(StoredVal);
15769 bool IsNonTemporalLoad =
15770 IsLoadSrc && cast<LoadSDNode>(StoredVal)->isNonTemporal();
15772 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
15778 getStoreMergeCandidates(St, StoreNodes, RootNode);
15781 if (StoreNodes.
size() < 2)
15786 llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) {
15787 return LHS.OffsetFromBase < RHS.OffsetFromBase;
15799 while (StoreNodes.
size() > 1) {
15800 size_t StartIdx = 0;
15801 while ((StartIdx + 1 < StoreNodes.
size()) &&
15802 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
15803 StoreNodes[StartIdx + 1].OffsetFromBase)
15807 if (StartIdx + 1 >= StoreNodes.
size())
15815 unsigned NumConsecutiveStores = 1;
15816 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
15819 for (
unsigned i = 1,
e = StoreNodes.
size(); i <
e; ++i) {
15820 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
15821 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
15823 NumConsecutiveStores = i + 1;
15826 if (NumConsecutiveStores < 2) {
15828 StoreNodes.
begin() + NumConsecutiveStores);
15837 if (IsConstantSrc) {
15838 while (NumConsecutiveStores >= 2) {
15841 unsigned FirstStoreAlign = FirstInChain->
getAlignment();
15842 unsigned LastLegalType = 1;
15843 unsigned LastLegalVectorType = 1;
15844 bool LastIntegerTrunc =
false;
15845 bool NonZero =
false;
15846 unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
15847 for (
unsigned i = 0; i < NumConsecutiveStores; ++i) {
15848 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
15850 bool IsElementZero =
false;
15852 IsElementZero =
C->isNullValue();
15854 IsElementZero =
C->getConstantFPValue()->isNullValue();
15855 if (IsElementZero) {
15856 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
15857 FirstZeroAfterNonZero = i;
15859 NonZero |= !IsElementZero;
15862 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
15864 bool IsFast =
false;
15875 LastIntegerTrunc =
false;
15876 LastLegalType = i + 1;
15880 EVT LegalizedStoredValTy =
15888 LastIntegerTrunc =
true;
15889 LastLegalType = i + 1;
15900 unsigned Elts = (i + 1) * NumMemElts;
15905 Context, DL, Ty, *FirstInChain->
getMemOperand(), &IsFast) &&
15907 LastLegalVectorType = i + 1;
15911 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
15912 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
15924 unsigned NumSkip = 1;
15926 (NumSkip < NumConsecutiveStores) &&
15927 (NumSkip < FirstZeroAfterNonZero) &&
15928 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
15932 NumConsecutiveStores -= NumSkip;
15937 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
15940 NumConsecutiveStores -= NumElem;
15944 RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
true,
15945 UseVector, LastIntegerTrunc);
15949 NumConsecutiveStores -= NumElem;
15956 if (IsExtractVecSrc) {
15958 while (NumConsecutiveStores >= 2) {
15961 unsigned FirstStoreAlign = FirstInChain->
getAlignment();
15962 unsigned NumStoresToMerge = 1;
15963 for (
unsigned i = 0; i < NumConsecutiveStores; ++i) {
15965 unsigned Elts = (i + 1) * NumMemElts;
15979 NumStoresToMerge = i + 1;
15984 if (NumStoresToMerge < 2) {
15991 unsigned NumSkip = 1;
15993 (NumSkip < NumConsecutiveStores) &&
15994 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
15998 NumConsecutiveStores -= NumSkip;
16003 if (!checkMergeStoreCandidatesForDependencies(
16004 StoreNodes, NumStoresToMerge, RootNode)) {
16006 StoreNodes.
begin() + NumStoresToMerge);
16007 NumConsecutiveStores -= NumStoresToMerge;
16011 RV |= MergeStoresOfConstantsOrVecElts(
16012 StoreNodes, MemVT, NumStoresToMerge,
false,
true,
false);
16015 StoreNodes.
begin() + NumStoresToMerge);
16016 NumConsecutiveStores -= NumStoresToMerge;
16032 for (
unsigned i = 0; i < NumConsecutiveStores; ++i) {
16033 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
16039 int64_t LdOffset = 0;
16050 LoadNodes.
push_back(MemOpLink(Ld, LdOffset));
16053 while (NumConsecutiveStores >= 2 && LoadNodes.
size() >= 2) {
16056 unsigned RequiredAlignment;
16057 if (LoadNodes.
size() == 2 &&
16059 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
16066 unsigned FirstStoreAlign = FirstInChain->
getAlignment();
16067 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
16074 unsigned LastConsecutiveLoad = 1;
16077 unsigned LastLegalVectorType = 1;
16078 unsigned LastLegalIntegerType = 1;
16079 bool isDereferenceable =
true;
16080 bool DoIntegerTruncate =
false;
16081 StartAddress = LoadNodes[0].OffsetFromBase;
16083 for (
unsigned i = 1; i < LoadNodes.
size(); ++i) {
16085 if (LoadNodes[i].MemNode->getChain() != FirstChain)
16088 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
16089 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
16091 LastConsecutiveLoad = i;
16093 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
16094 isDereferenceable =
false;
16097 unsigned Elts = (i + 1) * NumMemElts;
16104 bool IsFastSt, IsFastLd;
16113 LastLegalVectorType = i + 1;
16117 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
16127 LastLegalIntegerType = i + 1;
16128 DoIntegerTruncate =
false;
16147 LastLegalIntegerType = i + 1;
16148 DoIntegerTruncate =
true;
16156 LastLegalVectorType > LastLegalIntegerType && !NoVectors;
16157 unsigned LastLegalType =
16158 std::max(LastLegalVectorType, LastLegalIntegerType);
16163 std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
16164 NumElem = std::min(LastLegalType, NumElem);
16174 unsigned NumSkip = 1;
16175 while ((NumSkip < LoadNodes.
size()) &&
16176 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
16177 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
16181 NumConsecutiveStores -= NumSkip;
16186 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
16190 NumConsecutiveStores -= NumElem;
16199 unsigned Elts = NumElem * NumMemElts;
16202 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
16206 SDLoc LoadDL(LoadNodes[0].MemNode);
16207 SDLoc StoreDL(StoreNodes[0].MemNode);
16212 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
16213 AddToWorklist(NewStoreChain.
getNode());
16218 if (IsNonTemporalLoad)
16226 if (UseVectorTy || !DoIntegerTruncate) {
16230 FirstLoadAlign, LdMMOFlags);
16232 NewStoreChain, StoreDL, NewLoad, FirstInChain->
getBasePtr(),
16240 FirstLoadAlign, LdMMOFlags);
16241 NewStore = DAG.
getTruncStore(NewStoreChain, StoreDL, NewLoad,
16249 for (
unsigned i = 0; i < NumElem; ++i) {
16250 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
16257 for (
unsigned i = 0; i < NumElem; ++i) {
16258 SDValue Val = StoreNodes[i].MemNode->getOperand(1);
16259 CombineTo(StoreNodes[i].MemNode, NewStore);
16261 recursivelyDeleteUnusedNodes(Val.
getNode());
16267 NumConsecutiveStores -= NumElem;
16292 AddToWorklist(Token.
getNode());
16295 return CombineTo(ST, Token,
false);
16332 bitcastToAPInt().getZExtValue(),
SDLoc(CFP),
16345 return DAG.
getStore(Chain, DL, Tmp,
16367 Alignment =
MinAlign(Alignment, 4U);
16370 Alignment, MMOFlags, AAInfo);
16396 if (((!LegalOperations && ST->
isSimple()) ||
16426 if (
SDValue NewST = TransformFPLoadStorePair(N))
16436 if (findBetterNeighborChains(ST)) {
16447 (!isa<ConstantSDNode>(
Value) ||
16448 !cast<ConstantSDNode>(Value)->isOpaque())) {
16449 APInt TruncDemandedBits =
16456 AddToWorklist(Value.
getNode());
16463 if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
16477 if (
LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
16478 if (Ld->getBasePtr() == Ptr && ST->
getMemoryVT() == Ld->getMemoryVT() &&
16482 Chain.reachesChainWithoutSideEffects(
SDValue(Ld, 1))) {
16489 if (
StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
16491 ST1->isUnindexed() && ST1->isSimple()) {
16492 if (ST1->getBasePtr() == Ptr && ST1->getValue() == Value &&
16500 !ST1->getBasePtr().isUndef()) {
16504 unsigned ChainBitSize = ST1->getMemoryVT().getSizeInBits();
16509 if (STBase.
contains(DAG, STBitSize, ChainBase, ChainBitSize)) {
16510 CombineTo(ST1, ST1->getChain());
16535 bool Changed = MergeConsecutiveStores(ST);
16536 if (!Changed)
break;
16545 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
16553 if (isa<ConstantFPSDNode>(ST->
getValue())) {
16554 if (
SDValue NewSt = replaceStoreOfFPConstant(ST))
16561 return ReduceLoadOpStoreWidth(N);
16565 const auto *LifetimeEnd = cast<LifetimeSDNode>(
N);
16566 if (!LifetimeEnd->hasOffset())
16570 LifetimeEnd->getOffset(),
false);
16574 while (!Chains.empty()) {
16575 SDValue Chain = Chains.back();
16599 if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase,
16602 dbgs() <<
"\nwithin LIFETIME_END of : ";
16603 LifetimeEndBase.dump();
dbgs() <<
"\n");
16718 Alignment / 2, MMOFlags, AAInfo);
16723 SDValue DAGCombiner::combineInsertEltToShuffle(
SDNode *N,
unsigned InsIndex) {
16725 "Expected extract_vector_elt");
16735 isa<ConstantSDNode>(InsertVal.getOperand(1))) {
16746 int ElementOffset = -1;
16755 while (!ArgWorkList.
empty()) {
16758 std::tie(ArgOffset, ArgVal) = ArgWorkList.
pop_back_val();
16760 if (ArgVal == InsertVal0) {
16761 ElementOffset = ArgOffset;
16767 int CurrentArgOffset =
16771 CurrentArgOffset -= Step;
16777 assert(CurrentArgOffset == ArgOffset);
16781 if (ElementOffset != -1) {
16784 auto *ExtrIndex = cast<ConstantSDNode>(InsertVal.getOperand(1));
16785 NewMask[InsIndex] = ElementOffset + ExtrIndex->getZExtValue();
16786 assert(NewMask[InsIndex] <
16788 NewMask[InsIndex] >= 0 &&
"NewMask[InsIndex] is out of bound");
16794 return LegalShuffle;
16802 if (InsertVal.getOpcode() !=
ISD::BITCAST || !InsertVal.hasOneUse() ||
16803 !InsertVal.getOperand(0).getValueType().isVector())
16812 unsigned NumMaskVals = ExtendRatio * NumSrcElts;
16820 for (
unsigned i = 0; i != NumMaskVals; ++i) {
16821 if (i / NumSrcElts == InsIndex)
16822 Mask[i] = (i % NumSrcElts) + NumMaskVals;
16837 ConcatOps[0] = SubVec;
16843 AddToWorklist(PaddedSubV.
getNode());
16844 AddToWorklist(DestVecBC.
getNode());
16845 AddToWorklist(Shuf.
getNode());
16859 if (
auto *IndexC = dyn_cast<ConstantSDNode>(EltNo))
16881 unsigned Elt = IndexC->getZExtValue();
16882 if (
SDValue Shuf = combineInsertEltToShuffle(N, Elt))
16893 && isa<ConstantSDNode>(InVec.getOperand(2))) {
16894 unsigned OtherElt = InVec.getConstantOperandVal(2);
16895 if (Elt < OtherElt) {
16898 InVec.getOperand(0), InVal, EltNo);
16899 AddToWorklist(NewOp.
getNode());
16916 Ops.
append(InVec.getNode()->op_begin(),
16917 InVec.getNode()->op_end());
16918 }
else if (InVec.isUndef()) {
16923 assert(Ops.
size() == NumElts &&
"Unexpected vector size");
16926 if (Elt < Ops.
size()) {
16929 EVT OpVT = Ops[0].getValueType();
16937 SDValue DAGCombiner::scalarizeExtractedVectorLoad(
SDNode *EVE,
EVT InVecVT,
16963 if (
auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
16964 int Elt = ConstEltNo->getZExtValue();
16987 if (ResultVT.bitsGT(VecEltVT)) {
16995 OriginalLoad->
getChain(), NewPtr, MPI, VecEltVT,
17004 if (ResultVT.bitsLT(VecEltVT))
17009 WorklistRemover DeadNodes(*
this);
17014 AddToWorklist(EVE);
17017 AddToWorklistWithUsers(Load.
getNode());
17025 bool LegalOperations) {
17092 if (IndexC && IndexC->getAPIntValue().uge(NumElts))
17103 if (ScalarVT == InEltVT)
17117 unsigned ExtractIndex = IndexC->getZExtValue();
17119 unsigned BCTruncElt = IsLE ? 0 : NumElts - 1;
17130 "Extract element and scalar to vector can't change element type " 17131 "from FP to integer.");
17134 BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1;
17139 if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) {
17140 assert(XBitWidth % VecEltBitWidth == 0 &&
17141 "Scalar bitwidth must be a multiple of vector element bitwidth");
17157 auto *Shuf = cast<ShuffleVectorSDNode>(VecOp);
17159 int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue());
17167 if (OrigElt < (
int)NumElts) {
17171 OrigElt -= NumElts;
17187 if (!LegalOperations ||
17201 Use->getOperand(0) == VecOp &&
17202 isa<ConstantSDNode>(
Use->getOperand(1));
17206 auto *CstElt = cast<ConstantSDNode>(
Use->getOperand(1));
17207 if (CstElt->getAPIntValue().ult(NumElts))
17208 DemandedElts.
setBit(CstElt->getZExtValue());
17210 if (SimplifyDemandedVectorElts(VecOp, DemandedElts,
true)) {
17222 bool BCNumEltsChanged =
false;
17237 BCNumEltsChanged =
true;
17243 if (!LegalOperations && !IndexC && VecOp.
hasOneUse() &&
17245 !Index->hasPredecessor(VecOp.
getNode())) {
17248 return scalarizeExtractedVectorLoad(N, VecVT, Index,
VecLoad);
17253 if (!LegalOperations || !IndexC)
17259 int Elt = IndexC->getZExtValue();
17262 LN0 = cast<LoadSDNode>(VecOp);
17270 LN0 = cast<LoadSDNode>(VecOp.
getOperand(0));
17272 if (
auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) {
17283 if (BCNumEltsChanged)
17287 int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt);
17298 LN0 = cast<LoadSDNode>(VecOp);
17299 Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts;
17300 Index = DAG.
getConstant(Elt, DL, Index.getValueType());
17313 return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0);
17317 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(
SDNode *N) {
17337 bool AllAnyExt =
true;
17339 for (
unsigned i = 0; i != NumInScalars; ++i) {
17348 if (!ZeroExt && !AnyExt) {
17360 else if (InTy != SourceType) {
17367 AllAnyExt &= AnyExt;
17374 bool ValidTypes = SourceType !=
MVT::Other &&
17385 assert(ElemRatio > 1 &&
"Invalid element size ratio");
17397 Cast.
isUndef()) &&
"Invalid cast opcode");
17403 unsigned Index = isLE ? (i * ElemRatio) :
17404 (i * ElemRatio + (ElemRatio - 1));
17406 assert(Index < Ops.
size() &&
"Invalid index");
17413 "Invalid vector size");
17415 if (!isTypeLegal(VecVT) ||
17432 unsigned LeftIdx,
bool DidSplitVec) {
17441 unsigned ShuffleNumElems = NumElems;
17449 if (InVT1 != VT || InVT2 != VT) {
17454 assert(NumConcats >= 2 &&
"Concat needs at least two inputs!");
17456 ConcatOps[0] = VecIn1;
17457 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.
getUNDEF(InVT1);
17472 Vec2Offset = NumElems;
17478 if (LegalOperations &&
17485 if (InVT1 != InVT2) {
17489 DAG.
getUNDEF(InVT1), VecIn2, ZeroIdx);
17491 ShuffleNumElems = NumElems * 2;
17501 ConcatOps[0] = VecIn2;
17518 for (
unsigned i = 0; i != NumElems; ++i) {
17519 if (VectorMask[i] <= 0)
17523 if (VectorMask[i] == (
int)LeftIdx) {
17524 Mask[i] = ExtIndex;
17525 }
else if (VectorMask[i] == (
int)LeftIdx + 1) {
17526 Mask[i] = Vec2Offset + ExtIndex;
17539 if (ShuffleNumElems > NumElems)
17552 for (
int i = 0; i != NumBVOps; ++i) {
17584 if (DestSize % SrcSize != 0 ||
17590 int ZextRatio = DestSize / SrcSize;
17591 int NumMaskElts = NumBVOps * ZextRatio;
17593 for (
int i = 0; i != NumMaskElts; ++i) {
17594 if (i / ZextRatio == ZextElt) {
17599 if (i % ZextRatio == 0)
17602 ShufMask[i] = NumMaskElts;
17616 ZeroVec, ShufMask, DAG);
17630 if (!isTypeLegal(VT))
17640 bool UsesZeroVector =
false;
17653 for (
unsigned i = 0; i != NumElems; ++i) {
17663 UsesZeroVector =
true;
17687 unsigned Idx = std::distance(
17689 if (Idx == VecIn.
size())
17692 VectorMask[i] = Idx;
17696 if (VecIn.
size() < 2)
17703 bool DidSplitVec =
false;
17704 if (VecIn.
size() == 2) {
17705 unsigned MaxIndex = 0;
17706 unsigned NearestPow2 = 0;
17712 for (
unsigned i = 0; i < NumElems; i++) {
17713 if (VectorMask[i] <= 0)
17716 IndexVec[i] =
Index;
17717 MaxIndex =
std::max(MaxIndex, Index);
17721 if (InVT.
isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
17722 NumElems * 2 < NearestPow2) {
17723 unsigned SplitSize = NearestPow2 / 2;
17734 DidSplitVec =
true;
17736 for (
unsigned i = 0; i < NumElems; i++) {
17737 if (VectorMask[i] <= 0)
17739 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
17765 for (
unsigned In = 0, Len = (VecIn.
size() / 2);
In < Len; ++
In) {
17766 unsigned LeftIdx = 2 *
In + 1;
17767 SDValue VecLeft = VecIn[LeftIdx];
17769 (LeftIdx + 1) < VecIn.
size() ? VecIn[LeftIdx + 1] :
SDValue();
17771 if (
SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
17772 VecRight, LeftIdx, DidSplitVec))
17780 if (UsesZeroVector)
17785 if (Shuffles.
size() == 1)
17786 return Shuffles[0];
17789 for (
int &Vec : VectorMask)
17791 Vec = Shuffles.
size() - 1;
17793 Vec = (Vec - 1) / 2;
17807 if (Shuffles.
size() % 2)
17810 for (
unsigned CurSize = Shuffles.
size(); CurSize > 1; CurSize /= 2) {
17812 Shuffles[CurSize] = DAG.
getUNDEF(VT);
17815 for (
unsigned In = 0, Len = CurSize / 2;
In < Len; ++
In) {
17819 for (
unsigned i = 0; i != NumElems; ++i) {
17820 if (VectorMask[i] == Left) {
17822 VectorMask[i] =
In;
17823 }
else if (VectorMask[i] == Right) {
17824 Mask[i] = i + NumElems;
17825 VectorMask[i] =
In;
17833 return Shuffles[0];
17840 SDValue DAGCombiner::convertBuildVecZextToZext(
SDNode *N) {
17841 if (LegalOperations)
17846 bool FoundZeroExtend =
false;
17848 auto checkElem = [&](
SDValue Op) -> int64_t {
17855 return C->getZExtValue();
17861 int64_t
Offset = checkElem(Op0);
17875 for (
unsigned i = 1; i != NumElems; ++i) {
17876 if ((Offset + i) != checkElem(N->
getOperand(i)))
17902 if (!LegalOperations) {
17905 EVT SrcVT = Splat.getValueType();
17922 if (
SDValue V = cast<BuildVectorSDNode>(N)->getSplatValue()) {
17923 assert(!V.isUndef() &&
"Splat of undef should have been handled earlier");
17930 auto checkElem = [&](
SDValue Op) -> uint64_t {
17933 if (
auto CNode = dyn_cast<ConstantSDNode>(Op.
getOperand(1)))
17934 return CNode->getZExtValue();
17938 int Offset = checkElem(Op0);
17940 if (Offset + i != checkElem(N->
getOperand(i))) {
17946 if ((Offset == 0) &&
17949 if ((Offset != -1) &&
17956 if (
SDValue V = convertBuildVecZextToZext(N))
17959 if (
SDValue V = reduceBuildVecExtToExtBuildVec(N))
17962 if (
SDValue V = reduceBuildVecToShuffle(N))
17984 bool AnyInteger =
false;
17985 bool AnyFP =
false;
17997 EVT LastOpVT = Ops.
back().getValueType();
18047 Mask.
append((
unsigned)NumOpElts, -1);
18064 Mask.
append((
unsigned)NumOpElts, -1);
18079 if (0 == (NumExtElts % NumElts))
18080 ExtIdx /= (NumExtElts / NumElts);
18081 else if (0 == (NumElts % NumExtElts))
18082 ExtIdx *= (NumElts / NumExtElts);
18087 if (SV0.
isUndef() || SV0 == ExtVec) {
18089 for (
int i = 0; i != NumOpElts; ++i)
18091 }
else if (SV1.isUndef() || SV1 == ExtVec) {
18093 for (
int i = 0; i != NumOpElts; ++i)
18162 if (VNTNumElms < 2)
18178 auto IsBuildVectorOrUndef = [](
const SDValue &
Op) {
18189 bool FoundMinVT =
false;
18193 MinVT = (!FoundMinVT || OpSVT.
bitsLE(MinVT)) ? OpSVT : MinVT;
18196 assert(FoundMinVT &&
"Concat vector type mismatch");
18211 for (
unsigned i = 0; i != NumElts; ++i)
18219 "Concat vector type mismatch");
18250 if (SingleSource.
getNode()) {
18269 unsigned IdentityIndex = i * PartNumElem;
18270 if (CS->getAPIntValue() != IdentityIndex)
18275 return SingleSource;
18301 unsigned BinOpcode = BinOp.
getOpcode();
18307 if (VecVT != Bop0.
getValueType() || VecVT != Bop1.getValueType())
18321 if (!Sub0 || !Sub1)
18327 return DAG.
getNode(BinOpcode,
SDLoc(Extract), SubVT, Sub0, Sub1,
18342 if (!ExtractIndexC)
18359 unsigned ExtractIndex = ExtractIndexC->getZExtValue();
18361 "Extract index is not a multiple of the vector length.");
18366 if (WideWidth % NarrowWidth != 0)
18371 unsigned NarrowingRatio = WideWidth / NarrowWidth;
18373 if (WideNumElts % NarrowingRatio != 0)
18378 WideNumElts / NarrowingRatio);
18405 if (NarrowingRatio != 2)
18426 if (SubVecL || SubVecR) {
18442 SDValue NarrowBinOp = DAG.
getNode(BOpcode, DL, NarrowBVT, X, Y);
18459 if (!Ld || Ld->getExtensionType() || !Ld->isSimple() ||
18480 SDValue NewLd = DAG.
getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
18518 if ((SrcNumElts % DestNumElts) == 0) {
18519 unsigned SrcDestRatio = SrcNumElts / DestNumElts;
18532 if ((DestNumElts % SrcNumElts) == 0) {
18533 unsigned DestSrcRatio = DestNumElts / SrcNumElts;
18554 "Concat and extract subvector do not change element type");
18558 assert(ExtIdx % ExtNumElts == 0 &&
18559 "Extract index is not a multiple of the input vector length.");
18562 unsigned ConcatOpIdx = ExtIdx / ConcatSrcNumElts;
18567 if (ConcatSrcNumElts == ExtNumElts)
18575 if (ConcatSrcNumElts % ExtNumElts == 0) {
18577 unsigned NewExtIdx = ExtIdx - ConcatOpIdx * ConcatSrcNumElts;
18578 assert(NewExtIdx + ExtNumElts <= ConcatSrcNumElts &&
18579 "Trying to extract from >1 concat operand?");
18580 assert(NewExtIdx % ExtNumElts == 0 &&
18581 "Extract index is not a multiple of the input vector length.");
18593 if (
auto *IdxC = dyn_cast<ConstantSDNode>(Index)) {
18598 if (ExtractSize % EltSize == 0) {
18599 unsigned NumElems = ExtractSize / EltSize;
18601 EVT ExtractVT = NumElems == 1 ? EltVT
18608 unsigned IdxVal = IdxC->getZExtValue();
18612 if (NumElems == 1) {
18621 ExtractVT,
SDLoc(N), V->
ops().slice(IdxVal, NumElems));
18632 if (!NVT.
bitsEq(SmallVT))
18638 if (InsIdx && ExtIdx) {
18657 if (SimplifyDemandedVectorElts(
SDValue(N, 0)))
18680 unsigned HalfNumElts = NumElts / 2;
18683 for (
unsigned i = 0; i != NumElts; ++i) {
18686 int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (
int)HalfNumElts;
18687 if (i < HalfNumElts)
18690 Mask1[i - HalfNumElts] = M;
18724 unsigned NumConcats = NumElts / NumElemsPerConcat;
18726 auto IsUndefMaskElt = [](
int i) {
return i == -1; };
18731 if (NumElemsPerConcat * 2 == NumElts && N1.
isUndef() &&
18732 llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat),
18736 Mask.slice(0, NumElemsPerConcat));
18743 for (
unsigned I = 0;
I != NumConcats; ++
I) {
18744 unsigned Begin =
I * NumElemsPerConcat;
18754 for (
int i = 0; i != (int)NumElemsPerConcat; ++i) {
18755 if (IsUndefMaskElt(SubMask[i]))
18757 if ((SubMask[i] % (
int)NumElemsPerConcat) != i)
18759 int EltOpIdx = SubMask[i] / NumElemsPerConcat;
18760 if (0 <= OpIdx && EltOpIdx != OpIdx)
18764 assert(0 <= OpIdx &&
"Unknown concat_vectors op");
18818 bool IsSplat =
false;
18822 if (
SDValue Splat0 = BV0->getSplatValue())
18823 IsSplat = (Splat0 == BV1->getSplatValue());
18827 for (
int M : SVN->
getMask()) {
18830 int Idx = M < (int)NumElts ? M : M - NumElts;
18831 SDValue &S = (M < (int)NumElts ? N0 : N1);
18847 if (!Op.
isUndef() && !isa<ConstantSDNode>(
Op) && !isa<ConstantFPSDNode>(Op))
18848 if (!IsSplat && !DuplicateOps.
insert(Op).second)
18875 bool LegalOperations) {
18889 auto isAnyExtend = [&
Mask, &NumElts](
unsigned Scale) {
18890 for (
unsigned i = 0; i != NumElts; ++i) {
18893 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
18902 for (
unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
18904 if (NumElts % Scale != 0)
18906 if (!isAnyExtend(Scale))
18914 if (!LegalOperations ||
18918 SDLoc(SVN), OutVT, N0));
18953 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
18955 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
18960 auto isTruncate = [&
Mask, &NumElts](
unsigned Scale) {
18961 for (
unsigned i = 0; i != NumElts; ++i) {
18964 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
18974 if (EltSizeInBits != ExtSrcSizeInBits)
18979 if (isTruncate(ExtScale))
18995 if (!Splat || !Splat->isSplat())
19000 assert(ShufMask.
size() == SplatMask.
size() &&
"Mask length mismatch");
19018 auto CanSimplifyToExistingSplat = [](
ArrayRef<int> UserMask,
19020 for (
unsigned i = 0,
e = UserMask.
size(); i !=
e; ++i)
19021 if (UserMask[i] != -1 && SplatMask[i] == -1 &&
19022 SplatMask[UserMask[i]] != -1)
19026 if (CanSimplifyToExistingSplat(ShufMask, SplatMask))
19032 for (
int Idx : ShufMask)
19033 NewMask.
push_back(Idx == -1 ? -1 : SplatMask[Idx]);
19036 Splat->getOperand(0), Splat->getOperand(1),
19045 int MaskSize = Mask.
size();
19046 int EltFromOp0 = -1;
19051 for (
int i = 0; i != MaskSize; ++i) {
19052 if (Mask[i] >= 0 && Mask[i] < MaskSize) {
19054 if (EltFromOp0 != -1)
19057 }
else if (Mask[i] != i + MaskSize) {
19077 if (ShufOp0Index == -1) {
19081 if (ShufOp0Index == -1)
19085 Mask = CommutedMask;
19093 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (
int)Mask.
size() &&
19094 "Shuffle mask value must be from operand 0");
19099 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
19113 Op0.getOperand(2).getValueType());
19115 Op1, Op0.getOperand(1), NewInsIndex);
19130 for (
int i = 0,
e = (
int)Mask.
size(); i !=
e; ++i) {
19134 assert(Mask[i] >= 0 && Mask[i] <
e &&
"Unexpected shuffle mask value");
19138 if (Mask0[Mask[i]] != Mask0[i])
19164 for (
unsigned i = 0; i != NumElts; ++i) {
19166 if (Idx >= (
int)NumElts) Idx -= NumElts;
19178 bool Changed =
false;
19180 for (
unsigned i = 0; i != NumElts; ++i) {
19182 if (Idx >= (
int)NumElts) {
19233 "BUILD_VECTOR has wrong number of operands");
19235 bool AllSame =
true;
19236 for (
unsigned i = 0; i != NumElts; ++i) {
19243 if (!Base.getNode())
19245 for (
unsigned i = 0; i != NumElts; ++i) {
19269 if (SimplifyDemandedVectorElts(
SDValue(N, 0)))
19300 int HalfNumElts = (int)NumElts / 2;
19302 for (
unsigned i = 0; i != NumElts; ++i) {
19304 if (Idx >= HalfNumElts) {
19305 assert(Idx < (
int)NumElts &&
"Shuffle mask chooses undef op");
19306 Idx -= HalfNumElts;
19336 for (
int s = 0; s != Scale; ++s)
19337 NewMask.
push_back(M < 0 ? -1 : Scale * M + s);
19348 EVT ScaleVT = SVT.
bitsLT(InnerSVT) ? VT : InnerVT;
19360 ScaleShuffleMask(InnerSVN->
getMask(), InnerScale);
19362 ScaleShuffleMask(SVN->
getMask(), OuterScale);
19366 for (
int M : OuterMask)
19367 NewMask.
push_back(M < 0 ? -1 : InnerMask[M]);
19399 "Shuffle types don't match");
19403 bool HasSameOp0 = N0 == SV0;
19404 bool IsSV1Undef = SV1.
isUndef();
19405 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
19429 "Shuffle types don't match");
19435 for (
unsigned i = 0; i != NumElts; ++i) {
19444 if (Idx < (
int)NumElts) {
19454 CurrentVec = (Idx < (int) NumElts) ? OtherSV->
getOperand(0)
19469 Idx = Idx % NumElts;
19470 if (!SV0.getNode() || SV0 == CurrentVec) {
19479 if (SV1.getNode() && SV1 != CurrentVec)
19489 bool isUndefMask =
true;
19490 for (
unsigned i = 0; i != NumElts && isUndefMask; ++i)
19491 isUndefMask &= Mask[i] < 0;
19496 if (!SV0.getNode())
19498 if (!SV1.getNode())
19529 int Elt = C0->getZExtValue();
19544 DAG.
getUNDEF(InVecT), NewMask, DAG);
19545 if (LegalShuffle) {
19549 return LegalShuffle;
19558 LegalShuffle, ZeroIdx);
19633 if (!isa<ConstantSDNode>(N2))
19636 uint64_t InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
19647 if ((N0.
isUndef() || N0SrcSVT == N1SrcSVT) &&
19659 NewIdx = DAG.
getConstant(InsIdx * Scale, DL, IdxVT);
19660 }
else if ((N1SrcSVT.
getSizeInBits() % EltSizeInBits) == 0) {
19662 if ((NumElts % Scale) == 0 && (InsIdx % Scale) == 0) {
19664 NewIdx = DAG.
getConstant(InsIdx / Scale, DL, IdxVT);
19683 if (InsIdx < OtherIdx) {
19687 AddToWorklist(NewOp.
getNode());
19700 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
19706 if (SimplifyDemandedVectorElts(
SDValue(N, 0)))
19781 if (LegalOperations)
19793 auto BuildClearMask = [&](
int Split) {
19794 int NumSubElts = NumElts * Split;
19798 for (
int i = 0; i != NumSubElts; ++i) {
19799 int EltIdx = i / Split;
19800 int SubIdx = i % Split;
19810 if (isa<ConstantSDNode>(Elt))
19811 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
19812 else if (isa<ConstantFPSDNode>(Elt))
19813 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
19819 Bits = Bits.
extractBits(NumSubBits, (Split - SubIdx - 1) * NumSubBits);
19821 Bits = Bits.
extractBits(NumSubBits, SubIdx * NumSubBits);
19825 else if (Bits == 0)
19848 for (
int Split = 1; Split <= MaxSplit; ++Split)
19850 if (
SDValue S = BuildClearMask(Split))
19869 int Index0, Index1;
19872 if (!Src0 || !Src1 || Index0 != Index1 ||
19894 Ops[Index0] = ScalarBO;
19906 "SimplifyVBinOp only works on vectors!");
19916 Opcode,
SDLoc(LHS), LHS.getValueType(), Ops, N->
getFlags()))
19931 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
19932 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
19933 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
19935 SDValue NewBinOp = DAG.
getNode(Opcode, DL, VT, LHS.getOperand(0),
19936 RHS.getOperand(0), N->
getFlags());
19948 LHS.getOperand(2) == RHS.getOperand(2) &&
19949 (LHS.hasOneUse() || RHS.hasOneUse())) {
19980 if (ConcatWithConstantOrUndef(LHS) && ConcatWithConstantOrUndef(RHS) &&
19981 (LHS.hasOneUse() || RHS.hasOneUse())) {
19982 EVT NarrowVT = LHS.getOperand(0).getValueType();
19983 if (NarrowVT == RHS.getOperand(0).getValueType() &&
19986 unsigned NumOperands = LHS.getNumOperands();
19988 for (
unsigned i = 0; i != NumOperands; ++i) {
19991 RHS.getOperand(i)));
20009 cast<CondCodeSDNode>(N0.
getOperand(2))->
get());
20014 if (SCC.getNode()) {
20021 SCC.getOperand(0), SCC.getOperand(1),
20022 SCC.getOperand(4), Flags);
20023 AddToWorklist(SETCC.
getNode());
20025 SCC.getOperand(2), SCC.getOperand(3));
20040 bool DAGCombiner::SimplifySelectOps(
SDNode *TheSelect,
SDValue LHS,
20053 CC = cast<CondCodeSDNode>(TheSelect->
getOperand(4))->
get();
20060 CC = cast<CondCodeSDNode>(Cmp.
getOperand(2))->
get();
20065 if (Zero && Zero->
isZero() &&
20069 CombineTo(TheSelect, Sqrt);
20096 !LLD->
isSimple() || !RLD->isSimple() ||
20099 LLD->
isIndexed() || RLD->isIndexed() ||
20113 RLD->getPointerInfo().getAddrSpace() != 0 ||
20136 Visited.
insert(TheSelect);
20156 (RLD->hasAnyUseOfValue(1) &&
20163 RLD->getBasePtr());
20178 (RLD->hasAnyUseOfValue(1) &&
20194 unsigned Alignment = std::min(LLD->
getAlignment(), RLD->getAlignment());
20196 if (!RLD->isInvariant())
20198 if (!RLD->isDereferenceable())
20215 CombineTo(TheSelect, Load);
20262 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
20263 unsigned ShCt = XType.
getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
20267 AddToWorklist(Shift.
getNode());
20269 if (XType.
bitsGT(AType)) {
20271 AddToWorklist(Shift.
getNode());
20275 Shift = DAG.
getNOT(DL, Shift, AType);
20287 AddToWorklist(Shift.
getNode());
20289 if (XType.
bitsGT(AType)) {
20291 AddToWorklist(Shift.
getNode());
20295 Shift = DAG.
getNOT(DL, Shift, AType);
20304 SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset(
20320 TLI.
isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) ||
20321 TLI.
isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize))
20326 if (!TV->hasOneUse() && !FV->hasOneUse())
20330 const_cast<ConstantFP*>(TV->getConstantFPValue()) };
20338 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->
getAlignment();
20347 AddToWorklist(Cond.
getNode());
20349 AddToWorklist(CstOffset.getNode());
20350 CPIdx = DAG.
getNode(
ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset);
20351 AddToWorklist(CPIdx.getNode());
20361 bool NotExtCompare) {
20363 if (N2 == N3)
return N2;
20366 EVT CmpResVT = getSetCCResultType(CmpOpVT);
20374 AddToWorklist(SCC.getNode());
20375 if (
auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) {
20378 return !(SCCC->isNullValue()) ? N2 : N3;
20383 convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC))
20386 if (
SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
20399 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
20401 const APInt &AndMask = ConstAndRHS->getAPIntValue();
20422 bool Fold = N2C &&
isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2();
20423 bool Swap = N3C &&
isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2();
20425 if ((Fold || Swap) &&
20437 if (NotExtCompare && N2C->isOne())
20443 SCC = DAG.
getSetCC(DL, CmpResVT, N0, N1, CC);
20453 AddToWorklist(SCC.
getNode());
20454 AddToWorklist(Temp.
getNode());
20459 unsigned ShCt = N2C->getAPIntValue().logBase2();
20484 if (
auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
20510 bool foldBooleans) {
20512 DagCombineInfo(DAG, Level,
false,
this);
20513 return TLI.
SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
20609 if (Enabled == TLI.ReciprocalEstimate::Disabled)
20616 AddToWorklist(Est.getNode());
20624 for (
int i = 0; i < Iterations; ++i) {
20627 if (i == Iterations - 1) {
20629 AddToWorklist(MulEst.
getNode());
20633 AddToWorklist(NewEst.getNode());
20636 (i == Iterations - 1 ? N : FPOne), NewEst, Flags);
20637 AddToWorklist(NewEst.getNode());
20640 AddToWorklist(NewEst.getNode());
20643 AddToWorklist(Est.getNode());
20648 AddToWorklist(Est.getNode());
20664 unsigned Iterations,
20676 for (
unsigned i = 0; i < Iterations; ++i) {
20696 unsigned Iterations,
20709 for (
unsigned i = 0; i < Iterations; ++i) {
20718 if (Reciprocal || (i + 1) < Iterations) {
20748 if (Enabled == TLI.ReciprocalEstimate::Disabled)
20755 bool UseOneConstNR =
false;
20759 AddToWorklist(Est.
getNode());
20762 Est = UseOneConstNR
20763 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
20764 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
20770 EVT CCVT = getSetCCResultType(VT);
20781 Est = DAG.
getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
20786 Est = DAG.
getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
20797 return buildSqrtEstimateImpl(Op, Flags,
true);
20801 return buildSqrtEstimateImpl(Op, Flags,
false);
20805 bool DAGCombiner::isAlias(
SDNode *Op0,
SDNode *Op1)
const {
20807 struct MemUseCharacteristics {
20816 auto getCharacteristics = [](
SDNode *
N) -> MemUseCharacteristics {
20817 if (
const auto *LSN = dyn_cast<LSBaseSDNode>(N)) {
20819 if (
auto *
C = dyn_cast<ConstantSDNode>(LSN->getOffset()))
20821 ?
C->getSExtValue()
20823 ? -1 *
C->getSExtValue()
20825 return {LSN->isVolatile(), LSN->
isAtomic(), LSN->getBasePtr(),
20828 LSN->getMemOperand()};
20830 if (
const auto *LN = cast<LifetimeSDNode>(N))
20831 return {
false ,
false, LN->getOperand(1),
20832 (LN->hasOffset()) ? LN->getOffset() : 0,
20837 return {
false ,
false,
SDValue(),
20842 MemUseCharacteristics MUC0 = getCharacteristics(Op0),
20843 MUC1 = getCharacteristics(Op1);
20846 if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr &&
20847 MUC0.Offset == MUC1.Offset)
20851 if (MUC0.IsVolatile && MUC1.IsVolatile)
20856 if (MUC0.IsAtomic && MUC1.IsAtomic)
20859 if (MUC0.MMO && MUC1.MMO) {
20860 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
20861 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
20874 if (!MUC0.MMO || !MUC1.MMO)
20880 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
20881 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
20888 int64_t SrcValOffset0 = MUC0.MMO->getOffset();
20889 int64_t SrcValOffset1 = MUC1.MMO->getOffset();
20890 unsigned OrigAlignment0 = MUC0.MMO->getBaseAlignment();
20891 unsigned OrigAlignment1 = MUC1.MMO->getBaseAlignment();
20892 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
20893 MUC0.NumBytes.hasValue() && MUC1.NumBytes.hasValue() &&
20894 *MUC0.NumBytes == *MUC1.NumBytes && OrigAlignment0 > *MUC0.NumBytes) {
20895 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
20896 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
20900 if ((OffAlign0 + *MUC0.NumBytes) <= OffAlign1 ||
20901 (OffAlign1 + *MUC1.NumBytes) <= OffAlign0)
20914 if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue()) {
20916 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
20917 int64_t Overlap0 = *MUC0.NumBytes + SrcValOffset0 - MinOffset;
20918 int64_t Overlap1 = *MUC1.NumBytes + SrcValOffset1 - MinOffset;
20934 void DAGCombiner::GatherAllAliases(
SDNode *N,
SDValue OriginalChain,
20941 const bool IsLoad = isa<LoadSDNode>(
N) && cast<LoadSDNode>(N)->isSimple();
20945 unsigned Depth = 0;
20948 std::function<bool(SDValue &)> ImproveChain = [&](
SDValue &
C) ->
bool {
20958 bool IsOpLoad = isa<LoadSDNode>(
C.getNode()) &&
20959 cast<LSBaseSDNode>(
C.getNode())->
isSimple();
20960 if ((IsLoad && IsOpLoad) || !isAlias(N,
C.getNode())) {
20978 if (!isAlias(N,
C.getNode())) {
20993 while (!Chains.
empty()) {
21027 if (ImproveChain(Chain)) {
21049 GatherAllAliases(N, OldChain, Aliases);
21052 if (Aliases.
size() == 0)
21056 if (Aliases.
size() == 1)
21065 struct UnitT { } Unit;
21066 bool operator==(
const UnitT &,
const UnitT &) {
return true; }
21067 bool operator!=(
const UnitT &,
const UnitT &) {
return false; }
21083 bool DAGCombiner::parallelizeChainedStores(
StoreSDNode *St) {
21115 if (!Chain->isSimple() || Chain->isIndexed())
21124 int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8;
21127 auto I = Intervals.find(Offset);
21129 if (
I != Intervals.end() &&
I.start() < (Offset + Length))
21132 if (
I != Intervals.begin() && (--
I).stop() <=
Offset)
21134 Intervals.insert(Offset, Offset + Length, Unit);
21141 if (ChainedStores.
size() == 0)
21148 for (
unsigned I = ChainedStores.
size();
I;) {
21150 SDValue BetterChain = FindBetterChain(S, NewChain);
21154 ChainedStores[
I] = S;
21158 SDValue BetterChain = FindBetterChain(St, NewChain);
21173 auto hasImprovedChain = [&](
SDValue ST) ->
bool {
21176 bool AddNewChain =
llvm::all_of(TFOps, hasImprovedChain);
21187 AddToWorklist(STChain);
21191 bool DAGCombiner::findBetterNeighborChains(
StoreSDNode *St) {
21206 if (parallelizeChainedStores(St))
21211 if (St->
getChain() != BetterChain) {
21212 replaceStoreChain(St, BetterChain);
21222 DAGCombiner(*
this, AA, OptLevel).Run(Level);
SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
bool LegalizeOp(SDNode *N, SmallSetVector< SDNode *, 16 > &UpdatedNodes)
Transforms a SelectionDAG node and any operands to it into a node that is compatible with the target ...
APInt abs() const
Get the absolute value;.
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
static bool isBSwapHWordElement(SDValue N, MutableArrayRef< SDNode *> Parts)
Return true if the specified node is an element that makes up a 32-bit packed halfword byteswap...
static MVT getIntegerVT(unsigned BitWidth)
std::string & operator+=(std::string &buffer, StringRef string)
BUILTIN_OP_END - This must be the last enum value in this list.
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
reference emplace_back(ArgTypes &&... Args)
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
virtual MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
EVT getValueType() const
Return the ValueType of the referenced return value.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg If BaseGV is null...
static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG)
static void commuteMask(MutableArrayRef< int > Mask)
Change values in a shuffle permute mask assuming the two vector operands have swapped position...
bool isShiftedMask() const
Return true if this APInt value contains a sequence of ones with the remainder zero.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
const SDValue & getOffset() const
static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, SDValue X, SDValue Carry0, SDValue Carry1, SDNode *N)
If we are facing some sort of diamond carry propapagtion pattern try to break it up to generate somet...
iterator_range< use_iterator > uses()
void setFlags(SDNodeFlags NewFlags)
static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, SelectionDAG &DAG, bool LegalTypes)
Try to fold a sext/zext/aext dag node into a ConstantSDNode or a build_vector of constants.
static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG)
virtual bool canMergeStoresTo(unsigned AS, EVT MemVT, const SelectionDAG &DAG) const
Returns if it's reasonable to merge stores to MemVT size.
static bool isConstant(const MachineInstr &MI)
bool hasNoSignedZeros() const
SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG)
Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles followed by concatenatio...
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant, which is required to be operand #1) half of the integer or float value specified as operand #0.
uint64_t getZExtValue() const
Get zero extended value.
APInt sext(unsigned width) const
Sign extend to a new width.
static bool areSlicesNextToEachOther(const LoadedSlice &First, const LoadedSlice &Second)
Check whether or not First and Second are next to each other in memory.
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
const TargetLibraryInfo & getLibInfo() const
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef...
DiagnosticInfoOptimizationBase::Argument NV
typename SuperClass::const_iterator const_iterator
bool isIndexed() const
Return true if this is a pre/post inc/dec load/store.
SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
DELETED_NODE - This is an illegal value that is used to catch errors.
LLVM_NODISCARD T pop_back_val()
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR (an vector value) starting with the ...
CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
BR_CC - Conditional branch.
This class represents lattice values for constants.
static bool IsMasked(Instruction *I)
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not...
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
size_type size() const
Determine the number of elements in the SetVector.
SDValue simplifyShift(SDValue X, SDValue Y)
Try to simplify a shift into 1 of its operands or a constant.
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0...
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG)
Try to fold a 'not' shifted sign-bit with add/sub with constant operand into a shift and add with a d...
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
int getSplatIndex() const
static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG)
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
const Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
static uint64_t * getMemory(unsigned numWords)
A utility function for allocating memory and checking for allocation failure.
const SDValue & getBasePtr() const
SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base, SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, ISD::LoadExtType, bool IsExpanding=false)
bool isNegative() const
Return true if the value is negative.
Carry-setting nodes for multiple precision addition and subtraction.
static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, KnownBits &Known)
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
void push_back(const T &Elt)
static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, SelectionDAG &DAG, const TargetLowering &TLI)
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
Clients of various APIs that cause global effects on the DAG can optionally implement this interface...
SDValue makeEquivalentMemoryOrdering(LoadSDNode *Old, SDValue New)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
APInt zext(unsigned width) const
Zero extend to a new width.
bool operator>(int64_t V1, const APSInt &V2)
virtual bool enableAggressiveFMAFusion(EVT VT) const
Return true if target always beneficiates from combining into FMA for a given value type...
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
const SDValue & getValue() const
virtual bool getPreIndexedAddressParts(SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if the node's...
virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps, bool &UseOneConstNR, bool Reciprocal) const
Hooks for building estimates in place of slower divisions and square roots.
SDVTList getVTList() const
virtual bool isFNegFree(EVT VT) const
Return true if an fneg operation is free to the point where it is never worthwhile to replace it with...
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const
Return true if extraction of a scalar element from the given vector type at the given index is cheap...
virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const
This method will be invoked for all target nodes and for any target-independent nodes that the target...
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
The two locations do not alias at all.
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
const SDValue & getChain() const
static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG)
Try to replace shift/logic that tests if a bit is clear with mask + setcc.
unsigned getResNo() const
Convenience function for get().getResNo().
SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
ISD::MemIndexedMode getAddressingMode() const
Return the addressing mode for this load or store: unindexed, pre-inc, pre-dec, post-inc, or post-dec.
virtual bool isCommutativeBinOp(unsigned Opcode) const
Returns true if the opcode is a commutative binary operation.
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
static const fltSemantics & EVTToAPFloatSemantics(EVT VT)
Returns an APFloat semantics tag appropriate for the given type.
unsigned getAlignment() const
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
bool isAllOnesOrAllOnesSplat(SDValue V)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
APInt trunc(unsigned width) const
Truncate to new width.
void setAllBits()
Set every bit to 1.
bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const
Return true if the specified store with truncation is legal on this target.
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
TypeSize getScalarValueSizeInBits() const
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS)
Helper function to make it easier to build Select's if you just have operands and don't want to check...
const fltSemantics & getSemantics() const
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const
Return true if creating a shift of the type by the given amount is not profitable.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
[US]{MIN/MAX} - Binary minimum or maximum or signed or unsigned integers.
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
const SDNodeFlags getFlags() const
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
iv Induction Variable Users
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 maximum semantics.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
static SDValue tryToFoldExtOfMaskedLoad(SelectionDAG &DAG, const TargetLowering &TLI, EVT VT, SDNode *N, SDValue N0, ISD::LoadExtType ExtLoadType, ISD::NodeType ExtOpc)
SDValue getConstantPool(const Constant *C, EVT VT, unsigned Align=0, int Offs=0, bool isT=false, unsigned TargetFlags=0)
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
virtual bool storeOfVectorConstantIsCheap(EVT MemVT, unsigned NumElem, unsigned AddrSpace) const
Return true if it is expected to be cheaper to do a store of a non-zero vector constant with the give...
bool isOperationLegalOrCustom(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
bool isByteSized() const
Return true if the bit size is a multiple of 8.
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
void DeleteNode(SDNode *N)
Remove the specified node from the system.
static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG)
bool isConstTrueVal(const SDNode *N) const
Return if the N is a constant or constant vector equal to the true value from getBooleanContents().
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1 at the ...
unsigned getBitWidth() const
Get the bit width of this value.
virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode *> &Created) const
Targets may override this function to provide custom SDIV lowering for power-of-2 denominators...
EntryToken - This is the marker used to indicate the start of a region.
static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract, SelectionDAG &DAG)
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
static Optional< bool > isBigEndian(const ArrayRef< int64_t > ByteOffsets, int64_t FirstOffset)
unsigned getBitWidth() const
Return the number of bits in the APInt.
SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, SmallVectorImpl< SDNode *> &Created) const
Given an ISD::UDIV node expressing a divide by constant, return a DAG expression to select that will ...
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
bool isAllOnesValue() const
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal on this target.
void transferDbgValues(SDValue From, SDValue To, unsigned OffsetInBits=0, unsigned SizeInBits=0, bool InvalidateDbg=true)
Transfer debug values from one node to another, while optionally generating fragment expressions for ...
bool hasApproximateFuncs() const
bool isTruncatingStore() const
Return true if the op does a truncation before store.
int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const
Return a ReciprocalEstimate enum value for a square root of the given type based on the function's at...
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode *> &Visited, SmallVectorImpl< const SDNode *> &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
unsigned getAddressSpace() const
Return the address space for the associated pointer.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
bool operator<=(int64_t V1, const APSInt &V2)
static bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N)
copysign(x, fp_extend(y)) -> copysign(x, y) copysign(x, fp_round(y)) -> copysign(x, y)
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
unsigned countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
static cl::opt< bool > UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), cl::desc("Enable DAG combiner's use of TBAA"))
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
static uint32_t getAlignment(const MCSectionCOFF &Sec)
bool hasOneUse() const
Return true if there is exactly one use of this node.
static bool isContractable(SDNode *N)
static SDValue combineShiftOfShiftedLogic(SDNode *Shift, SelectionDAG &DAG)
If we have a shift-by-constant of a bitwise logic op that itself has a shift-by-constant operand with...
A description of a memory reference used in the backend.
APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
OverflowKind computeOverflowKind(SDValue N0, SDValue N1) const
Determine if the result of the addition of 2 node can overflow.
bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef, APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Vector Op.
static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG)
void setBit(unsigned BitPosition)
Set a given bit to 1.
static ManagedStatic< DebugCounter > DC
SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, bool foldBooleans, DAGCombinerInfo &DCI, const SDLoc &dl) const
Try to simplify a setcc built with the specified operands and cc.
bool operator>=(int64_t V1, const APSInt &V2)
bool isUndef(unsigned Opcode, ArrayRef< SDValue > Ops)
Return true if the result of this operation is always undefined.
ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
SDValue getSplatSourceVector(SDValue V, int &SplatIndex)
If V is a splatted value, return the source vector and its splat index.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
static cl::opt< std::string > CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, cl::desc("Only use DAG-combiner alias analysis in this" " function"))
APInt shl(unsigned shiftAmt) const
Left-shift function.
Shift and rotation operations.
bool matchUnaryPredicate(SDValue Op, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant BUI...
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
static cl::opt< bool > Aggressive("aggressive-ext-opt", cl::Hidden, cl::desc("Aggressive extension optimization"))
static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG)
APInt zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Base class for LoadSDNode and StoreSDNode.
bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef...
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth...
A Use represents the edge between a Value definition and its users.
bool equalBaseIndex(const BaseIndexOffset &Other, const SelectionDAG &DAG, int64_t &Off) const
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
const SDValue & getPassThru() const
CopyToReg - This node has three operands: a chain, a register number to set to this value...
op_iterator op_end() const
uint64_t getConstantOperandVal(unsigned i) const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
This file contains the simple types necessary to represent the attributes associated with functions a...
virtual bool mergeStoresAfterLegalization(EVT MemVT) const
Allow store merging for the specified type after legalization in addition to before legalization...
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 minimum semantics.
virtual bool generateFMAsInMachineCombiner(CodeGenOpt::Level OptLevel) const
bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal or custom on this target.
The memory access is dereferenceable (i.e., doesn't trap).
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first...
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const
Use bitwise logic to make pairs of compares more efficient.
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const DataLayout & getDataLayout() const
SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
This class is used to represent EVT's, which are used to parameterize some operations.
CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical AND between different comparisons of identical values: ((X op1 Y) & (X...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
bool remove(const value_type &X)
Remove an item from the set vector.
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl)
Constant fold a setcc to true or false.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const
This file implements a class to represent arbitrary precision integral constant values and operations...
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
iterator_range< allnodes_iterator > allnodes()
SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
This class is used to represent an MSTORE node.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
unsigned getActiveBits() const
Compute the number of active bits in the value.
int64_t getSExtValue() const
SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode CC, const TargetLowering &TLI, SelectionDAG &DAG)
Generate Min/Max node.
int64_t getSExtValue() const
Get sign extended value.
unsigned NoNaNsFPMath
NoNaNsFPMath - This flag is enabled when the -enable-no-nans-fp-math flag is specified on the command...
Type * getType() const
All values are typed, get the type of this value.
bool getBoolValue() const
Convert APInt to a boolean value.
MachineFunction & getMachineFunction() const
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool isOneOrOneSplat(SDValue V)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
bool isKnownNeverZero(SDValue Op) const
Test whether the given SDValue is known to contain non-zero value(s).
const TargetMachine & getTarget() const
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
static SDValue flipBoolean(SDValue V, const SDLoc &DL, SelectionDAG &DAG, const TargetLowering &TLI)
SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
Simple integer binary arithmetic operators.
bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
bool isOperandOf(const SDNode *N) const
Return true if this node is an operand of N.
static cl::opt< bool > StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, cl::desc("Bypass the profitability model of load slicing"), cl::init(false))
Hidden option to stress test load slicing, i.e., when this option is enabled, load slicing bypasses m...
bool has(LibFunc F) const
Tests whether a library function is available.
int32_t exactLogBase2() const
APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
bool contains(const SelectionDAG &DAG, int64_t BitSize, const BaseIndexOffset &Other, int64_t OtherBitSize, int64_t &BitOffset) const
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false)
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
bool isLittleEndian() const
Layout endianness...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
AttributeList getAttributes() const
Return the attribute list for this Function.
bool isKnownNeverNaN(SDValue Op, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue is known to never be NaN.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out...
op_iterator op_begin() const
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification, or lowering of the constant.
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
ArrayRef< SDUse > ops() const
const SDValue & getMask() const
int64_t getSrcValueOffset() const
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
DenormalMode getDenormalMode(EVT VT) const
Return the current function's default denormal handling kind for the given floating point type...
Value * getOperand(unsigned i) const
std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const
Return a ReciprocalEstimate enum value for a division of the given type based on the function's attri...
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
UNDEF - An undefined node.
This class is used to represent ISD::STORE nodes.
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
bool hasAllowReciprocal() const
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a vector with the specified, possibly variable...
bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
AliasResult
The possible results of an alias query.
This corresponds to the llvm.lifetime.
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
iterator find(const_arg_type_t< KeyT > Val)
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits...
bool isZero() const
Return true if the value is positive or negative zero.
bool hasAllowContract() const
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
static unsigned LittleEndianByteAt(unsigned BW, unsigned i)
bool isNegative() const
Determine sign of this APInt.
const SDValue & getBasePtr() const
bool isSimple() const
Returns true if the memory operation is neither atomic or volatile.
initializer< Ty > init(const Ty &Val)
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
bool erase(const KeyT &Val)
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, const TargetLowering &TLI)
unsigned UnsafeFPMath
UnsafeFPMath - This flag is enabled when the -enable-unsafe-fp-math flag is specified on the command ...
These reductions are non-strict, and have a single vector operand.
bool isAllOnesValue() const
Determine if all bits are set.
FPOpFusion::FPOpFusionMode AllowFPOpFusion
AllowFPOpFusion - This flag is set by the -fuse-fp-ops=xxx option.
SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SDValue foldSelectOfConstantsUsingSra(SDNode *N, SelectionDAG &DAG)
If a (v)select has a condition value that is a sign-bit test, try to smear the condition operand sign...
bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, SDNode *N1, SDNode *N2)
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isExpandingLoad() const
static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG)
static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG)
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
Simple binary floating point operators.
bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
size_t size() const
size - Get the array size.
static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef< int > Mask)
If the shuffle mask is taking exactly one element from the first vector operand and passing through a...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
iterator_range< value_op_iterator > op_values() const
LLVM_NODISCARD bool empty() const
bool isRound() const
Return true if the size is a power-of-two number of bytes.
const SDValue & getOperand(unsigned Num) const
SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Carry-using nodes for multiple precision addition and subtraction.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool isMask(unsigned numBits) const
bool isOneValue() const
Determine if this is a value of 1.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
void AddToWorklist(SDNode *N)
const SDValue & getOffset() const
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This class provides iterator support for SDUse operands that use a specific SDNode.
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOperations, bool ForCodeSize, unsigned Depth=0) const
If isNegatibleForFree returns true, return the newly negated expression.
static cl::opt< unsigned > StoreMergeDependenceLimit("combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10), cl::desc("Limit the number of times for the same StoreNode and RootNode " "to bail out in store merging dependence check"))
bool recursivelyDeleteUnusedNodes(SDNode *N)
static EVT getFloatingPointVT(unsigned BitWidth)
Returns the EVT that represents a floating-point type with the given number of bits.
void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
const APInt & getAPIntValue() const
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static bool getCombineLoadStoreParts(SDNode *N, unsigned Inc, unsigned Dec, bool &IsLoad, bool &IsMasked, SDValue &Ptr, const TargetLowering &TLI)
static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, SDValue &Mask)
Match "(X shl/srl V1) & V2" where V2 may not be present.
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
virtual bool hasPairedLoad(EVT, unsigned &) const
Return true if the target supplies and combines to a paired load two loaded values of type LoadedType...
static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG)
If we are extracting a subvector produced by a wide binary operator try to use a narrow binary operat...
static cl::opt< unsigned > TokenFactorInlineLimit("combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048), cl::desc("Limit the number of operands to inline for Token Factors"))
static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N, APFloat(*Op)(const APFloat &, const APFloat &))
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
The memory access is non-temporal.
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y)...
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
static SDValue ShrinkLoadReplaceStoreWithStore(const std::pair< unsigned, unsigned > &MaskInfo, SDValue IVal, StoreSDNode *St, DAGCombiner *DC)
Check to see if IVal is something that provides a value as specified by MaskInfo. ...
bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
static cl::opt< bool > CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, cl::desc("Enable DAG combiner's use of IR alias analysis"))
virtual bool isDesirableToTransformToIntegerOp(unsigned, EVT) const
Return true if it is profitable for dag combiner to transform a floating point op of specified opcode...
static unsigned BigEndianByteAt(unsigned BW, unsigned i)
Bit counting operators with an undefined result for zero inputs.
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
static const Optional< ByteProvider > calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, bool Root=false)
Recursively traverses the expression calculating the origin of the requested byte of the given value...
Targets can subclass this to parameterize the SelectionDAG lowering and instruction selection process...
static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG)
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, const TargetLowering &TLI, EVT VT, bool LegalOperations, SDNode *N, SDValue N0, ISD::LoadExtType ExtLoadType)
iterator erase(const_iterator CI)
SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, SDValue N1, MutableArrayRef< int > Mask, SelectionDAG &DAG) const
Tries to build a legal vector shuffle using the provided parameters or equivalent variations...
bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
static bool areUsedBitsDense(const APInt &UsedBits)
Check that all bits set in UsedBits form a dense region, i.e., UsedBits looks like 0...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
unsigned countLeadingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the most significant bit to the least stopping at the first 1...
static void adjustCostForPairing(SmallVectorImpl< LoadedSlice > &LoadedSlices, LoadedSlice::Cost &GlobalLSCost)
Adjust the GlobalLSCost according to the target paring capabilities and the layout of the slices...
SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
int getDivRefinementSteps(EVT VT, MachineFunction &MF) const
Return the refinement step count for a division of the given type based on the function's attributes...
static bool computeAliasing(const SDNode *Op0, const Optional< int64_t > NumBytes0, const SDNode *Op1, const Optional< int64_t > NumBytes1, const SelectionDAG &DAG, bool &IsAlias)
This class contains a discriminated union of information about pointers in memory operands...
unsigned getNumOperands() const
Return the number of values used by this operation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
HANDLENODE node - Used as a handle for various purposes.
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1, SelectionDAG &DAG, const SDLoc &DL)
Given the operands of an add/sub operation, see if the 2nd operand is a masked 0/1 whose source opera...
This struct is a compact representation of a valid (non-zero power of two) alignment.
SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value...
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT...
SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands...
virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, EVT DestVT, EVT SrcVT) const
Return true if an fpext operation input to an Opcode operation is free (for instance, because half-precision floating-point numbers are implicitly extended to float-precision) for an FMA instruction.
bool isUnindexed() const
Return true if this is NOT a pre/post inc/dec load/store.
static SDValue getAsCarry(const TargetLowering &TLI, SDValue V)
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
void sort(IteratorTy Start, IteratorTy End)
virtual bool shouldScalarizeBinop(SDValue VecOp) const
Try to convert an extract element of a vector binary operation into an extract element followed by a ...
bool isUNINDEXEDLoad(const SDNode *N)
Returns true if the specified node is an unindexed load.
static cl::opt< bool > EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true), cl::desc("DAG combiner enable merging multiple stores " "into a wider store"))
const APInt & getConstantOperandAPInt(unsigned i) const
SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type...
bool use_empty() const
Return true if there are no uses of this node.
Representation for a specific memory location.
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
virtual bool IsDesirableToPromoteOp(SDValue, EVT &) const
This method query the target whether it is beneficial for dag combiner to promote the specified node...
TokenFactor - This node takes multiple tokens as input and produces a single token result...
bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef...
void dump() const
Dump this node, for debugging.
static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG, const TargetLowering &TLI)
Return true if 'Use' is a load or a store that uses N as its base pointer and that N may be folded in...
const TargetLowering & getTargetLoweringInfo() const
Helper struct to parse and store a memory address as base + index + offset.
static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG)
If a vector binop is performed on splat values, it may be profitable to extract, scalarize, and insert/splat.
A SetVector that performs no allocations if smaller than a certain size.
void setNoUnsignedWrap(bool b)
static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, SelectionDAG &DAG, const TargetLowering &TLI, bool LegalOperations)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset=0)
SDValue getMemBasePlusOffset(SDValue Base, int64_t Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
virtual bool preferIncOfAddToSubOfNot(EVT VT) const
These two forms are equivalent: sub y, (xor x, -1) add (add x, 1), y The variant with two add's is IR...
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT) const
Return true if it is profitable to reduce a load to a smaller type.
SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, SmallVectorImpl< SDNode *> &Created) const
Given an ISD::SDIV node expressing a divide by constant, return a DAG expression to select that will ...
virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context, EVT VT) const
Returns true if we should normalize select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely that it saves us from materializing N0 and N1 in an integer register.
virtual bool getPostIndexedAddressParts(SDNode *, SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if this node ...
BlockVerifier::State From
bool isNullOrNullSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Align max(MaybeAlign Lhs, Align Rhs)
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
static int numVectorEltsOrZero(EVT T)
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
EVT getVectorElementType() const
Given a vector type, return the type of each element.
static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, bool LegalOperations)
SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
const SDValue & getMask() const
bool isAtomic() const
Return true if the memory operation ordering is Unordered or higher.
SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, unsigned Index) const
Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type from this source type with ...
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
static APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const
There are two ways to clear extreme bits (either low or high): Mask: x & (-1 << y) (the instcombine c...
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
BRCOND - Conditional branch.
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimum or maximum on two values, following the IEEE-754 2008 definition.
static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG, bool LegalOperations)
Transform a vector binary operation into a scalar binary operation by moving the math/logic after an ...
void Combine(CombineLevel Level, AAResults *AA, CodeGenOpt::Level OptLevel)
This iterates over the nodes in the SelectionDAG, folding certain types of nodes together, or eliminating superfluous nodes.
const SDValue & getPassThru() const
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Byte Swap and Counting operators.
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...
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const
Return true if folding a vector load into ExtVal (a sign, zero, or any extend node) is profitable...
LLVM_NODISCARD T pop_back_val()
This is an abstract virtual class for memory operations.
virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT, const SelectionDAG &DAG, const MachineMemOperand &MMO) const
Return true if the following transform is beneficial: fold (conv (load x)) -> (load (conv*)x) On arch...
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Represents one node in the SelectionDAG.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, const TargetLowering &TLI, EVT VT, bool LegalOperations, SDNode *N, SDValue N0, ISD::LoadExtType ExtLoadType, ISD::NodeType ExtOpc)
static unsigned int semanticsPrecision(const fltSemantics &)
bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
bool isConstFalseVal(const SDNode *N) const
Return if the N is a constant or constant vector equal to the false value from getBooleanContents().
unsigned logBase2() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
MachinePointerInfo getWithOffset(int64_t O) const
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
TypeSize getValueSizeInBits(unsigned ResNo) const
Returns MVT::getSizeInBits(getValueType(ResNo)).
unsigned countTrailingOnes() const
Count the number of trailing one bits.
size_t use_size() const
Return the number of uses of this node.
SDNode * isConstantIntBuildVectorOrConstantInt(SDValue N)
Test whether the given value is a constant int or similar node.
static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, const TargetLowering &TLI)
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT...
EVT getMemoryVT() const
Return the type of the in-memory value.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Class for arbitrary precision integers.
static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, SelectionDAG &DAG)
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
bool isBuildVectorOfConstantFPSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantFPSDNode or undef...
SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG)
If a shuffle inserts exactly one element from a source vector operand into another vector operand and...
virtual bool hasAndNot(SDValue X) const
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
iterator_range< use_iterator > uses()
static cl::opt< bool > MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), cl::desc("DAG combiner may split indexing from loads"))
CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical OR between different comparisons of identical values: ((X op1 Y) | (X ...
static SDNode * getBuildPairElt(SDNode *N, unsigned i)
A "pseudo-class" with methods for operating on BUILD_VECTORs.
Select(COND, TRUEVAL, FALSEVAL).
SDValue peekThroughOneUseBitcasts(SDValue V)
Return the non-bitcasted and one-use source operand of V if it exists.
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static use_iterator use_end()
bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
ZERO_EXTEND - Used for integer types, zeroing the new bits.
ANY_EXTEND - Used for integer types. The high bits are undefined.
static std::pair< unsigned, unsigned > CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain)
Check to see if V is (and load (ptr), imm), where the load is having specific bytes cleared out...
SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
iterator insert(iterator I, T &&Elt)
static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques=false)
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
int getMaskElt(unsigned Idx) const
static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
SDValue FoldConstantVectorArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, const SDNodeFlags Flags=SDNodeFlags())
bool hasVectorReduction() const
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Flags
Flags values. These may be or'd together.
int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const
Return the refinement step count for a square root of the given type based on the function's attribut...
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
bool hasNoSignedWrap() const
const TargetRegisterClass * getCommonSubClass(const TargetRegisterClass *A, const TargetRegisterClass *B) const
Find the largest common subclass of A and B.
bool matchBinaryPredicate(SDValue LHS, SDValue RHS, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
bool operator!=(uint64_t V1, const APInt &V2)
static mvt_range all_valuetypes()
SimpleValueType Iteration.
virtual bool isFPImmLegal(const APFloat &, EVT, bool ForCodeSize=false) const
Returns true if the target can instruction select the specified FP immediate natively.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
opStatus
IEEE-754R 7: Default exception handling.
These are IR-level optimization flags that may be propagated to SDNodes.
Represents a use of a SDNode.
virtual bool isDesirableToCommuteWithShift(const SDNode *N, CombineLevel Level) const
Return true if it is profitable to move this shift by a constant amount though its operand...
bool isVector() const
Return true if this is a vector value type.
static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, SDValue ExtractFrom, SDValue &Mask, const SDLoc &DL)
Helper function for visitOR to extract the needed side of a rotate idiom from a shl/srl/mul/udiv.
static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG, const TargetLowering &TLI, bool Force)
Flips a boolean if it is cheaper to compute.
const SDValue & getValue() const
virtual bool convertSelectOfConstantsToMath(EVT VT) const
Return true if a select of constants (select Cond, C1, C2) should be transformed into simple math ops...
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Bitwise operators - logical and, logical or, logical xor.
bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
pointer data()
Return a pointer to the vector's buffer, even if empty().
virtual char isNegatibleForFree(SDValue Op, SelectionDAG &DAG, bool LegalOperations, bool ForCodeSize, unsigned Depth=0) const
Return 1 if we can compute the negated form of the specified expression for the same cost as the expr...
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
LLVM_NODISCARD bool empty() const
StringRef getValueAsString() const
Return the attribute's value as a string.
bool isKnownToBeAPowerOfTwo(SDValue Val) const
Test if the given value is known to have exactly one bit set.
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS)
This file provides utility analysis objects describing memory locations.
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps) const
Return a reciprocal estimate value for the input operand.
ISD::CondCode get() const
const ConstantInt * getConstantIntValue() const
const TargetSubtargetInfo & getSubtarget() const
bool empty() const
Determine if the SetVector is empty or not.
Flags getFlags() const
Return the raw flags of the source value,.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
The memory access always returns the same value (or traps).
unsigned InferPtrAlignment(SDValue Ptr) const
Infer alignment of a load / store address.
static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, SelectionDAG &DAG, bool LegalOperations)
SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL, bool LegalTypes=true)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT)
virtual bool decomposeMulByConstant(LLVMContext &Context, EVT VT, SDValue C) const
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
static bool isBSwapHWordPair(SDValue N, MutableArrayRef< SDNode *> Parts)
static SDValue stripTruncAndExt(SDValue Value)
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
const SDValue & getBasePtr() const
static SDValue getInputChainForNode(SDNode *N)
Given a node, return its input chain if it has one, otherwise return a null sd operand.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
unsigned getOpcode() const
SDValue getValue(unsigned R) const
virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const
Return true if integer divide is usually cheaper than a sequence of several shifts, adds, and multiplies for this target.
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
This class is used to represent an MSCATTER node.
static MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
static BaseIndexOffset match(const SDNode *N, const SelectionDAG &DAG)
Parses tree in N for base, index, offset addresses.
bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask)
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT, const SelectionDAG &DAG, const MachineMemOperand &MMO) const
Return true if the following transform is beneficial: (store (y (conv x)), y*)) -> (store x...
virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const
Return true if it is profitable to convert a select of FP constants into a constant pool load whose a...
const MachinePointerInfo & getPointerInfo() const
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS, SDValue RHS, const TargetLowering &TLI)
bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts)
Test whether V has a splatted value for all the demanded elements.
This class is used to form a handle around another node that is persistent and is updated across invo...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, EVT SVT, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf)
If we have a unary shuffle of a shuffle, see if it can be folded away completely. ...
virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N, CombineLevel Level) const
Return true if it is profitable to fold a pair of shifts into a mask.
This class is used to represent an MLOAD node.
bool isPredecessorOf(const SDNode *N) const
Return true if this node is a predecessor of N.
bool operator<(int64_t V1, const APSInt &V2)
static ConstantSDNode * getAsNonOpaqueConstant(SDValue N)
If N is a ConstantSDNode with isOpaque() == false return it casted to a ConstantSDNode pointer else n...
TypeSize getScalarSizeInBits() const
static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, unsigned ExtOpc, SmallVectorImpl< SDNode *> &ExtendNodes, const TargetLowering &TLI)
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
ArrayRef< int > getMask() const
LLVM Value Representation.
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
FMA - Perform a * b + c with no intermediate rounding step.
static bool isSlicingProfitable(SmallVectorImpl< LoadedSlice > &LoadedSlices, const APInt &UsedBits, bool ForCodeSize)
Check the profitability of all involved LoadedSlice.
Integer reductions may have a result type larger than the vector element type.
unsigned getResNo() const
get the index which selects a specific result in the SDNode
Fast - This calling convention attempts to make calls as fast as possible (e.g.
SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
unsigned countTrailingOnes(T Value, ZeroBehavior ZB=ZB_Width)
Count the number of ones from the least significant bit to the first zero bit.
A vector that has set insertion semantics.
static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, const TargetLowering &TLI)
Return true if divmod libcall is available.
bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond)
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
This class is used to represent an MGATHER node.
bool hasNoUnsignedWrap() const
SDValue getValueType(EVT)
virtual bool isVectorClearMaskLegal(ArrayRef< int >, EVT) const
Similar to isShuffleMaskLegal.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const
Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
bool isNonTemporal() const
bool isUndef() const
Return true if the type of the node type undefined.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
DenormalMode
Represent handled modes for denormal (aka subnormal) modes in the floating point environment.
void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone...
ISD::MemIndexedMode getAddressingMode() const
Return the addressing mode for this load or store: unindexed, pre-inc, pre-dec, post-inc, or post-dec.
bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal on this target.
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX)
bool hasAllowReassociation() const
virtual bool useAA() const
Enable use of alias analysis during code generation (during MI scheduling, DAGCombine, etc.).
const APFloat & getValueAPF() const
unsigned NoSignedZerosFPMath
NoSignedZerosFPMath - This flag is enabled when the -enable-no-signed-zeros-fp-math is specified on t...
virtual const SelectionDAGTargetInfo * getSelectionDAGInfo() const
ISD::LoadExtType getExtensionType() const
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations...
SetCC operator - This evaluates to a true value iff the condition is true.
virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const
Return true if folding a constant offset with the given GlobalAddress is legal.
APInt bitcastToAPInt() const
static SDNode * isConstantFPBuildVectorOrConstantFP(SDValue N)
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG)
If we are extracting a subvector from a wide vector load, convert to a narrow load to eliminate the e...
KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
static SDValue combineCarryDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, const TargetLowering &TLI, SDValue Carry0, SDValue Carry1, SDNode *N)
bool operator==(uint64_t V1, const APInt &V2)
unsigned getNumOperands() const
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations, those with specific masks.
static APInt getNullValue(unsigned numBits)
Get the '0' value.
const SDValue & getOperand(unsigned i) const
SDNode * getUser()
This returns the SDNode that contains this Use.
unsigned getGatherAllAliasesMaxDepth() const
uint64_t getZExtValue() const
SDNode * getNodeIfExists(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops, const SDNodeFlags Flags=SDNodeFlags())
Get the specified node if it's already available, or else return NULL.
TRUNCATE - Completely drop the high bits.
virtual bool isFMADLegalForFAddFSub(const SelectionDAG &DAG, const SDNode *N) const
Returns true if the FADD or FSUB node passed could legally be combined with an fmul to form an ISD::F...
static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG)
Given an extending node with a pop-count operand, if the target does not support a pop-count in the n...
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
bool hasTargetDAGCombine(ISD::NodeType NT) const
If true, the target has custom DAG combine transformations that it can perform for the specified node...
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
virtual bool hasBitPreservingFPLogic(EVT VT) const
Return true if it is safe to transform an integer-domain bitwise operation into the equivalent floati...
Perform various unary floating-point operations inspired by libm.
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual bool isLegalAddImmediate(int64_t) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, unsigned Alignment=1, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, bool *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
bool shouldOptForSize() const
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
const SDValue & getBasePtr() const
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
LLVMContext * getContext() const
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
static SDValue visitORCommutative(SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N)
OR combines for which the commuted variant will be tried as well.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE minNum semantics.
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL, bool LegalTypes=true) const
bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
Carry-using nodes for multiple precision addition and subtraction.
const SDValue & getMask() const
bool isNullValue() const
Determine if all bits are clear.
CARRY_FALSE - This node is used when folding other nodes, like ADDC/SUBC, which indicate the carry re...
virtual bool isNarrowingProfitable(EVT, EVT) const
Return true if it's profitable to narrow operations of type VT1 to VT2.
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
SDValue GetDemandedBits(SDValue V, const APInt &DemandedBits)
See if the specified operand can be simplified with the knowledge that only the bits specified by Dem...
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
This file describes how to lower LLVM code to machine code.
void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO)
IEEE-754 denormal numbers preserved.
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.
virtual bool shouldSplatInsEltVarIndex(EVT) const
Return true if inserting a scalar into a variable element of an undef vector is more efficiently hand...
static bool isConstantOrConstantVector(SDValue N, bool NoOpaques=false)
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
This class is used to represent ISD::LOAD nodes.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.