1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This implements the SelectionDAG class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/CodeGen/Analysis.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
40 #include "llvm/CodeGen/SelectionDAGNodes.h"
41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
42 #include "llvm/CodeGen/TargetFrameLowering.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugInfoMetadata.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MachineValueType.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85 SDVTList Res = {VTs, NumVTs};
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
96 #define DEBUG_TYPE "selectiondag"
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99 cl::Hidden, cl::init(true),
100 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103 cl::desc("Number limit for gluing ld/st of memcpy."),
104 cl::Hidden, cl::init(0));
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110 //===----------------------------------------------------------------------===//
111 // ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119 return getValueAPF().bitwiseIsEqual(V);
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123 const APFloat& Val) {
124 assert(VT.isFloatingPoint() && "Can only convert between FP types");
126 // convert modifies in place, so make a copy.
127 APFloat Val2 = APFloat(Val);
129 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130 APFloat::rmNearestTiesToEven,
135 //===----------------------------------------------------------------------===//
137 //===----------------------------------------------------------------------===//
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
142 N->getValueType(0).getVectorElementType().getSizeInBits();
143 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144 SplatVal = Op0->getAPIntValue().trunc(EltSize);
147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
153 auto *BV = dyn_cast<BuildVectorSDNode>(N);
158 unsigned SplatBitSize;
160 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
163 EltSize == SplatBitSize;
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170 // Look through a bit convert.
171 while (N->getOpcode() == ISD::BITCAST)
172 N = N->getOperand(0).getNode();
174 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
176 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
179 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
181 unsigned i = 0, e = N->getNumOperands();
183 // Skip over all of the undef values.
184 while (i != e && N->getOperand(i).isUndef())
187 // Do not accept an all-undef vector.
188 if (i == e) return false;
190 // Do not accept build_vectors that aren't all constants or which have non-~0
191 // elements. We have to be a bit careful here, as the type of the constant
192 // may not be the same as the type of the vector elements due to type
193 // legalization (the elements are promoted to a legal type for the target and
194 // a vector of a type may be legal when the base element type is not).
195 // We only want to check enough bits to cover the vector elements, because
196 // we care if the resultant vector is all ones, not whether the individual
198 SDValue NotZero = N->getOperand(i);
199 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
203 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
209 // Okay, we have at least one ~0 value, check to see if the rest match or are
210 // undefs. Even with the above element type twiddling, this should be OK, as
211 // the same type legalization should have applied to all the elements.
212 for (++i; i != e; ++i)
213 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219 // Look through a bit convert.
220 while (N->getOpcode() == ISD::BITCAST)
221 N = N->getOperand(0).getNode();
223 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
225 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
228 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
230 bool IsAllUndef = true;
231 for (const SDValue &Op : N->op_values()) {
235 // Do not accept build_vectors that aren't all constants or which have non-0
236 // elements. We have to be a bit careful here, as the type of the constant
237 // may not be the same as the type of the vector elements due to type
238 // legalization (the elements are promoted to a legal type for the target
239 // and a vector of a type may be legal when the base element type is not).
240 // We only want to check enough bits to cover the vector elements, because
241 // we care if the resultant vector is all zeros, not whether the individual
243 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
247 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
254 // Do not accept an all-undef vector.
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269 if (N->getOpcode() != ISD::BUILD_VECTOR)
272 for (const SDValue &Op : N->op_values()) {
275 if (!isa<ConstantSDNode>(Op))
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282 if (N->getOpcode() != ISD::BUILD_VECTOR)
285 for (const SDValue &Op : N->op_values()) {
288 if (!isa<ConstantFPSDNode>(Op))
294 bool ISD::allOperandsUndef(const SDNode *N) {
295 // Return false if the node has no operands.
296 // This is "logically inconsistent" with the definition of "all" but
297 // is probably the desired behavior.
298 if (N->getNumOperands() == 0)
300 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
303 bool ISD::matchUnaryPredicate(SDValue Op,
304 std::function<bool(ConstantSDNode *)> Match,
306 // FIXME: Add support for scalar UNDEF cases?
307 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
310 // FIXME: Add support for vector UNDEF cases?
311 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312 ISD::SPLAT_VECTOR != Op.getOpcode())
315 EVT SVT = Op.getValueType().getScalarType();
316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317 if (AllowUndefs && Op.getOperand(i).isUndef()) {
323 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
330 bool ISD::matchBinaryPredicate(
331 SDValue LHS, SDValue RHS,
332 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333 bool AllowUndefs, bool AllowTypeMismatch) {
334 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
337 // TODO: Add support for scalar UNDEF cases?
338 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340 return Match(LHSCst, RHSCst);
342 // TODO: Add support for vector UNDEF cases?
343 if (LHS.getOpcode() != RHS.getOpcode() ||
344 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345 LHS.getOpcode() != ISD::SPLAT_VECTOR))
348 EVT SVT = LHS.getValueType().getScalarType();
349 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350 SDValue LHSOp = LHS.getOperand(i);
351 SDValue RHSOp = RHS.getOperand(i);
352 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
358 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359 LHSOp.getValueType() != RHSOp.getValueType()))
361 if (!Match(LHSCst, RHSCst))
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368 switch (VecReduceOpcode) {
370 llvm_unreachable("Expected VECREDUCE opcode");
371 case ISD::VECREDUCE_FADD:
372 case ISD::VECREDUCE_SEQ_FADD:
373 case ISD::VP_REDUCE_FADD:
374 case ISD::VP_REDUCE_SEQ_FADD:
376 case ISD::VECREDUCE_FMUL:
377 case ISD::VECREDUCE_SEQ_FMUL:
378 case ISD::VP_REDUCE_FMUL:
379 case ISD::VP_REDUCE_SEQ_FMUL:
381 case ISD::VECREDUCE_ADD:
382 case ISD::VP_REDUCE_ADD:
384 case ISD::VECREDUCE_MUL:
385 case ISD::VP_REDUCE_MUL:
387 case ISD::VECREDUCE_AND:
388 case ISD::VP_REDUCE_AND:
390 case ISD::VECREDUCE_OR:
391 case ISD::VP_REDUCE_OR:
393 case ISD::VECREDUCE_XOR:
394 case ISD::VP_REDUCE_XOR:
396 case ISD::VECREDUCE_SMAX:
397 case ISD::VP_REDUCE_SMAX:
399 case ISD::VECREDUCE_SMIN:
400 case ISD::VP_REDUCE_SMIN:
402 case ISD::VECREDUCE_UMAX:
403 case ISD::VP_REDUCE_UMAX:
405 case ISD::VECREDUCE_UMIN:
406 case ISD::VP_REDUCE_UMIN:
408 case ISD::VECREDUCE_FMAX:
409 case ISD::VP_REDUCE_FMAX:
411 case ISD::VECREDUCE_FMIN:
412 case ISD::VP_REDUCE_FMIN:
417 bool ISD::isVPOpcode(unsigned Opcode) {
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
424 #include "llvm/IR/VPIntrinsics.def"
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
440 bool ISD::isVPReduction(unsigned Opcode) {
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
460 #include "llvm/IR/VPIntrinsics.def"
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
472 #include "llvm/IR/VPIntrinsics.def"
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
479 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
481 return ISD::SIGN_EXTEND;
483 return ISD::ZERO_EXTEND;
488 llvm_unreachable("Invalid LoadExtType");
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492 // To perform this operation, we just need to swap the L and G bits of the
494 unsigned OldL = (Operation >> 2) & 1;
495 unsigned OldG = (Operation >> 1) & 1;
496 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
497 (OldL << 1) | // New G bit
498 (OldG << 2)); // New L bit.
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502 unsigned Operation = Op;
504 Operation ^= 7; // Flip L, G, E bits, but not U.
506 Operation ^= 15; // Flip all of the condition bits.
508 if (Operation > ISD::SETTRUE2)
509 Operation &= ~8; // Don't let N and U bits get set.
511 return ISD::CondCode(Operation);
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515 return getSetCCInverseImpl(Op, Type.isInteger());
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519 bool isIntegerLike) {
520 return getSetCCInverseImpl(Op, isIntegerLike);
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
528 default: llvm_unreachable("Illegal integer setcc operation!");
530 case ISD::SETNE: return 0;
534 case ISD::SETGE: return 1;
538 case ISD::SETUGE: return 2;
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
544 bool IsInteger = Type.isInteger();
545 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546 // Cannot fold a signed integer setcc with an unsigned integer setcc.
547 return ISD::SETCC_INVALID;
549 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
551 // If the N and U bits get set, then the resultant comparison DOES suddenly
552 // care about orderedness, and it is true when ordered.
553 if (Op > ISD::SETTRUE2)
554 Op &= ~16; // Clear the U bit if the N bit is set.
556 // Canonicalize illegal integer setcc's.
557 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
560 return ISD::CondCode(Op);
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
565 bool IsInteger = Type.isInteger();
566 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567 // Cannot fold a signed setcc with an unsigned setcc.
568 return ISD::SETCC_INVALID;
570 // Combine all of the condition bits.
571 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
573 // Canonicalize illegal integer setcc's.
577 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
578 case ISD::SETOEQ: // SETEQ & SETU[LG]E
579 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
580 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
581 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
588 //===----------------------------------------------------------------------===//
589 // SDNode Profile Support
590 //===----------------------------------------------------------------------===//
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600 ID.AddPointer(VTList.VTs);
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605 ArrayRef<SDValue> Ops) {
606 for (const auto &Op : Ops) {
607 ID.AddPointer(Op.getNode());
608 ID.AddInteger(Op.getResNo());
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614 ArrayRef<SDUse> Ops) {
615 for (const auto &Op : Ops) {
616 ID.AddPointer(Op.getNode());
617 ID.AddInteger(Op.getResNo());
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622 SDVTList VTList, ArrayRef<SDValue> OpList) {
623 AddNodeIDOpcode(ID, OpC);
624 AddNodeIDValueTypes(ID, VTList);
625 AddNodeIDOperands(ID, OpList);
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630 switch (N->getOpcode()) {
631 case ISD::TargetExternalSymbol:
632 case ISD::ExternalSymbol:
634 llvm_unreachable("Should only be used on nodes with operands");
635 default: break; // Normal nodes don't need extra info.
636 case ISD::TargetConstant:
637 case ISD::Constant: {
638 const ConstantSDNode *C = cast<ConstantSDNode>(N);
639 ID.AddPointer(C->getConstantIntValue());
640 ID.AddBoolean(C->isOpaque());
643 case ISD::TargetConstantFP:
644 case ISD::ConstantFP:
645 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
647 case ISD::TargetGlobalAddress:
648 case ISD::GlobalAddress:
649 case ISD::TargetGlobalTLSAddress:
650 case ISD::GlobalTLSAddress: {
651 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652 ID.AddPointer(GA->getGlobal());
653 ID.AddInteger(GA->getOffset());
654 ID.AddInteger(GA->getTargetFlags());
657 case ISD::BasicBlock:
658 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
661 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
663 case ISD::RegisterMask:
664 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
667 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
669 case ISD::FrameIndex:
670 case ISD::TargetFrameIndex:
671 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
673 case ISD::LIFETIME_START:
674 case ISD::LIFETIME_END:
675 if (cast<LifetimeSDNode>(N)->hasOffset()) {
676 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
680 case ISD::PSEUDO_PROBE:
681 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
686 case ISD::TargetJumpTable:
687 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
690 case ISD::ConstantPool:
691 case ISD::TargetConstantPool: {
692 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693 ID.AddInteger(CP->getAlign().value());
694 ID.AddInteger(CP->getOffset());
695 if (CP->isMachineConstantPoolEntry())
696 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
698 ID.AddPointer(CP->getConstVal());
699 ID.AddInteger(CP->getTargetFlags());
702 case ISD::TargetIndex: {
703 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704 ID.AddInteger(TI->getIndex());
705 ID.AddInteger(TI->getOffset());
706 ID.AddInteger(TI->getTargetFlags());
710 const LoadSDNode *LD = cast<LoadSDNode>(N);
711 ID.AddInteger(LD->getMemoryVT().getRawBits());
712 ID.AddInteger(LD->getRawSubclassData());
713 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714 ID.AddInteger(LD->getMemOperand()->getFlags());
718 const StoreSDNode *ST = cast<StoreSDNode>(N);
719 ID.AddInteger(ST->getMemoryVT().getRawBits());
720 ID.AddInteger(ST->getRawSubclassData());
721 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722 ID.AddInteger(ST->getMemOperand()->getFlags());
726 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727 ID.AddInteger(ELD->getMemoryVT().getRawBits());
728 ID.AddInteger(ELD->getRawSubclassData());
729 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730 ID.AddInteger(ELD->getMemOperand()->getFlags());
733 case ISD::VP_STORE: {
734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735 ID.AddInteger(EST->getMemoryVT().getRawBits());
736 ID.AddInteger(EST->getRawSubclassData());
737 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738 ID.AddInteger(EST->getMemOperand()->getFlags());
741 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743 ID.AddInteger(SLD->getMemoryVT().getRawBits());
744 ID.AddInteger(SLD->getRawSubclassData());
745 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750 ID.AddInteger(SST->getMemoryVT().getRawBits());
751 ID.AddInteger(SST->getRawSubclassData());
752 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
755 case ISD::VP_GATHER: {
756 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757 ID.AddInteger(EG->getMemoryVT().getRawBits());
758 ID.AddInteger(EG->getRawSubclassData());
759 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760 ID.AddInteger(EG->getMemOperand()->getFlags());
763 case ISD::VP_SCATTER: {
764 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765 ID.AddInteger(ES->getMemoryVT().getRawBits());
766 ID.AddInteger(ES->getRawSubclassData());
767 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768 ID.AddInteger(ES->getMemOperand()->getFlags());
772 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773 ID.AddInteger(MLD->getMemoryVT().getRawBits());
774 ID.AddInteger(MLD->getRawSubclassData());
775 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776 ID.AddInteger(MLD->getMemOperand()->getFlags());
780 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781 ID.AddInteger(MST->getMemoryVT().getRawBits());
782 ID.AddInteger(MST->getRawSubclassData());
783 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784 ID.AddInteger(MST->getMemOperand()->getFlags());
788 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789 ID.AddInteger(MG->getMemoryVT().getRawBits());
790 ID.AddInteger(MG->getRawSubclassData());
791 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792 ID.AddInteger(MG->getMemOperand()->getFlags());
795 case ISD::MSCATTER: {
796 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797 ID.AddInteger(MS->getMemoryVT().getRawBits());
798 ID.AddInteger(MS->getRawSubclassData());
799 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800 ID.AddInteger(MS->getMemOperand()->getFlags());
803 case ISD::ATOMIC_CMP_SWAP:
804 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805 case ISD::ATOMIC_SWAP:
806 case ISD::ATOMIC_LOAD_ADD:
807 case ISD::ATOMIC_LOAD_SUB:
808 case ISD::ATOMIC_LOAD_AND:
809 case ISD::ATOMIC_LOAD_CLR:
810 case ISD::ATOMIC_LOAD_OR:
811 case ISD::ATOMIC_LOAD_XOR:
812 case ISD::ATOMIC_LOAD_NAND:
813 case ISD::ATOMIC_LOAD_MIN:
814 case ISD::ATOMIC_LOAD_MAX:
815 case ISD::ATOMIC_LOAD_UMIN:
816 case ISD::ATOMIC_LOAD_UMAX:
817 case ISD::ATOMIC_LOAD:
818 case ISD::ATOMIC_STORE: {
819 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820 ID.AddInteger(AT->getMemoryVT().getRawBits());
821 ID.AddInteger(AT->getRawSubclassData());
822 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823 ID.AddInteger(AT->getMemOperand()->getFlags());
826 case ISD::PREFETCH: {
827 const MemSDNode *PF = cast<MemSDNode>(N);
828 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829 ID.AddInteger(PF->getMemOperand()->getFlags());
832 case ISD::VECTOR_SHUFFLE: {
833 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
836 ID.AddInteger(SVN->getMaskElt(i));
839 case ISD::TargetBlockAddress:
840 case ISD::BlockAddress: {
841 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842 ID.AddPointer(BA->getBlockAddress());
843 ID.AddInteger(BA->getOffset());
844 ID.AddInteger(BA->getTargetFlags());
847 case ISD::AssertAlign:
848 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
850 } // end switch (N->getOpcode())
852 // Target specific memory nodes could also have address spaces and flags
854 if (N->isTargetMemoryOpcode()) {
855 const MemSDNode *MN = cast<MemSDNode>(N);
856 ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857 ID.AddInteger(MN->getMemOperand()->getFlags());
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864 AddNodeIDOpcode(ID, N->getOpcode());
865 // Add the return value info.
866 AddNodeIDValueTypes(ID, N->getVTList());
867 // Add the operand info.
868 AddNodeIDOperands(ID, N->ops());
870 // Handle SDNode leafs with special info.
871 AddNodeIDCustom(ID, N);
874 //===----------------------------------------------------------------------===//
875 // SelectionDAG Class
876 //===----------------------------------------------------------------------===//
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880 if (N->getValueType(0) == MVT::Glue)
881 return true; // Never CSE anything that produces a flag.
883 switch (N->getOpcode()) {
885 case ISD::HANDLENODE:
887 return true; // Never CSE these nodes.
890 // Check that remaining values produced are not flags.
891 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892 if (N->getValueType(i) == MVT::Glue)
893 return true; // Never CSE anything that produces a flag.
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
900 void SelectionDAG::RemoveDeadNodes() {
901 // Create a dummy node (which is not added to allnodes), that adds a reference
902 // to the root node, preventing it from being deleted.
903 HandleSDNode Dummy(getRoot());
905 SmallVector<SDNode*, 128> DeadNodes;
907 // Add all obviously-dead nodes to the DeadNodes worklist.
908 for (SDNode &Node : allnodes())
909 if (Node.use_empty())
910 DeadNodes.push_back(&Node);
912 RemoveDeadNodes(DeadNodes);
914 // If the root changed (e.g. it was a dead load, update the root).
915 setRoot(Dummy.getValue());
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
922 // Process the worklist, deleting the nodes and adding their uses to the
924 while (!DeadNodes.empty()) {
925 SDNode *N = DeadNodes.pop_back_val();
926 // Skip to next node if we've already managed to delete the node. This could
927 // happen if replacing a node causes a node previously added to the node to
929 if (N->getOpcode() == ISD::DELETED_NODE)
932 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933 DUL->NodeDeleted(N, nullptr);
935 // Take the node out of the appropriate CSE map.
936 RemoveNodeFromCSEMaps(N);
938 // Next, brutally remove the operand list. This is safe to do, as there are
939 // no cycles in the graph.
940 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
942 SDNode *Operand = Use.getNode();
945 // Now that we removed this operand, see if there are no uses of it left.
946 if (Operand->use_empty())
947 DeadNodes.push_back(Operand);
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955 SmallVector<SDNode*, 16> DeadNodes(1, N);
957 // Create a dummy node that adds a reference to the root node, preventing
958 // it from being deleted. (This matters if the root is an operand of the
960 HandleSDNode Dummy(getRoot());
962 RemoveDeadNodes(DeadNodes);
965 void SelectionDAG::DeleteNode(SDNode *N) {
966 // First take this out of the appropriate CSE map.
967 RemoveNodeFromCSEMaps(N);
969 // Finally, remove uses due to operands of this node, remove from the
970 // AllNodes list, and delete the node.
971 DeleteNodeNotInCSEMaps(N);
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975 assert(N->getIterator() != AllNodes.begin() &&
976 "Cannot delete the entry node!");
977 assert(N->use_empty() && "Cannot delete a node that is not dead!");
979 // Drop all of the operands and decrement used node's use counts.
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986 assert(!(V->isVariadic() && isParameter));
988 ByvalParmDbgValues.push_back(V);
990 DbgValues.push_back(V);
991 for (const SDNode *Node : V->getSDNodes())
993 DbgValMap[Node].push_back(V);
996 void SDDbgInfo::erase(const SDNode *Node) {
997 DbgValMapType::iterator I = DbgValMap.find(Node);
998 if (I == DbgValMap.end())
1000 for (auto &Val: I->second)
1001 Val->setIsInvalidated();
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006 // If we have operands, deallocate them.
1009 NodeAllocator.Deallocate(AllNodes.remove(N));
1011 // Set the opcode to DELETED_NODE to help catch bugs when node
1012 // memory is reallocated.
1013 // FIXME: There are places in SDag that have grown a dependency on the opcode
1014 // value in the released node.
1015 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016 N->NodeType = ISD::DELETED_NODE;
1018 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019 // them and forget about that node.
1024 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026 switch (N->getOpcode()) {
1029 case ISD::BUILD_PAIR: {
1030 EVT VT = N->getValueType(0);
1031 assert(N->getNumValues() == 1 && "Too many results!");
1032 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033 "Wrong return type!");
1034 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036 "Mismatched operand types!");
1037 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038 "Wrong operand type!");
1039 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040 "Wrong return type size");
1043 case ISD::BUILD_VECTOR: {
1044 assert(N->getNumValues() == 1 && "Too many results!");
1045 assert(N->getValueType(0).isVector() && "Wrong return type!");
1046 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047 "Wrong number of operands!");
1048 EVT EltVT = N->getValueType(0).getVectorElementType();
1049 for (const SDUse &Op : N->ops()) {
1050 assert((Op.getValueType() == EltVT ||
1051 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052 EltVT.bitsLE(Op.getValueType()))) &&
1053 "Wrong operand type!");
1054 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055 "Operands must all have the same type");
1063 /// Insert a newly allocated node into the DAG.
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068 AllNodes.push_back(N);
1070 N->PersistentId = NextPersistentId++;
1073 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074 DUL->NodeInserted(N);
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it. This is useful when we're about to delete or repurpose
1079 /// the node. We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082 bool Erased = false;
1083 switch (N->getOpcode()) {
1084 case ISD::HANDLENODE: return false; // noop.
1086 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087 "Cond code doesn't exist!");
1088 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1091 case ISD::ExternalSymbol:
1092 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1094 case ISD::TargetExternalSymbol: {
1095 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097 ESN->getSymbol(), ESN->getTargetFlags()));
1100 case ISD::MCSymbol: {
1101 auto *MCSN = cast<MCSymbolSDNode>(N);
1102 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1105 case ISD::VALUETYPE: {
1106 EVT VT = cast<VTSDNode>(N)->getVT();
1107 if (VT.isExtended()) {
1108 Erased = ExtendedValueTypeNodes.erase(VT);
1110 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1116 // Remove it from the CSE Map.
1117 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119 Erased = CSEMap.RemoveNode(N);
1123 // Verify that the node was actually in one of the CSE maps, unless it has a
1124 // flag result (which cannot be CSE'd) or is one of the special cases that are
1125 // not subject to CSE.
1126 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127 !N->isMachineOpcode() && !doNotCSE(N)) {
1130 llvm_unreachable("Node is not in map!");
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142 // For node types that aren't CSE'd, just act as if no identical node
1145 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146 if (Existing != N) {
1147 // If there was already an existing matching node, use ReplaceAllUsesWith
1148 // to replace the dead one with the existing one. This can cause
1149 // recursive merging of other unrelated nodes down the line.
1150 ReplaceAllUsesWith(N, Existing);
1152 // N is now dead. Inform the listeners and delete it.
1153 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154 DUL->NodeDeleted(N, Existing);
1155 DeleteNodeNotInCSEMaps(N);
1160 // If the node doesn't already exist, we updated it. Inform listeners.
1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162 DUL->NodeUpdated(N);
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified. If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take. If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1174 SDValue Ops[] = { Op };
1175 FoldingSetNodeID ID;
1176 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177 AddNodeIDCustom(ID, N);
1178 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1180 Node->intersectFlagsWith(N->getFlags());
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified. If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take. If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189 SDValue Op1, SDValue Op2,
1194 SDValue Ops[] = { Op1, Op2 };
1195 FoldingSetNodeID ID;
1196 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197 AddNodeIDCustom(ID, N);
1198 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1200 Node->intersectFlagsWith(N->getFlags());
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified. If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take. If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1213 FoldingSetNodeID ID;
1214 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215 AddNodeIDCustom(ID, N);
1216 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1218 Node->intersectFlagsWith(N->getFlags());
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223 Type *Ty = VT == MVT::iPTR ?
1224 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225 VT.getTypeForEVT(*getContext());
1227 return getDataLayout().getABITypeAlign(Ty);
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232 : TM(tm), OptLevel(OL),
1233 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234 Root(getEntryNode()) {
1235 InsertNode(&EntryNode);
1236 DbgInfo = new SDDbgInfo();
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240 OptimizationRemarkEmitter &NewORE,
1241 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242 LegacyDivergenceAnalysis * Divergence,
1243 ProfileSummaryInfo *PSIin,
1244 BlockFrequencyInfo *BFIin) {
1246 SDAGISelPass = PassPtr;
1248 TLI = getSubtarget().getTargetLowering();
1249 TSI = getSubtarget().getSelectionDAGInfo();
1250 LibInfo = LibraryInfo;
1251 Context = &MF->getFunction().getContext();
1257 SelectionDAG::~SelectionDAG() {
1258 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1260 OperandRecycler.clear(OperandAllocator);
1264 bool SelectionDAG::shouldOptForSize() const {
1265 return MF->getFunction().hasOptSize() ||
1266 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1269 void SelectionDAG::allnodes_clear() {
1270 assert(&*AllNodes.begin() == &EntryNode);
1271 AllNodes.remove(AllNodes.begin());
1272 while (!AllNodes.empty())
1273 DeallocateNode(&AllNodes.front());
1275 NextPersistentId = 0;
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1281 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1283 switch (N->getOpcode()) {
1286 case ISD::ConstantFP:
1287 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288 "debug location. Use another overload.");
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295 const SDLoc &DL, void *&InsertPos) {
1296 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1298 switch (N->getOpcode()) {
1300 case ISD::ConstantFP:
1301 // Erase debug location from the node if the node is used at several
1302 // different places. Do not propagate one location to all uses as it
1303 // will cause a worse single stepping debugging experience.
1304 if (N->getDebugLoc() != DL.getDebugLoc())
1305 N->setDebugLoc(DebugLoc());
1308 // When the node's point of use is located earlier in the instruction
1309 // sequence than its prior point of use, update its debug info to the
1310 // earlier location.
1311 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312 N->setDebugLoc(DL.getDebugLoc());
1319 void SelectionDAG::clear() {
1321 OperandRecycler.clear(OperandAllocator);
1322 OperandAllocator.Reset();
1325 ExtendedValueTypeNodes.clear();
1326 ExternalSymbols.clear();
1327 TargetExternalSymbols.clear();
1329 SDCallSiteDbgInfo.clear();
1330 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331 static_cast<CondCodeSDNode*>(nullptr));
1332 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333 static_cast<SDNode*>(nullptr));
1335 EntryNode.UseList = nullptr;
1336 InsertNode(&EntryNode);
1337 Root = getEntryNode();
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342 return VT.bitsGT(Op.getValueType())
1343 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349 const SDLoc &DL, EVT VT) {
1350 assert(!VT.bitsEq(Op.getValueType()) &&
1351 "Strict no-op FP extend/round not allowed.");
1353 VT.bitsGT(Op.getValueType())
1354 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356 {Chain, Op, getIntPtrConstant(0, DL)});
1358 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362 return VT.bitsGT(Op.getValueType()) ?
1363 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364 getNode(ISD::TRUNCATE, DL, VT, Op);
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368 return VT.bitsGT(Op.getValueType()) ?
1369 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370 getNode(ISD::TRUNCATE, DL, VT, Op);
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374 return VT.bitsGT(Op.getValueType()) ?
1375 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376 getNode(ISD::TRUNCATE, DL, VT, Op);
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1381 if (VT.bitsLE(Op.getValueType()))
1382 return getNode(ISD::TRUNCATE, SL, VT, Op);
1384 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389 EVT OpVT = Op.getValueType();
1390 assert(VT.isInteger() && OpVT.isInteger() &&
1391 "Cannot getZeroExtendInReg FP types");
1392 assert(VT.isVector() == OpVT.isVector() &&
1393 "getZeroExtendInReg type should be vector iff the operand "
1395 assert((!VT.isVector() ||
1396 VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397 "Vector element counts must match in getZeroExtendInReg");
1398 assert(VT.bitsLE(OpVT) && "Not extending!");
1401 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402 VT.getScalarSizeInBits());
1403 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407 // Only unsigned pointer semantics are supported right now. In the future this
1408 // might delegate to TLI to check pointer signedness.
1409 return getZExtOrTrunc(Op, DL, VT);
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413 // Only unsigned pointer semantics are supported right now. In the future this
1414 // might delegate to TLI to check pointer signedness.
1415 return getZeroExtendInReg(Op, DL, VT);
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429 SDValue Mask, SDValue EVL, EVT VT) {
1430 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1437 return getConstant(0, DL, VT);
1439 switch (TLI->getBooleanContents(OpVT)) {
1440 case TargetLowering::ZeroOrOneBooleanContent:
1441 case TargetLowering::UndefinedBooleanContent:
1442 return getConstant(1, DL, VT);
1443 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444 return getAllOnesConstant(DL, VT);
1446 llvm_unreachable("Unexpected boolean content enum!");
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450 bool isT, bool isO) {
1451 EVT EltVT = VT.getScalarType();
1452 assert((EltVT.getSizeInBits() >= 64 ||
1453 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454 "getConstant with a uint64_t value that doesn't fit in the type!");
1455 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459 bool isT, bool isO) {
1460 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464 EVT VT, bool isT, bool isO) {
1465 assert(VT.isInteger() && "Cannot create FP integer constant!");
1467 EVT EltVT = VT.getScalarType();
1468 const ConstantInt *Elt = &Val;
1470 // In some cases the vector type is legal but the element type is illegal and
1471 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1472 // inserted value (the type does not need to match the vector element type).
1473 // Any extra bits introduced will be truncated away.
1474 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475 TargetLowering::TypePromoteInteger) {
1476 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478 Elt = ConstantInt::get(*getContext(), NewVal);
1480 // In other cases the element type is illegal and needs to be expanded, for
1481 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482 // the value into n parts and use a vector type with n-times the elements.
1483 // Then bitcast to the type requested.
1484 // Legalizing constants too early makes the DAGCombiner's job harder so we
1485 // only legalize if the DAG tells us we must produce legal types.
1486 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487 TLI->getTypeAction(*getContext(), EltVT) ==
1488 TargetLowering::TypeExpandInteger) {
1489 const APInt &NewVal = Elt->getValue();
1490 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1493 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494 if (VT.isScalableVector()) {
1495 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496 "Can only handle an even split!");
1497 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1499 SmallVector<SDValue, 2> ScalarParts;
1500 for (unsigned i = 0; i != Parts; ++i)
1501 ScalarParts.push_back(getConstant(
1502 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503 ViaEltVT, isT, isO));
1505 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1508 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1511 // Check the temporary vector is the correct size. If this fails then
1512 // getTypeToTransformTo() probably returned a type whose size (in bits)
1513 // isn't a power-of-2 factor of the requested type size.
1514 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1516 SmallVector<SDValue, 2> EltParts;
1517 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518 EltParts.push_back(getConstant(
1519 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520 ViaEltVT, isT, isO));
1522 // EltParts is currently in little endian order. If we actually want
1523 // big-endian order then reverse it now.
1524 if (getDataLayout().isBigEndian())
1525 std::reverse(EltParts.begin(), EltParts.end());
1527 // The elements must be reversed when the element order is different
1528 // to the endianness of the elements (because the BITCAST is itself a
1529 // vector shuffle in this situation). However, we do not need any code to
1530 // perform this reversal because getConstant() is producing a vector
1532 // This situation occurs in MIPS MSA.
1534 SmallVector<SDValue, 8> Ops;
1535 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536 llvm::append_range(Ops, EltParts);
1539 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1543 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544 "APInt size does not match type size!");
1545 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546 FoldingSetNodeID ID;
1547 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1551 SDNode *N = nullptr;
1552 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1554 return SDValue(N, 0);
1557 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558 CSEMap.InsertNode(N, IP);
1560 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1563 SDValue Result(N, 0);
1564 if (VT.isScalableVector())
1565 Result = getSplatVector(VT, DL, Result);
1566 else if (VT.isVector())
1567 Result = getSplatBuildVector(VT, DL, Result);
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1574 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578 const SDLoc &DL, bool LegalTypes) {
1579 assert(VT.isInteger() && "Shift amount is not an integer type!");
1580 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581 return getConstant(Val, DL, ShiftVT);
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1586 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1591 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595 EVT VT, bool isTarget) {
1596 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1598 EVT EltVT = VT.getScalarType();
1600 // Do the map lookup using the actual bit pattern for the floating point
1601 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602 // we don't have issues with SNANs.
1603 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604 FoldingSetNodeID ID;
1605 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1608 SDNode *N = nullptr;
1609 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1611 return SDValue(N, 0);
1614 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615 CSEMap.InsertNode(N, IP);
1619 SDValue Result(N, 0);
1620 if (VT.isScalableVector())
1621 Result = getSplatVector(VT, DL, Result);
1622 else if (VT.isVector())
1623 Result = getSplatBuildVector(VT, DL, Result);
1624 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1630 EVT EltVT = VT.getScalarType();
1631 if (EltVT == MVT::f32)
1632 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633 if (EltVT == MVT::f64)
1634 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1638 APFloat APF = APFloat(Val);
1639 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1641 return getConstantFP(APF, DL, VT, isTarget);
1643 llvm_unreachable("Unsupported type in getConstantFP");
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647 EVT VT, int64_t Offset, bool isTargetGA,
1648 unsigned TargetFlags) {
1649 assert((TargetFlags == 0 || isTargetGA) &&
1650 "Cannot set target flags on target-independent globals");
1652 // Truncate (with sign-extension) the offset value to the pointer size.
1653 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1655 Offset = SignExtend64(Offset, BitWidth);
1658 if (GV->isThreadLocal())
1659 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1661 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1663 FoldingSetNodeID ID;
1664 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1666 ID.AddInteger(Offset);
1667 ID.AddInteger(TargetFlags);
1669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670 return SDValue(E, 0);
1672 auto *N = newSDNode<GlobalAddressSDNode>(
1673 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674 CSEMap.InsertNode(N, IP);
1676 return SDValue(N, 0);
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681 FoldingSetNodeID ID;
1682 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1685 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686 return SDValue(E, 0);
1688 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689 CSEMap.InsertNode(N, IP);
1691 return SDValue(N, 0);
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695 unsigned TargetFlags) {
1696 assert((TargetFlags == 0 || isTarget) &&
1697 "Cannot set target flags on target-independent jump tables");
1698 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699 FoldingSetNodeID ID;
1700 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1702 ID.AddInteger(TargetFlags);
1704 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705 return SDValue(E, 0);
1707 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708 CSEMap.InsertNode(N, IP);
1710 return SDValue(N, 0);
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714 MaybeAlign Alignment, int Offset,
1715 bool isTarget, unsigned TargetFlags) {
1716 assert((TargetFlags == 0 || isTarget) &&
1717 "Cannot set target flags on target-independent globals");
1719 Alignment = shouldOptForSize()
1720 ? getDataLayout().getABITypeAlign(C->getType())
1721 : getDataLayout().getPrefTypeAlign(C->getType());
1722 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723 FoldingSetNodeID ID;
1724 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725 ID.AddInteger(Alignment->value());
1726 ID.AddInteger(Offset);
1728 ID.AddInteger(TargetFlags);
1730 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731 return SDValue(E, 0);
1733 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1735 CSEMap.InsertNode(N, IP);
1737 SDValue V = SDValue(N, 0);
1738 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743 MaybeAlign Alignment, int Offset,
1744 bool isTarget, unsigned TargetFlags) {
1745 assert((TargetFlags == 0 || isTarget) &&
1746 "Cannot set target flags on target-independent globals");
1748 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750 FoldingSetNodeID ID;
1751 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752 ID.AddInteger(Alignment->value());
1753 ID.AddInteger(Offset);
1754 C->addSelectionDAGCSEId(ID);
1755 ID.AddInteger(TargetFlags);
1757 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758 return SDValue(E, 0);
1760 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1762 CSEMap.InsertNode(N, IP);
1764 return SDValue(N, 0);
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768 unsigned TargetFlags) {
1769 FoldingSetNodeID ID;
1770 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771 ID.AddInteger(Index);
1772 ID.AddInteger(Offset);
1773 ID.AddInteger(TargetFlags);
1775 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776 return SDValue(E, 0);
1778 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779 CSEMap.InsertNode(N, IP);
1781 return SDValue(N, 0);
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785 FoldingSetNodeID ID;
1786 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1789 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790 return SDValue(E, 0);
1792 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793 CSEMap.InsertNode(N, IP);
1795 return SDValue(N, 0);
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800 ValueTypeNodes.size())
1801 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1803 SDNode *&N = VT.isExtended() ?
1804 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1806 if (N) return SDValue(N, 0);
1807 N = newSDNode<VTSDNode>(VT);
1809 return SDValue(N, 0);
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813 SDNode *&N = ExternalSymbols[Sym];
1814 if (N) return SDValue(N, 0);
1815 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1817 return SDValue(N, 0);
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821 SDNode *&N = MCSymbols[Sym];
1823 return SDValue(N, 0);
1824 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1826 return SDValue(N, 0);
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830 unsigned TargetFlags) {
1832 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833 if (N) return SDValue(N, 0);
1834 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1836 return SDValue(N, 0);
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840 if ((unsigned)Cond >= CondCodeNodes.size())
1841 CondCodeNodes.resize(Cond+1);
1843 if (!CondCodeNodes[Cond]) {
1844 auto *N = newSDNode<CondCodeSDNode>(Cond);
1845 CondCodeNodes[Cond] = N;
1849 return SDValue(CondCodeNodes[Cond], 0);
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853 APInt One(ResVT.getScalarSizeInBits(), 1);
1854 return getStepVector(DL, ResVT, One);
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859 if (ResVT.isScalableVector())
1861 ISD::STEP_VECTOR, DL, ResVT,
1862 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1864 SmallVector<SDValue, 16> OpsStepConstants;
1865 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866 OpsStepConstants.push_back(
1867 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868 return getBuildVector(ResVT, DL, OpsStepConstants);
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1875 ShuffleVectorSDNode::commuteMask(M);
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879 SDValue N2, ArrayRef<int> Mask) {
1880 assert(VT.getVectorNumElements() == Mask.size() &&
1881 "Must have the same number of vector elements as mask elements!");
1882 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883 "Invalid VECTOR_SHUFFLE");
1885 // Canonicalize shuffle undef, undef -> undef
1886 if (N1.isUndef() && N2.isUndef())
1887 return getUNDEF(VT);
1889 // Validate that all indices in Mask are within the range of the elements
1890 // input to the shuffle.
1891 int NElts = Mask.size();
1892 assert(llvm::all_of(Mask,
1893 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894 "Index out of range");
1896 // Copy the mask so we can do any needed cleanup.
1897 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1899 // Canonicalize shuffle v, v -> v, undef
1902 for (int i = 0; i != NElts; ++i)
1903 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1906 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1908 commuteShuffle(N1, N2, MaskVec);
1910 if (TLI->hasVectorBlend()) {
1911 // If shuffling a splat, try to blend the splat instead. We do this here so
1912 // that even when this arises during lowering we don't have to re-handle it.
1913 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914 BitVector UndefElements;
1915 SDValue Splat = BV->getSplatValue(&UndefElements);
1919 for (int i = 0; i < NElts; ++i) {
1920 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1923 // If this input comes from undef, mark it as such.
1924 if (UndefElements[MaskVec[i] - Offset]) {
1929 // If we can blend a non-undef lane, use that instead.
1930 if (!UndefElements[i])
1931 MaskVec[i] = i + Offset;
1934 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935 BlendSplat(N1BV, 0);
1936 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937 BlendSplat(N2BV, NElts);
1940 // Canonicalize all index into lhs, -> shuffle lhs, undef
1941 // Canonicalize all index into rhs, -> shuffle rhs, undef
1942 bool AllLHS = true, AllRHS = true;
1943 bool N2Undef = N2.isUndef();
1944 for (int i = 0; i != NElts; ++i) {
1945 if (MaskVec[i] >= NElts) {
1950 } else if (MaskVec[i] >= 0) {
1954 if (AllLHS && AllRHS)
1955 return getUNDEF(VT);
1956 if (AllLHS && !N2Undef)
1960 commuteShuffle(N1, N2, MaskVec);
1962 // Reset our undef status after accounting for the mask.
1963 N2Undef = N2.isUndef();
1964 // Re-check whether both sides ended up undef.
1965 if (N1.isUndef() && N2Undef)
1966 return getUNDEF(VT);
1968 // If Identity shuffle return that node.
1969 bool Identity = true, AllSame = true;
1970 for (int i = 0; i != NElts; ++i) {
1971 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1974 if (Identity && NElts)
1977 // Shuffling a constant splat doesn't change the result.
1981 // Look through any bitcasts. We check that these don't change the number
1982 // (and size) of elements and just changes their types.
1983 while (V.getOpcode() == ISD::BITCAST)
1984 V = V->getOperand(0);
1986 // A splat should always show up as a build vector node.
1987 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988 BitVector UndefElements;
1989 SDValue Splat = BV->getSplatValue(&UndefElements);
1990 // If this is a splat of an undef, shuffling it is also undef.
1991 if (Splat && Splat.isUndef())
1992 return getUNDEF(VT);
1995 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1997 // We only have a splat which can skip shuffles if there is a splatted
1998 // value and no undef lanes rearranged by the shuffle.
1999 if (Splat && UndefElements.none()) {
2000 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001 // number of elements match or the value splatted is a zero constant.
2004 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2009 // If the shuffle itself creates a splat, build the vector directly.
2010 if (AllSame && SameNumElts) {
2011 EVT BuildVT = BV->getValueType(0);
2012 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2015 // We may have jumped through bitcasts, so the type of the
2016 // BUILD_VECTOR may not match the type of the shuffle.
2018 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2024 FoldingSetNodeID ID;
2025 SDValue Ops[2] = { N1, N2 };
2026 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027 for (int i = 0; i != NElts; ++i)
2028 ID.AddInteger(MaskVec[i]);
2031 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032 return SDValue(E, 0);
2034 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035 // SDNode doesn't have access to it. This memory will be "leaked" when
2036 // the node is deallocated, but recovered when the NodeAllocator is released.
2037 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038 llvm::copy(MaskVec, MaskAlloc);
2040 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041 dl.getDebugLoc(), MaskAlloc);
2042 createOperands(N, Ops);
2044 CSEMap.InsertNode(N, IP);
2046 SDValue V = SDValue(N, 0);
2047 NewSDValueDbgMsg(V, "Creating new node: ", this);
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052 EVT VT = SV.getValueType(0);
2053 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054 ShuffleVectorSDNode::commuteMask(MaskVec);
2056 SDValue Op0 = SV.getOperand(0);
2057 SDValue Op1 = SV.getOperand(1);
2058 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062 FoldingSetNodeID ID;
2063 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064 ID.AddInteger(RegNo);
2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067 return SDValue(E, 0);
2069 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071 CSEMap.InsertNode(N, IP);
2073 return SDValue(N, 0);
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077 FoldingSetNodeID ID;
2078 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079 ID.AddPointer(RegMask);
2081 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082 return SDValue(E, 0);
2084 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085 CSEMap.InsertNode(N, IP);
2087 return SDValue(N, 0);
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2092 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096 SDValue Root, MCSymbol *Label) {
2097 FoldingSetNodeID ID;
2098 SDValue Ops[] = { Root };
2099 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100 ID.AddPointer(Label);
2102 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103 return SDValue(E, 0);
2106 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107 createOperands(N, Ops);
2109 CSEMap.InsertNode(N, IP);
2111 return SDValue(N, 0);
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115 int64_t Offset, bool isTarget,
2116 unsigned TargetFlags) {
2117 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2119 FoldingSetNodeID ID;
2120 AddNodeIDNode(ID, Opc, getVTList(VT), None);
2122 ID.AddInteger(Offset);
2123 ID.AddInteger(TargetFlags);
2125 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126 return SDValue(E, 0);
2128 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129 CSEMap.InsertNode(N, IP);
2131 return SDValue(N, 0);
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135 FoldingSetNodeID ID;
2136 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2140 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141 return SDValue(E, 0);
2143 auto *N = newSDNode<SrcValueSDNode>(V);
2144 CSEMap.InsertNode(N, IP);
2146 return SDValue(N, 0);
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150 FoldingSetNodeID ID;
2151 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2155 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156 return SDValue(E, 0);
2158 auto *N = newSDNode<MDNodeSDNode>(MD);
2159 CSEMap.InsertNode(N, IP);
2161 return SDValue(N, 0);
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165 if (VT == V.getValueType())
2168 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172 unsigned SrcAS, unsigned DestAS) {
2173 SDValue Ops[] = {Ptr};
2174 FoldingSetNodeID ID;
2175 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176 ID.AddInteger(SrcAS);
2177 ID.AddInteger(DestAS);
2180 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181 return SDValue(E, 0);
2183 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2185 createOperands(N, Ops);
2187 CSEMap.InsertNode(N, IP);
2189 return SDValue(N, 0);
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199 EVT OpTy = Op.getValueType();
2200 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201 if (OpTy == ShTy || OpTy.isVector()) return Op;
2203 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2208 const TargetLowering &TLI = getTargetLoweringInfo();
2209 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210 EVT VT = Node->getValueType(0);
2211 SDValue Tmp1 = Node->getOperand(0);
2212 SDValue Tmp2 = Node->getOperand(1);
2213 const MaybeAlign MA(Node->getConstantOperandVal(3));
2215 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216 Tmp2, MachinePointerInfo(V));
2217 SDValue VAList = VAListLoad;
2219 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2224 getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2228 // Increment the pointer, VAList, to the next vaarg
2229 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230 getConstant(getDataLayout().getTypeAllocSize(
2231 VT.getTypeForEVT(*getContext())),
2232 dl, VAList.getValueType()));
2233 // Store the incremented VAList to the legalized pointer
2235 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236 // Load the actual argument out of the pointer VAList
2237 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2242 const TargetLowering &TLI = getTargetLoweringInfo();
2243 // This defaults to loading a pointer from the input and storing it to the
2244 // output, returning the chain.
2245 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2248 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249 Node->getOperand(2), MachinePointerInfo(VS));
2250 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251 MachinePointerInfo(VD));
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255 const DataLayout &DL = getDataLayout();
2256 Type *Ty = VT.getTypeForEVT(*getContext());
2257 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2259 if (TLI->isTypeLegal(VT) || !VT.isVector())
2262 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263 const Align StackAlign = TFI->getStackAlign();
2265 // See if we can choose a smaller ABI alignment in cases where it's an
2266 // illegal vector type that will get broken down.
2267 if (RedAlign > StackAlign) {
2270 unsigned NumIntermediates;
2271 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272 NumIntermediates, RegisterVT);
2273 Ty = IntermediateVT.getTypeForEVT(*getContext());
2274 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275 if (RedAlign2 < RedAlign)
2276 RedAlign = RedAlign2;
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283 MachineFrameInfo &MFI = MF->getFrameInfo();
2284 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2286 if (Bytes.isScalable())
2287 StackID = TFI->getStackIDForScalableVectors();
2288 // The stack id gives an indication of whether the object is scalable or
2289 // not, so it's safe to pass in the minimum size here.
2290 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291 false, nullptr, StackID);
2292 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296 Type *Ty = VT.getTypeForEVT(*getContext());
2298 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303 TypeSize VT1Size = VT1.getStoreSize();
2304 TypeSize VT2Size = VT2.getStoreSize();
2305 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306 "Don't know how to choose the maximum size when creating a stack "
2309 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2311 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313 const DataLayout &DL = getDataLayout();
2314 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315 return CreateStackTemporary(Bytes, Align);
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319 ISD::CondCode Cond, const SDLoc &dl) {
2320 EVT OpVT = N1.getValueType();
2322 // These setcc operations always fold.
2326 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2328 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2340 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2344 if (OpVT.isInteger()) {
2345 // For EQ and NE, we can always pick a value for the undef to make the
2346 // predicate pass or fail, so we can return undef.
2347 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348 // icmp eq/ne X, undef -> undef.
2349 if ((N1.isUndef() || N2.isUndef()) &&
2350 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351 return getUNDEF(VT);
2353 // If both operands are undef, we can return undef for int comparison.
2354 // icmp undef, undef -> undef.
2355 if (N1.isUndef() && N2.isUndef())
2356 return getUNDEF(VT);
2358 // icmp X, X -> true/false
2359 // icmp X, undef -> true/false because undef could be X.
2361 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2364 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365 const APInt &C2 = N2C->getAPIntValue();
2366 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367 const APInt &C1 = N1C->getAPIntValue();
2369 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2374 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2377 if (N1CFP && N2CFP) {
2378 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2381 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2382 return getUNDEF(VT);
2384 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2386 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2387 return getUNDEF(VT);
2389 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390 R==APFloat::cmpLessThan, dl, VT,
2392 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2393 return getUNDEF(VT);
2395 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2397 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2398 return getUNDEF(VT);
2400 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2402 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2403 return getUNDEF(VT);
2405 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406 R==APFloat::cmpEqual, dl, VT,
2408 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2409 return getUNDEF(VT);
2411 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412 R==APFloat::cmpEqual, dl, VT, OpVT);
2413 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2415 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2417 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418 R==APFloat::cmpEqual, dl, VT,
2420 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2422 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423 R==APFloat::cmpLessThan, dl, VT,
2425 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426 R==APFloat::cmpUnordered, dl, VT,
2428 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2430 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2433 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434 // Ensure that the constant occurs on the RHS.
2435 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2438 return getSetCC(dl, VT, N2, N1, SwappedCond);
2439 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441 // If an operand is known to be a nan (or undef that could be a nan), we can
2443 // Choosing NaN for the undef will always make unordered comparison succeed
2444 // and ordered comparison fails.
2445 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446 switch (ISD::getUnorderedFlavor(Cond)) {
2448 llvm_unreachable("Unknown flavor!");
2449 case 0: // Known false.
2450 return getBoolConstant(false, dl, VT, OpVT);
2451 case 1: // Known true.
2452 return getBoolConstant(true, dl, VT, OpVT);
2453 case 2: // Undefined.
2454 return getUNDEF(VT);
2458 // Could not fold it.
2462 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2463 /// use this predicate to simplify operations downstream.
2464 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2465 unsigned BitWidth = Op.getScalarValueSizeInBits();
2466 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2469 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2470 /// this predicate to simplify operations downstream. Mask is known to be zero
2471 /// for bits that V cannot have.
2472 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2473 unsigned Depth) const {
2474 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2477 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2478 /// DemandedElts. We use this predicate to simplify operations downstream.
2479 /// Mask is known to be zero for bits that V cannot have.
2480 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2481 const APInt &DemandedElts,
2482 unsigned Depth) const {
2483 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2486 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2487 /// DemandedElts. We use this predicate to simplify operations downstream.
2488 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2489 unsigned Depth /* = 0 */) const {
2490 return computeKnownBits(V, DemandedElts, Depth).isZero();
2493 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2494 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2495 unsigned Depth) const {
2496 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2499 /// isSplatValue - Return true if the vector V has the same value
2500 /// across all DemandedElts. For scalable vectors it does not make
2501 /// sense to specify which elements are demanded or undefined, therefore
2502 /// they are simply ignored.
2503 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2504 APInt &UndefElts, unsigned Depth) const {
2505 unsigned Opcode = V.getOpcode();
2506 EVT VT = V.getValueType();
2507 assert(VT.isVector() && "Vector type expected");
2509 if (!VT.isScalableVector() && !DemandedElts)
2510 return false; // No demanded elts, better to assume we don't know anything.
2512 if (Depth >= MaxRecursionDepth)
2513 return false; // Limit search depth.
2515 // Deal with some common cases here that work for both fixed and scalable
2518 case ISD::SPLAT_VECTOR:
2519 UndefElts = V.getOperand(0).isUndef()
2520 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2521 : APInt(DemandedElts.getBitWidth(), 0);
2528 APInt UndefLHS, UndefRHS;
2529 SDValue LHS = V.getOperand(0);
2530 SDValue RHS = V.getOperand(1);
2531 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2532 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2533 UndefElts = UndefLHS | UndefRHS;
2540 case ISD::SIGN_EXTEND:
2541 case ISD::ZERO_EXTEND:
2542 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2544 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2545 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2546 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2550 // We don't support other cases than those above for scalable vectors at
2552 if (VT.isScalableVector())
2555 unsigned NumElts = VT.getVectorNumElements();
2556 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2557 UndefElts = APInt::getZero(NumElts);
2560 case ISD::BUILD_VECTOR: {
2562 for (unsigned i = 0; i != NumElts; ++i) {
2563 SDValue Op = V.getOperand(i);
2565 UndefElts.setBit(i);
2568 if (!DemandedElts[i])
2570 if (Scl && Scl != Op)
2576 case ISD::VECTOR_SHUFFLE: {
2577 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2578 APInt DemandedLHS = APInt::getNullValue(NumElts);
2579 APInt DemandedRHS = APInt::getNullValue(NumElts);
2580 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2581 for (int i = 0; i != (int)NumElts; ++i) {
2584 UndefElts.setBit(i);
2587 if (!DemandedElts[i])
2589 if (M < (int)NumElts)
2590 DemandedLHS.setBit(M);
2592 DemandedRHS.setBit(M - NumElts);
2595 // If we aren't demanding either op, assume there's no splat.
2596 // If we are demanding both ops, assume there's no splat.
2597 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2598 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2601 // See if the demanded elts of the source op is a splat or we only demand
2602 // one element, which should always be a splat.
2603 // TODO: Handle source ops splats with undefs.
2604 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2606 return (SrcElts.countPopulation() == 1) ||
2607 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2608 (SrcElts & SrcUndefs).isZero());
2610 if (!DemandedLHS.isZero())
2611 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2612 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2614 case ISD::EXTRACT_SUBVECTOR: {
2615 // Offset the demanded elts by the subvector index.
2616 SDValue Src = V.getOperand(0);
2617 // We don't support scalable vectors at the moment.
2618 if (Src.getValueType().isScalableVector())
2620 uint64_t Idx = V.getConstantOperandVal(1);
2621 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2623 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2624 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2625 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2630 case ISD::ANY_EXTEND_VECTOR_INREG:
2631 case ISD::SIGN_EXTEND_VECTOR_INREG:
2632 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2633 // Widen the demanded elts by the src element count.
2634 SDValue Src = V.getOperand(0);
2635 // We don't support scalable vectors at the moment.
2636 if (Src.getValueType().isScalableVector())
2638 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2640 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2641 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2642 UndefElts = UndefSrcElts.trunc(NumElts);
2647 case ISD::BITCAST: {
2648 SDValue Src = V.getOperand(0);
2649 EVT SrcVT = Src.getValueType();
2650 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2651 unsigned BitWidth = VT.getScalarSizeInBits();
2653 // Ignore bitcasts from unsupported types.
2654 // TODO: Add fp support?
2655 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2658 // Bitcast 'small element' vector to 'large element' vector.
2659 if ((BitWidth % SrcBitWidth) == 0) {
2660 // See if each sub element is a splat.
2661 unsigned Scale = BitWidth / SrcBitWidth;
2662 unsigned NumSrcElts = SrcVT.getVectorNumElements();
2663 APInt ScaledDemandedElts =
2664 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2665 for (unsigned I = 0; I != Scale; ++I) {
2667 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2668 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2669 SubDemandedElts &= ScaledDemandedElts;
2670 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2672 // TODO: Add support for merging sub undef elements.
2673 if (!SubUndefElts.isZero())
2685 /// Helper wrapper to main isSplatValue function.
2686 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2687 EVT VT = V.getValueType();
2688 assert(VT.isVector() && "Vector type expected");
2693 // For now we don't support this with scalable vectors.
2694 if (!VT.isScalableVector())
2695 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2696 return isSplatValue(V, DemandedElts, UndefElts) &&
2697 (AllowUndefs || !UndefElts);
2700 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2701 V = peekThroughExtractSubvectors(V);
2703 EVT VT = V.getValueType();
2704 unsigned Opcode = V.getOpcode();
2710 if (!VT.isScalableVector())
2711 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2713 if (isSplatValue(V, DemandedElts, UndefElts)) {
2714 if (VT.isScalableVector()) {
2715 // DemandedElts and UndefElts are ignored for scalable vectors, since
2716 // the only supported cases are SPLAT_VECTOR nodes.
2719 // Handle case where all demanded elements are UNDEF.
2720 if (DemandedElts.isSubsetOf(UndefElts)) {
2722 return getUNDEF(VT);
2724 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2730 case ISD::SPLAT_VECTOR:
2733 case ISD::VECTOR_SHUFFLE: {
2734 if (VT.isScalableVector())
2737 // Check if this is a shuffle node doing a splat.
2738 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2739 // getTargetVShiftNode currently struggles without the splat source.
2740 auto *SVN = cast<ShuffleVectorSDNode>(V);
2741 if (!SVN->isSplat())
2743 int Idx = SVN->getSplatIndex();
2744 int NumElts = V.getValueType().getVectorNumElements();
2745 SplatIdx = Idx % NumElts;
2746 return V.getOperand(Idx / NumElts);
2753 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2755 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2756 EVT SVT = SrcVector.getValueType().getScalarType();
2758 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2759 if (!SVT.isInteger())
2761 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2762 if (LegalSVT.bitsLT(SVT))
2765 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2766 getVectorIdxConstant(SplatIdx, SDLoc(V)));
2772 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2773 const APInt &DemandedElts) const {
2774 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2775 V.getOpcode() == ISD::SRA) &&
2776 "Unknown shift node");
2777 unsigned BitWidth = V.getScalarValueSizeInBits();
2778 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2779 // Shifting more than the bitwidth is not valid.
2780 const APInt &ShAmt = SA->getAPIntValue();
2781 if (ShAmt.ult(BitWidth))
2787 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2788 SDValue V, const APInt &DemandedElts) const {
2789 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2790 V.getOpcode() == ISD::SRA) &&
2791 "Unknown shift node");
2792 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2794 unsigned BitWidth = V.getScalarValueSizeInBits();
2795 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2798 const APInt *MinShAmt = nullptr;
2799 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2800 if (!DemandedElts[i])
2802 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2805 // Shifting more than the bitwidth is not valid.
2806 const APInt &ShAmt = SA->getAPIntValue();
2807 if (ShAmt.uge(BitWidth))
2809 if (MinShAmt && MinShAmt->ule(ShAmt))
2816 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2817 SDValue V, const APInt &DemandedElts) const {
2818 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2819 V.getOpcode() == ISD::SRA) &&
2820 "Unknown shift node");
2821 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2823 unsigned BitWidth = V.getScalarValueSizeInBits();
2824 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2827 const APInt *MaxShAmt = nullptr;
2828 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2829 if (!DemandedElts[i])
2831 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2834 // Shifting more than the bitwidth is not valid.
2835 const APInt &ShAmt = SA->getAPIntValue();
2836 if (ShAmt.uge(BitWidth))
2838 if (MaxShAmt && MaxShAmt->uge(ShAmt))
2845 /// Determine which bits of Op are known to be either zero or one and return
2846 /// them in Known. For vectors, the known bits are those that are shared by
2847 /// every vector element.
2848 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2849 EVT VT = Op.getValueType();
2851 // TOOD: Until we have a plan for how to represent demanded elements for
2852 // scalable vectors, we can just bail out for now.
2853 if (Op.getValueType().isScalableVector()) {
2854 unsigned BitWidth = Op.getScalarValueSizeInBits();
2855 return KnownBits(BitWidth);
2858 APInt DemandedElts = VT.isVector()
2859 ? APInt::getAllOnes(VT.getVectorNumElements())
2861 return computeKnownBits(Op, DemandedElts, Depth);
2864 /// Determine which bits of Op are known to be either zero or one and return
2865 /// them in Known. The DemandedElts argument allows us to only collect the known
2866 /// bits that are shared by the requested vector elements.
2867 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2868 unsigned Depth) const {
2869 unsigned BitWidth = Op.getScalarValueSizeInBits();
2871 KnownBits Known(BitWidth); // Don't know anything.
2873 // TOOD: Until we have a plan for how to represent demanded elements for
2874 // scalable vectors, we can just bail out for now.
2875 if (Op.getValueType().isScalableVector())
2878 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2879 // We know all of the bits for a constant!
2880 return KnownBits::makeConstant(C->getAPIntValue());
2882 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2883 // We know all of the bits for a constant fp!
2884 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2887 if (Depth >= MaxRecursionDepth)
2888 return Known; // Limit search depth.
2891 unsigned NumElts = DemandedElts.getBitWidth();
2892 assert((!Op.getValueType().isVector() ||
2893 NumElts == Op.getValueType().getVectorNumElements()) &&
2894 "Unexpected vector size");
2897 return Known; // No demanded elts, better to assume we don't know anything.
2899 unsigned Opcode = Op.getOpcode();
2901 case ISD::MERGE_VALUES:
2902 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
2904 case ISD::BUILD_VECTOR:
2905 // Collect the known bits that are shared by every demanded vector element.
2906 Known.Zero.setAllBits(); Known.One.setAllBits();
2907 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2908 if (!DemandedElts[i])
2911 SDValue SrcOp = Op.getOperand(i);
2912 Known2 = computeKnownBits(SrcOp, Depth + 1);
2914 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2915 if (SrcOp.getValueSizeInBits() != BitWidth) {
2916 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2917 "Expected BUILD_VECTOR implicit truncation");
2918 Known2 = Known2.trunc(BitWidth);
2921 // Known bits are the values that are shared by every demanded element.
2922 Known = KnownBits::commonBits(Known, Known2);
2924 // If we don't know any bits, early out.
2925 if (Known.isUnknown())
2929 case ISD::VECTOR_SHUFFLE: {
2930 // Collect the known bits that are shared by every vector element referenced
2932 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2933 Known.Zero.setAllBits(); Known.One.setAllBits();
2934 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2935 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2936 for (unsigned i = 0; i != NumElts; ++i) {
2937 if (!DemandedElts[i])
2940 int M = SVN->getMaskElt(i);
2942 // For UNDEF elements, we don't know anything about the common state of
2943 // the shuffle result.
2945 DemandedLHS.clearAllBits();
2946 DemandedRHS.clearAllBits();
2950 if ((unsigned)M < NumElts)
2951 DemandedLHS.setBit((unsigned)M % NumElts);
2953 DemandedRHS.setBit((unsigned)M % NumElts);
2955 // Known bits are the values that are shared by every demanded element.
2956 if (!!DemandedLHS) {
2957 SDValue LHS = Op.getOperand(0);
2958 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2959 Known = KnownBits::commonBits(Known, Known2);
2961 // If we don't know any bits, early out.
2962 if (Known.isUnknown())
2964 if (!!DemandedRHS) {
2965 SDValue RHS = Op.getOperand(1);
2966 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2967 Known = KnownBits::commonBits(Known, Known2);
2971 case ISD::CONCAT_VECTORS: {
2972 // Split DemandedElts and test each of the demanded subvectors.
2973 Known.Zero.setAllBits(); Known.One.setAllBits();
2974 EVT SubVectorVT = Op.getOperand(0).getValueType();
2975 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2976 unsigned NumSubVectors = Op.getNumOperands();
2977 for (unsigned i = 0; i != NumSubVectors; ++i) {
2979 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2980 if (!!DemandedSub) {
2981 SDValue Sub = Op.getOperand(i);
2982 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2983 Known = KnownBits::commonBits(Known, Known2);
2985 // If we don't know any bits, early out.
2986 if (Known.isUnknown())
2991 case ISD::INSERT_SUBVECTOR: {
2992 // Demand any elements from the subvector and the remainder from the src its
2994 SDValue Src = Op.getOperand(0);
2995 SDValue Sub = Op.getOperand(1);
2996 uint64_t Idx = Op.getConstantOperandVal(2);
2997 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2998 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2999 APInt DemandedSrcElts = DemandedElts;
3000 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3002 Known.One.setAllBits();
3003 Known.Zero.setAllBits();
3004 if (!!DemandedSubElts) {
3005 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3006 if (Known.isUnknown())
3007 break; // early-out.
3009 if (!!DemandedSrcElts) {
3010 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3011 Known = KnownBits::commonBits(Known, Known2);
3015 case ISD::EXTRACT_SUBVECTOR: {
3016 // Offset the demanded elts by the subvector index.
3017 SDValue Src = Op.getOperand(0);
3018 // Bail until we can represent demanded elements for scalable vectors.
3019 if (Src.getValueType().isScalableVector())
3021 uint64_t Idx = Op.getConstantOperandVal(1);
3022 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3023 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3024 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3027 case ISD::SCALAR_TO_VECTOR: {
3028 // We know about scalar_to_vector as much as we know about it source,
3029 // which becomes the first element of otherwise unknown vector.
3030 if (DemandedElts != 1)
3033 SDValue N0 = Op.getOperand(0);
3034 Known = computeKnownBits(N0, Depth + 1);
3035 if (N0.getValueSizeInBits() != BitWidth)
3036 Known = Known.trunc(BitWidth);
3040 case ISD::BITCAST: {
3041 SDValue N0 = Op.getOperand(0);
3042 EVT SubVT = N0.getValueType();
3043 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3045 // Ignore bitcasts from unsupported types.
3046 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3049 // Fast handling of 'identity' bitcasts.
3050 if (BitWidth == SubBitWidth) {
3051 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3055 bool IsLE = getDataLayout().isLittleEndian();
3057 // Bitcast 'small element' vector to 'large element' scalar/vector.
3058 if ((BitWidth % SubBitWidth) == 0) {
3059 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3061 // Collect known bits for the (larger) output by collecting the known
3062 // bits from each set of sub elements and shift these into place.
3063 // We need to separately call computeKnownBits for each set of
3064 // sub elements as the knownbits for each is likely to be different.
3065 unsigned SubScale = BitWidth / SubBitWidth;
3066 APInt SubDemandedElts(NumElts * SubScale, 0);
3067 for (unsigned i = 0; i != NumElts; ++i)
3068 if (DemandedElts[i])
3069 SubDemandedElts.setBit(i * SubScale);
3071 for (unsigned i = 0; i != SubScale; ++i) {
3072 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3074 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3075 Known.insertBits(Known2, SubBitWidth * Shifts);
3079 // Bitcast 'large element' scalar/vector to 'small element' vector.
3080 if ((SubBitWidth % BitWidth) == 0) {
3081 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3083 // Collect known bits for the (smaller) output by collecting the known
3084 // bits from the overlapping larger input elements and extracting the
3085 // sub sections we actually care about.
3086 unsigned SubScale = SubBitWidth / BitWidth;
3087 APInt SubDemandedElts =
3088 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3089 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3091 Known.Zero.setAllBits(); Known.One.setAllBits();
3092 for (unsigned i = 0; i != NumElts; ++i)
3093 if (DemandedElts[i]) {
3094 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3095 unsigned Offset = (Shifts % SubScale) * BitWidth;
3096 Known = KnownBits::commonBits(Known,
3097 Known2.extractBits(BitWidth, Offset));
3098 // If we don't know any bits, early out.
3099 if (Known.isUnknown())
3106 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3107 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3112 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3113 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3118 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3119 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3124 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3125 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3126 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3127 // TODO: SelfMultiply can be poison, but not undef.
3129 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3130 Op.getOperand(0), DemandedElts, false, Depth + 1);
3131 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3133 // If the multiplication is known not to overflow, the product of a number
3134 // with itself is non-negative. Only do this if we didn't already computed
3135 // the opposite value for the sign bit.
3136 if (Op->getFlags().hasNoSignedWrap() &&
3137 Op.getOperand(0) == Op.getOperand(1) &&
3138 !Known.isNegative())
3139 Known.makeNonNegative();
3143 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3144 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3145 Known = KnownBits::mulhu(Known, Known2);
3149 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3150 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3151 Known = KnownBits::mulhs(Known, Known2);
3154 case ISD::UMUL_LOHI: {
3155 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3156 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3157 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3159 if (Op.getResNo() == 0)
3160 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3162 Known = KnownBits::mulhu(Known, Known2);
3165 case ISD::SMUL_LOHI: {
3166 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3167 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3168 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3169 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3170 if (Op.getResNo() == 0)
3171 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3173 Known = KnownBits::mulhs(Known, Known2);
3176 case ISD::AVGCEILU: {
3177 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3178 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3179 Known = Known.zext(BitWidth + 1);
3180 Known2 = Known2.zext(BitWidth + 1);
3181 KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3182 Known = KnownBits::computeForAddCarry(Known, Known2, One);
3183 Known = Known.extractBits(BitWidth, 1);
3188 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3189 // If we don't know any bits, early out.
3190 if (Known.isUnknown())
3192 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3194 // Only known if known in both the LHS and RHS.
3195 Known = KnownBits::commonBits(Known, Known2);
3197 case ISD::SELECT_CC:
3198 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3199 // If we don't know any bits, early out.
3200 if (Known.isUnknown())
3202 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3204 // Only known if known in both the LHS and RHS.
3205 Known = KnownBits::commonBits(Known, Known2);
3209 if (Op.getResNo() != 1)
3211 // The boolean result conforms to getBooleanContents.
3212 // If we know the result of a setcc has the top bits zero, use this info.
3213 // We know that we have an integer-based boolean since these operations
3214 // are only available for integer.
3215 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3216 TargetLowering::ZeroOrOneBooleanContent &&
3218 Known.Zero.setBitsFrom(1);
3221 case ISD::SETCCCARRY:
3222 case ISD::STRICT_FSETCC:
3223 case ISD::STRICT_FSETCCS: {
3224 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3225 // If we know the result of a setcc has the top bits zero, use this info.
3226 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3227 TargetLowering::ZeroOrOneBooleanContent &&
3229 Known.Zero.setBitsFrom(1);
3233 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3234 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3235 Known = KnownBits::shl(Known, Known2);
3237 // Minimum shift low bits are known zero.
3238 if (const APInt *ShMinAmt =
3239 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3240 Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3243 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3244 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3245 Known = KnownBits::lshr(Known, Known2);
3247 // Minimum shift high bits are known zero.
3248 if (const APInt *ShMinAmt =
3249 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3250 Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3253 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3254 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3255 Known = KnownBits::ashr(Known, Known2);
3256 // TODO: Add minimum shift high known sign bits.
3260 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3261 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3263 // For fshl, 0-shift returns the 1st arg.
3264 // For fshr, 0-shift returns the 2nd arg.
3266 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3267 DemandedElts, Depth + 1);
3271 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3272 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3273 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3274 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3275 if (Opcode == ISD::FSHL) {
3278 Known2.One.lshrInPlace(BitWidth - Amt);
3279 Known2.Zero.lshrInPlace(BitWidth - Amt);
3281 Known.One <<= BitWidth - Amt;
3282 Known.Zero <<= BitWidth - Amt;
3283 Known2.One.lshrInPlace(Amt);
3284 Known2.Zero.lshrInPlace(Amt);
3286 Known.One |= Known2.One;
3287 Known.Zero |= Known2.Zero;
3290 case ISD::SHL_PARTS:
3291 case ISD::SRA_PARTS:
3292 case ISD::SRL_PARTS: {
3293 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3295 // Collect lo/hi source values and concatenate.
3296 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3297 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3298 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3299 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3300 Known = Known2.concat(Known);
3302 // Collect shift amount.
3303 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3305 if (Opcode == ISD::SHL_PARTS)
3306 Known = KnownBits::shl(Known, Known2);
3307 else if (Opcode == ISD::SRA_PARTS)
3308 Known = KnownBits::ashr(Known, Known2);
3309 else // if (Opcode == ISD::SRL_PARTS)
3310 Known = KnownBits::lshr(Known, Known2);
3312 // TODO: Minimum shift low/high bits are known zero.
3314 if (Op.getResNo() == 0)
3315 Known = Known.extractBits(LoBits, 0);
3317 Known = Known.extractBits(HiBits, LoBits);
3320 case ISD::SIGN_EXTEND_INREG: {
3321 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3322 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3323 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3327 case ISD::CTTZ_ZERO_UNDEF: {
3328 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3329 // If we have a known 1, its position is our upper bound.
3330 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3331 unsigned LowBits = Log2_32(PossibleTZ) + 1;
3332 Known.Zero.setBitsFrom(LowBits);
3336 case ISD::CTLZ_ZERO_UNDEF: {
3337 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3338 // If we have a known 1, its position is our upper bound.
3339 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3340 unsigned LowBits = Log2_32(PossibleLZ) + 1;
3341 Known.Zero.setBitsFrom(LowBits);
3345 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3346 // If we know some of the bits are zero, they can't be one.
3347 unsigned PossibleOnes = Known2.countMaxPopulation();
3348 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3352 // Parity returns 0 everywhere but the LSB.
3353 Known.Zero.setBitsFrom(1);
3357 LoadSDNode *LD = cast<LoadSDNode>(Op);
3358 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3359 if (ISD::isNON_EXTLoad(LD) && Cst) {
3360 // Determine any common known bits from the loaded constant pool value.
3361 Type *CstTy = Cst->getType();
3362 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3363 // If its a vector splat, then we can (quickly) reuse the scalar path.
3364 // NOTE: We assume all elements match and none are UNDEF.
3365 if (CstTy->isVectorTy()) {
3366 if (const Constant *Splat = Cst->getSplatValue()) {
3368 CstTy = Cst->getType();
3371 // TODO - do we need to handle different bitwidths?
3372 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3373 // Iterate across all vector elements finding common known bits.
3374 Known.One.setAllBits();
3375 Known.Zero.setAllBits();
3376 for (unsigned i = 0; i != NumElts; ++i) {
3377 if (!DemandedElts[i])
3379 if (Constant *Elt = Cst->getAggregateElement(i)) {
3380 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3381 const APInt &Value = CInt->getValue();
3383 Known.Zero &= ~Value;
3386 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3387 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3389 Known.Zero &= ~Value;
3393 Known.One.clearAllBits();
3394 Known.Zero.clearAllBits();
3397 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3398 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3399 Known = KnownBits::makeConstant(CInt->getValue());
3400 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3402 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3406 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3407 // If this is a ZEXTLoad and we are looking at the loaded value.
3408 EVT VT = LD->getMemoryVT();
3409 unsigned MemBits = VT.getScalarSizeInBits();
3410 Known.Zero.setBitsFrom(MemBits);
3411 } else if (const MDNode *Ranges = LD->getRanges()) {
3412 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3413 computeKnownBitsFromRangeMetadata(*Ranges, Known);
3417 case ISD::ZERO_EXTEND_VECTOR_INREG: {
3418 EVT InVT = Op.getOperand(0).getValueType();
3419 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3420 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3421 Known = Known.zext(BitWidth);
3424 case ISD::ZERO_EXTEND: {
3425 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3426 Known = Known.zext(BitWidth);
3429 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3430 EVT InVT = Op.getOperand(0).getValueType();
3431 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3432 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3433 // If the sign bit is known to be zero or one, then sext will extend
3434 // it to the top bits, else it will just zext.
3435 Known = Known.sext(BitWidth);
3438 case ISD::SIGN_EXTEND: {
3439 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3440 // If the sign bit is known to be zero or one, then sext will extend
3441 // it to the top bits, else it will just zext.
3442 Known = Known.sext(BitWidth);
3445 case ISD::ANY_EXTEND_VECTOR_INREG: {
3446 EVT InVT = Op.getOperand(0).getValueType();
3447 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3448 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3449 Known = Known.anyext(BitWidth);
3452 case ISD::ANY_EXTEND: {
3453 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3454 Known = Known.anyext(BitWidth);
3457 case ISD::TRUNCATE: {
3458 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3459 Known = Known.trunc(BitWidth);
3462 case ISD::AssertZext: {
3463 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3464 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3465 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3466 Known.Zero |= (~InMask);
3467 Known.One &= (~Known.Zero);
3470 case ISD::AssertAlign: {
3471 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3472 assert(LogOfAlign != 0);
3474 // TODO: Should use maximum with source
3475 // If a node is guaranteed to be aligned, set low zero bits accordingly as
3476 // well as clearing one bits.
3477 Known.Zero.setLowBits(LogOfAlign);
3478 Known.One.clearLowBits(LogOfAlign);
3482 // All bits are zero except the low bit.
3483 Known.Zero.setBitsFrom(1);
3488 case ISD::SSUBO_CARRY:
3489 if (Op.getResNo() == 1) {
3490 // If we know the result of a setcc has the top bits zero, use this info.
3491 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3492 TargetLowering::ZeroOrOneBooleanContent &&
3494 Known.Zero.setBitsFrom(1);
3500 assert(Op.getResNo() == 0 &&
3501 "We only compute knownbits for the difference here.");
3503 // TODO: Compute influence of the carry operand.
3504 if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
3507 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3508 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3509 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3516 case ISD::SADDO_CARRY:
3517 if (Op.getResNo() == 1) {
3518 // If we know the result of a setcc has the top bits zero, use this info.
3519 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3520 TargetLowering::ZeroOrOneBooleanContent &&
3522 Known.Zero.setBitsFrom(1);
3529 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3531 // With ADDE and ADDCARRY, a carry bit may be added in.
3533 if (Opcode == ISD::ADDE)
3534 // Can't track carry from glue, set carry to unknown.
3536 else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
3537 // TODO: Compute known bits for the carry operand. Not sure if it is worth
3538 // the trouble (how often will we find a known carry bit). And I haven't
3539 // tested this very much yet, but something like this might work:
3540 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3541 // Carry = Carry.zextOrTrunc(1, false);
3546 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3547 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3548 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3554 Known = KnownBits::udiv(Known, Known2);
3558 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3559 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3560 Known = KnownBits::srem(Known, Known2);
3564 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3565 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3566 Known = KnownBits::urem(Known, Known2);
3569 case ISD::EXTRACT_ELEMENT: {
3570 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3571 const unsigned Index = Op.getConstantOperandVal(1);
3572 const unsigned EltBitWidth = Op.getValueSizeInBits();
3574 // Remove low part of known bits mask
3575 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3576 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3578 // Remove high part of known bit mask
3579 Known = Known.trunc(EltBitWidth);
3582 case ISD::EXTRACT_VECTOR_ELT: {
3583 SDValue InVec = Op.getOperand(0);
3584 SDValue EltNo = Op.getOperand(1);
3585 EVT VecVT = InVec.getValueType();
3586 // computeKnownBits not yet implemented for scalable vectors.
3587 if (VecVT.isScalableVector())
3589 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3590 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3592 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3593 // anything about the extended bits.
3594 if (BitWidth > EltBitWidth)
3595 Known = Known.trunc(EltBitWidth);
3597 // If we know the element index, just demand that vector element, else for
3598 // an unknown element index, ignore DemandedElts and demand them all.
3599 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3600 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3601 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3603 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3605 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3606 if (BitWidth > EltBitWidth)
3607 Known = Known.anyext(BitWidth);
3610 case ISD::INSERT_VECTOR_ELT: {
3611 // If we know the element index, split the demand between the
3612 // source vector and the inserted element, otherwise assume we need
3613 // the original demanded vector elements and the value.
3614 SDValue InVec = Op.getOperand(0);
3615 SDValue InVal = Op.getOperand(1);
3616 SDValue EltNo = Op.getOperand(2);
3617 bool DemandedVal = true;
3618 APInt DemandedVecElts = DemandedElts;
3619 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3620 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3621 unsigned EltIdx = CEltNo->getZExtValue();
3622 DemandedVal = !!DemandedElts[EltIdx];
3623 DemandedVecElts.clearBit(EltIdx);
3625 Known.One.setAllBits();
3626 Known.Zero.setAllBits();
3628 Known2 = computeKnownBits(InVal, Depth + 1);
3629 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3631 if (!!DemandedVecElts) {
3632 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3633 Known = KnownBits::commonBits(Known, Known2);
3637 case ISD::BITREVERSE: {
3638 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3639 Known = Known2.reverseBits();
3643 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3644 Known = Known2.byteSwap();
3648 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3649 Known = Known2.abs();
3652 case ISD::USUBSAT: {
3653 // The result of usubsat will never be larger than the LHS.
3654 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3659 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3660 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3661 Known = KnownBits::umin(Known, Known2);
3665 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667 Known = KnownBits::umax(Known, Known2);
3672 // If we have a clamp pattern, we know that the number of sign bits will be
3673 // the minimum of the clamp min/max range.
3674 bool IsMax = (Opcode == ISD::SMAX);
3675 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3676 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3677 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3679 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3680 if (CstLow && CstHigh) {
3682 std::swap(CstLow, CstHigh);
3684 const APInt &ValueLow = CstLow->getAPIntValue();
3685 const APInt &ValueHigh = CstHigh->getAPIntValue();
3686 if (ValueLow.sle(ValueHigh)) {
3687 unsigned LowSignBits = ValueLow.getNumSignBits();
3688 unsigned HighSignBits = ValueHigh.getNumSignBits();
3689 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3690 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3691 Known.One.setHighBits(MinSignBits);
3694 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3695 Known.Zero.setHighBits(MinSignBits);
3701 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3702 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3704 Known = KnownBits::smax(Known, Known2);
3706 Known = KnownBits::smin(Known, Known2);
3708 // For SMAX, if CstLow is non-negative we know the result will be
3709 // non-negative and thus all sign bits are 0.
3710 // TODO: There's an equivalent of this for smin with negative constant for
3712 if (IsMax && CstLow) {
3713 const APInt &ValueLow = CstLow->getAPIntValue();
3714 if (ValueLow.isNonNegative()) {
3715 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3716 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3722 case ISD::FP_TO_UINT_SAT: {
3723 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3724 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3725 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3728 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3729 if (Op.getResNo() == 1) {
3730 // The boolean result conforms to getBooleanContents.
3731 // If we know the result of a setcc has the top bits zero, use this info.
3732 // We know that we have an integer-based boolean since these operations
3733 // are only available for integer.
3734 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3735 TargetLowering::ZeroOrOneBooleanContent &&
3737 Known.Zero.setBitsFrom(1);
3741 case ISD::ATOMIC_CMP_SWAP:
3742 case ISD::ATOMIC_SWAP:
3743 case ISD::ATOMIC_LOAD_ADD:
3744 case ISD::ATOMIC_LOAD_SUB:
3745 case ISD::ATOMIC_LOAD_AND:
3746 case ISD::ATOMIC_LOAD_CLR:
3747 case ISD::ATOMIC_LOAD_OR:
3748 case ISD::ATOMIC_LOAD_XOR:
3749 case ISD::ATOMIC_LOAD_NAND:
3750 case ISD::ATOMIC_LOAD_MIN:
3751 case ISD::ATOMIC_LOAD_MAX:
3752 case ISD::ATOMIC_LOAD_UMIN:
3753 case ISD::ATOMIC_LOAD_UMAX:
3754 case ISD::ATOMIC_LOAD: {
3756 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3757 // If we are looking at the loaded value.
3758 if (Op.getResNo() == 0) {
3759 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3760 Known.Zero.setBitsFrom(MemBits);
3764 case ISD::FrameIndex:
3765 case ISD::TargetFrameIndex:
3766 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3767 Known, getMachineFunction());
3771 if (Opcode < ISD::BUILTIN_OP_END)
3774 case ISD::INTRINSIC_WO_CHAIN:
3775 case ISD::INTRINSIC_W_CHAIN:
3776 case ISD::INTRINSIC_VOID:
3777 // Allow the target to implement this method for its nodes.
3778 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3782 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3786 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3788 // X + 0 never overflow
3789 if (isNullConstant(N1))
3792 KnownBits N1Known = computeKnownBits(N1);
3793 if (N1Known.Zero.getBoolValue()) {
3794 KnownBits N0Known = computeKnownBits(N0);
3797 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3802 // mulhi + 1 never overflow
3803 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3804 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3807 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3808 KnownBits N0Known = computeKnownBits(N0);
3810 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3814 return OFK_Sometime;
3817 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3818 EVT OpVT = Val.getValueType();
3819 unsigned BitWidth = OpVT.getScalarSizeInBits();
3821 // Is the constant a known power of 2?
3822 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3823 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3825 // A left-shift of a constant one will have exactly one bit set because
3826 // shifting the bit off the end is undefined.
3827 if (Val.getOpcode() == ISD::SHL) {
3828 auto *C = isConstOrConstSplat(Val.getOperand(0));
3829 if (C && C->getAPIntValue() == 1)
3833 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3835 if (Val.getOpcode() == ISD::SRL) {
3836 auto *C = isConstOrConstSplat(Val.getOperand(0));
3837 if (C && C->getAPIntValue().isSignMask())
3841 // Are all operands of a build vector constant powers of two?
3842 if (Val.getOpcode() == ISD::BUILD_VECTOR)
3843 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3845 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3850 // Is the operand of a splat vector a constant power of two?
3851 if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3853 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3856 // vscale(power-of-two) is a power-of-two for some targets
3857 if (Val.getOpcode() == ISD::VSCALE &&
3858 getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
3859 isKnownToBeAPowerOfTwo(Val.getOperand(0)))
3862 // More could be done here, though the above checks are enough
3863 // to handle some common cases.
3865 // Fall back to computeKnownBits to catch other known cases.
3866 KnownBits Known = computeKnownBits(Val);
3867 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3870 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3871 EVT VT = Op.getValueType();
3873 // TODO: Assume we don't know anything for now.
3874 if (VT.isScalableVector())
3877 APInt DemandedElts = VT.isVector()
3878 ? APInt::getAllOnes(VT.getVectorNumElements())
3880 return ComputeNumSignBits(Op, DemandedElts, Depth);
3883 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3884 unsigned Depth) const {
3885 EVT VT = Op.getValueType();
3886 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3887 unsigned VTBits = VT.getScalarSizeInBits();
3888 unsigned NumElts = DemandedElts.getBitWidth();
3890 unsigned FirstAnswer = 1;
3892 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3893 const APInt &Val = C->getAPIntValue();
3894 return Val.getNumSignBits();
3897 if (Depth >= MaxRecursionDepth)
3898 return 1; // Limit search depth.
3900 if (!DemandedElts || VT.isScalableVector())
3901 return 1; // No demanded elts, better to assume we don't know anything.
3903 unsigned Opcode = Op.getOpcode();
3906 case ISD::AssertSext:
3907 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3908 return VTBits-Tmp+1;
3909 case ISD::AssertZext:
3910 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3912 case ISD::MERGE_VALUES:
3913 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
3915 case ISD::BUILD_VECTOR:
3917 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3918 if (!DemandedElts[i])
3921 SDValue SrcOp = Op.getOperand(i);
3922 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3924 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3925 if (SrcOp.getValueSizeInBits() != VTBits) {
3926 assert(SrcOp.getValueSizeInBits() > VTBits &&
3927 "Expected BUILD_VECTOR implicit truncation");
3928 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3929 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3931 Tmp = std::min(Tmp, Tmp2);
3935 case ISD::VECTOR_SHUFFLE: {
3936 // Collect the minimum number of sign bits that are shared by every vector
3937 // element referenced by the shuffle.
3938 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3939 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3940 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3941 for (unsigned i = 0; i != NumElts; ++i) {
3942 int M = SVN->getMaskElt(i);
3943 if (!DemandedElts[i])
3945 // For UNDEF elements, we don't know anything about the common state of
3946 // the shuffle result.
3949 if ((unsigned)M < NumElts)
3950 DemandedLHS.setBit((unsigned)M % NumElts);
3952 DemandedRHS.setBit((unsigned)M % NumElts);
3954 Tmp = std::numeric_limits<unsigned>::max();
3956 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3957 if (!!DemandedRHS) {
3958 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3959 Tmp = std::min(Tmp, Tmp2);
3961 // If we don't know anything, early out and try computeKnownBits fall-back.
3964 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3968 case ISD::BITCAST: {
3969 SDValue N0 = Op.getOperand(0);
3970 EVT SrcVT = N0.getValueType();
3971 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3973 // Ignore bitcasts from unsupported types..
3974 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3977 // Fast handling of 'identity' bitcasts.
3978 if (VTBits == SrcBits)
3979 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3981 bool IsLE = getDataLayout().isLittleEndian();
3983 // Bitcast 'large element' scalar/vector to 'small element' vector.
3984 if ((SrcBits % VTBits) == 0) {
3985 assert(VT.isVector() && "Expected bitcast to vector");
3987 unsigned Scale = SrcBits / VTBits;
3988 APInt SrcDemandedElts =
3989 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3991 // Fast case - sign splat can be simply split across the small elements.
3992 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3996 // Slow case - determine how far the sign extends into each sub-element.
3998 for (unsigned i = 0; i != NumElts; ++i)
3999 if (DemandedElts[i]) {
4000 unsigned SubOffset = i % Scale;
4001 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4002 SubOffset = SubOffset * VTBits;
4003 if (Tmp <= SubOffset)
4005 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4012 case ISD::FP_TO_SINT_SAT:
4013 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4014 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4015 return VTBits - Tmp + 1;
4016 case ISD::SIGN_EXTEND:
4017 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4018 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4019 case ISD::SIGN_EXTEND_INREG:
4020 // Max of the input and what this extends.
4021 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4023 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4024 return std::max(Tmp, Tmp2);
4025 case ISD::SIGN_EXTEND_VECTOR_INREG: {
4026 SDValue Src = Op.getOperand(0);
4027 EVT SrcVT = Src.getValueType();
4028 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4029 Tmp = VTBits - SrcVT.getScalarSizeInBits();
4030 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4033 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4034 // SRA X, C -> adds C sign bits.
4035 if (const APInt *ShAmt =
4036 getValidMinimumShiftAmountConstant(Op, DemandedElts))
4037 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4040 if (const APInt *ShAmt =
4041 getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4042 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4043 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4044 if (ShAmt->ult(Tmp))
4045 return Tmp - ShAmt->getZExtValue();
4050 case ISD::XOR: // NOT is handled here.
4051 // Logical binary ops preserve the number of sign bits at the worst.
4052 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4054 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4055 FirstAnswer = std::min(Tmp, Tmp2);
4056 // We computed what we know about the sign bits as our first
4057 // answer. Now proceed to the generic code that uses
4058 // computeKnownBits, and pick whichever answer is better.
4064 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4065 if (Tmp == 1) return 1; // Early out.
4066 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4067 return std::min(Tmp, Tmp2);
4068 case ISD::SELECT_CC:
4069 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4070 if (Tmp == 1) return 1; // Early out.
4071 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4072 return std::min(Tmp, Tmp2);
4076 // If we have a clamp pattern, we know that the number of sign bits will be
4077 // the minimum of the clamp min/max range.
4078 bool IsMax = (Opcode == ISD::SMAX);
4079 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4080 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4081 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4083 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4084 if (CstLow && CstHigh) {
4086 std::swap(CstLow, CstHigh);
4087 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4088 Tmp = CstLow->getAPIntValue().getNumSignBits();
4089 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4090 return std::min(Tmp, Tmp2);
4094 // Fallback - just get the minimum number of sign bits of the operands.
4095 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4097 return 1; // Early out.
4098 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4099 return std::min(Tmp, Tmp2);
4103 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4105 return 1; // Early out.
4106 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4107 return std::min(Tmp, Tmp2);
4110 case ISD::SADDO_CARRY:
4114 case ISD::SSUBO_CARRY:
4118 if (Op.getResNo() != 1)
4120 // The boolean result conforms to getBooleanContents. Fall through.
4121 // If setcc returns 0/-1, all bits are sign bits.
4122 // We know that we have an integer-based boolean since these operations
4123 // are only available for integer.
4124 if (TLI->getBooleanContents(VT.isVector(), false) ==
4125 TargetLowering::ZeroOrNegativeOneBooleanContent)
4129 case ISD::SETCCCARRY:
4130 case ISD::STRICT_FSETCC:
4131 case ISD::STRICT_FSETCCS: {
4132 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4133 // If setcc returns 0/-1, all bits are sign bits.
4134 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4135 TargetLowering::ZeroOrNegativeOneBooleanContent)
4141 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4143 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4147 if (ConstantSDNode *C =
4148 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4149 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4151 // Handle rotate right by N like a rotate left by 32-N.
4152 if (Opcode == ISD::ROTR)
4153 RotAmt = (VTBits - RotAmt) % VTBits;
4155 // If we aren't rotating out all of the known-in sign bits, return the
4156 // number that are left. This handles rotl(sext(x), 1) for example.
4157 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4162 // Add can have at most one carry bit. Thus we know that the output
4163 // is, at worst, one more bit than the inputs.
4164 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4165 if (Tmp == 1) return 1; // Early out.
4167 // Special case decrementing a value (ADD X, -1):
4168 if (ConstantSDNode *CRHS =
4169 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4170 if (CRHS->isAllOnes()) {
4172 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4174 // If the input is known to be 0 or 1, the output is 0/-1, which is all
4176 if ((Known.Zero | 1).isAllOnes())
4179 // If we are subtracting one from a positive number, there is no carry
4180 // out of the result.
4181 if (Known.isNonNegative())
4185 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4186 if (Tmp2 == 1) return 1; // Early out.
4187 return std::min(Tmp, Tmp2) - 1;
4189 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4190 if (Tmp2 == 1) return 1; // Early out.
4193 if (ConstantSDNode *CLHS =
4194 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4195 if (CLHS->isZero()) {
4197 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4198 // If the input is known to be 0 or 1, the output is 0/-1, which is all
4200 if ((Known.Zero | 1).isAllOnes())
4203 // If the input is known to be positive (the sign bit is known clear),
4204 // the output of the NEG has the same number of sign bits as the input.
4205 if (Known.isNonNegative())
4208 // Otherwise, we treat this like a SUB.
4211 // Sub can have at most one carry bit. Thus we know that the output
4212 // is, at worst, one more bit than the inputs.
4213 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4214 if (Tmp == 1) return 1; // Early out.
4215 return std::min(Tmp, Tmp2) - 1;
4217 // The output of the Mul can be at most twice the valid bits in the inputs.
4218 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4219 if (SignBitsOp0 == 1)
4221 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4222 if (SignBitsOp1 == 1)
4224 unsigned OutValidBits =
4225 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4226 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4229 // The sign bit is the LHS's sign bit, except when the result of the
4230 // remainder is zero. The magnitude of the result should be less than or
4231 // equal to the magnitude of the LHS. Therefore, the result should have
4232 // at least as many sign bits as the left hand side.
4233 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4234 case ISD::TRUNCATE: {
4235 // Check if the sign bits of source go down as far as the truncated value.
4236 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4237 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4238 if (NumSrcSignBits > (NumSrcBits - VTBits))
4239 return NumSrcSignBits - (NumSrcBits - VTBits);
4242 case ISD::EXTRACT_ELEMENT: {
4243 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4244 const int BitWidth = Op.getValueSizeInBits();
4245 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4247 // Get reverse index (starting from 1), Op1 value indexes elements from
4248 // little end. Sign starts at big end.
4249 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4251 // If the sign portion ends in our element the subtraction gives correct
4252 // result. Otherwise it gives either negative or > bitwidth result
4253 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4255 case ISD::INSERT_VECTOR_ELT: {
4256 // If we know the element index, split the demand between the
4257 // source vector and the inserted element, otherwise assume we need
4258 // the original demanded vector elements and the value.
4259 SDValue InVec = Op.getOperand(0);
4260 SDValue InVal = Op.getOperand(1);
4261 SDValue EltNo = Op.getOperand(2);
4262 bool DemandedVal = true;
4263 APInt DemandedVecElts = DemandedElts;
4264 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4265 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4266 unsigned EltIdx = CEltNo->getZExtValue();
4267 DemandedVal = !!DemandedElts[EltIdx];
4268 DemandedVecElts.clearBit(EltIdx);
4270 Tmp = std::numeric_limits<unsigned>::max();
4272 // TODO - handle implicit truncation of inserted elements.
4273 if (InVal.getScalarValueSizeInBits() != VTBits)
4275 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4276 Tmp = std::min(Tmp, Tmp2);
4278 if (!!DemandedVecElts) {
4279 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4280 Tmp = std::min(Tmp, Tmp2);
4282 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4285 case ISD::EXTRACT_VECTOR_ELT: {
4286 SDValue InVec = Op.getOperand(0);
4287 SDValue EltNo = Op.getOperand(1);
4288 EVT VecVT = InVec.getValueType();
4289 // ComputeNumSignBits not yet implemented for scalable vectors.
4290 if (VecVT.isScalableVector())
4292 const unsigned BitWidth = Op.getValueSizeInBits();
4293 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4294 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4296 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4297 // anything about sign bits. But if the sizes match we can derive knowledge
4298 // about sign bits from the vector operand.
4299 if (BitWidth != EltBitWidth)
4302 // If we know the element index, just demand that vector element, else for
4303 // an unknown element index, ignore DemandedElts and demand them all.
4304 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4305 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4306 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4308 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4310 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4312 case ISD::EXTRACT_SUBVECTOR: {
4313 // Offset the demanded elts by the subvector index.
4314 SDValue Src = Op.getOperand(0);
4315 // Bail until we can represent demanded elements for scalable vectors.
4316 if (Src.getValueType().isScalableVector())
4318 uint64_t Idx = Op.getConstantOperandVal(1);
4319 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4320 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4321 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4323 case ISD::CONCAT_VECTORS: {
4324 // Determine the minimum number of sign bits across all demanded
4325 // elts of the input vectors. Early out if the result is already 1.
4326 Tmp = std::numeric_limits<unsigned>::max();
4327 EVT SubVectorVT = Op.getOperand(0).getValueType();
4328 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4329 unsigned NumSubVectors = Op.getNumOperands();
4330 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4332 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4335 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4336 Tmp = std::min(Tmp, Tmp2);
4338 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4341 case ISD::INSERT_SUBVECTOR: {
4342 // Demand any elements from the subvector and the remainder from the src its
4344 SDValue Src = Op.getOperand(0);
4345 SDValue Sub = Op.getOperand(1);
4346 uint64_t Idx = Op.getConstantOperandVal(2);
4347 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4348 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4349 APInt DemandedSrcElts = DemandedElts;
4350 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4352 Tmp = std::numeric_limits<unsigned>::max();
4353 if (!!DemandedSubElts) {
4354 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4356 return 1; // early-out
4358 if (!!DemandedSrcElts) {
4359 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4360 Tmp = std::min(Tmp, Tmp2);
4362 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4365 case ISD::ATOMIC_CMP_SWAP:
4366 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4367 case ISD::ATOMIC_SWAP:
4368 case ISD::ATOMIC_LOAD_ADD:
4369 case ISD::ATOMIC_LOAD_SUB:
4370 case ISD::ATOMIC_LOAD_AND:
4371 case ISD::ATOMIC_LOAD_CLR:
4372 case ISD::ATOMIC_LOAD_OR:
4373 case ISD::ATOMIC_LOAD_XOR:
4374 case ISD::ATOMIC_LOAD_NAND:
4375 case ISD::ATOMIC_LOAD_MIN:
4376 case ISD::ATOMIC_LOAD_MAX:
4377 case ISD::ATOMIC_LOAD_UMIN:
4378 case ISD::ATOMIC_LOAD_UMAX:
4379 case ISD::ATOMIC_LOAD: {
4380 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4381 // If we are looking at the loaded value.
4382 if (Op.getResNo() == 0) {
4384 return 1; // early-out
4385 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4386 return VTBits - Tmp + 1;
4387 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4388 return VTBits - Tmp;
4394 // If we are looking at the loaded value of the SDNode.
4395 if (Op.getResNo() == 0) {
4396 // Handle LOADX separately here. EXTLOAD case will fallthrough.
4397 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4398 unsigned ExtType = LD->getExtensionType();
4401 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4402 Tmp = LD->getMemoryVT().getScalarSizeInBits();
4403 return VTBits - Tmp + 1;
4404 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4405 Tmp = LD->getMemoryVT().getScalarSizeInBits();
4406 return VTBits - Tmp;
4407 case ISD::NON_EXTLOAD:
4408 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4409 // We only need to handle vectors - computeKnownBits should handle
4411 Type *CstTy = Cst->getType();
4412 if (CstTy->isVectorTy() &&
4413 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4414 VTBits == CstTy->getScalarSizeInBits()) {
4416 for (unsigned i = 0; i != NumElts; ++i) {
4417 if (!DemandedElts[i])
4419 if (Constant *Elt = Cst->getAggregateElement(i)) {
4420 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4421 const APInt &Value = CInt->getValue();
4422 Tmp = std::min(Tmp, Value.getNumSignBits());
4425 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4426 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4427 Tmp = std::min(Tmp, Value.getNumSignBits());
4431 // Unknown type. Conservatively assume no bits match sign bit.
4442 // Allow the target to implement this method for its nodes.
4443 if (Opcode >= ISD::BUILTIN_OP_END ||
4444 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4445 Opcode == ISD::INTRINSIC_W_CHAIN ||
4446 Opcode == ISD::INTRINSIC_VOID) {
4448 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4450 FirstAnswer = std::max(FirstAnswer, NumBits);
4453 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4454 // use this information.
4455 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4456 return std::max(FirstAnswer, Known.countMinSignBits());
4459 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4460 unsigned Depth) const {
4461 unsigned SignBits = ComputeNumSignBits(Op, Depth);
4462 return Op.getScalarValueSizeInBits() - SignBits + 1;
4465 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4466 const APInt &DemandedElts,
4467 unsigned Depth) const {
4468 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4469 return Op.getScalarValueSizeInBits() - SignBits + 1;
4472 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4473 unsigned Depth) const {
4474 // Early out for FREEZE.
4475 if (Op.getOpcode() == ISD::FREEZE)
4478 // TODO: Assume we don't know anything for now.
4479 EVT VT = Op.getValueType();
4480 if (VT.isScalableVector())
4483 APInt DemandedElts = VT.isVector()
4484 ? APInt::getAllOnes(VT.getVectorNumElements())
4486 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4489 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4490 const APInt &DemandedElts,
4492 unsigned Depth) const {
4493 unsigned Opcode = Op.getOpcode();
4495 // Early out for FREEZE.
4496 if (Opcode == ISD::FREEZE)
4499 if (Depth >= MaxRecursionDepth)
4500 return false; // Limit search depth.
4502 if (isIntOrFPConstant(Op))
4509 case ISD::BUILD_VECTOR:
4510 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4511 // this shouldn't affect the result.
4512 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4513 if (!DemandedElts[i])
4515 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4521 // TODO: Search for noundef attributes from library functions.
4523 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4526 // Allow the target to implement this method for its nodes.
4527 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4528 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4529 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4530 Op, DemandedElts, *this, PoisonOnly, Depth);
4537 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4538 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4539 !isa<ConstantSDNode>(Op.getOperand(1)))
4542 if (Op.getOpcode() == ISD::OR &&
4543 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4549 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4550 // If we're told that NaNs won't happen, assume they won't.
4551 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4554 if (Depth >= MaxRecursionDepth)
4555 return false; // Limit search depth.
4557 // TODO: Handle vectors.
4558 // If the value is a constant, we can obviously see if it is a NaN or not.
4559 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4560 return !C->getValueAPF().isNaN() ||
4561 (SNaN && !C->getValueAPF().isSignaling());
4564 unsigned Opcode = Op.getOpcode();
4575 // TODO: Need isKnownNeverInfinity
4578 case ISD::FCANONICALIZE:
4585 case ISD::FROUNDEVEN:
4587 case ISD::FNEARBYINT: {
4590 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4594 case ISD::FCOPYSIGN: {
4595 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4598 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4599 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4600 case ISD::FP_EXTEND:
4601 case ISD::FP_ROUND: {
4604 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4606 case ISD::SINT_TO_FP:
4607 case ISD::UINT_TO_FP:
4613 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4614 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4615 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4617 case ISD::FSQRT: // Need is known positive
4625 // TODO: Refine on operand
4629 case ISD::FMAXNUM: {
4630 // Only one needs to be known not-nan, since it will be returned if the
4631 // other ends up being one.
4632 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4633 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4635 case ISD::FMINNUM_IEEE:
4636 case ISD::FMAXNUM_IEEE: {
4639 // This can return a NaN if either operand is an sNaN, or if both operands
4641 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4642 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4643 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4644 isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4647 case ISD::FMAXIMUM: {
4648 // TODO: Does this quiet or return the origina NaN as-is?
4649 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4650 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4652 case ISD::EXTRACT_VECTOR_ELT: {
4653 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4656 if (Opcode >= ISD::BUILTIN_OP_END ||
4657 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4658 Opcode == ISD::INTRINSIC_W_CHAIN ||
4659 Opcode == ISD::INTRINSIC_VOID) {
4660 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4667 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4668 assert(Op.getValueType().isFloatingPoint() &&
4669 "Floating point type expected");
4671 // If the value is a constant, we can obviously see if it is a zero or not.
4672 // TODO: Add BuildVector support.
4673 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4674 return !C->isZero();
4678 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4679 assert(!Op.getValueType().isFloatingPoint() &&
4680 "Floating point types unsupported - use isKnownNeverZeroFloat");
4682 // If the value is a constant, we can obviously see if it is a zero or not.
4683 if (ISD::matchUnaryPredicate(Op,
4684 [](ConstantSDNode *C) { return !C->isZero(); }))
4687 // TODO: Recognize more cases here.
4688 switch (Op.getOpcode()) {
4691 if (isKnownNeverZero(Op.getOperand(1)) ||
4692 isKnownNeverZero(Op.getOperand(0)))
4700 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4701 // Check the obvious case.
4702 if (A == B) return true;
4704 // For for negative and positive zero.
4705 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4706 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4707 if (CA->isZero() && CB->isZero()) return true;
4709 // Otherwise they may not be equal.
4713 // Only bits set in Mask must be negated, other bits may be arbitrary.
4714 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4715 if (isBitwiseNot(V, AllowUndefs))
4716 return V.getOperand(0);
4718 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4719 // bits in the non-extended part.
4720 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4721 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4723 SDValue ExtArg = V.getOperand(0);
4724 if (ExtArg.getScalarValueSizeInBits() >=
4725 MaskC->getAPIntValue().getActiveBits() &&
4726 isBitwiseNot(ExtArg, AllowUndefs) &&
4727 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4728 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4729 return ExtArg.getOperand(0).getOperand(0);
4733 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4734 // Match masked merge pattern (X & ~M) op (Y & M)
4735 // Including degenerate case (X & ~M) op M
4736 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4738 if (SDValue NotOperand =
4739 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4740 if (Other == NotOperand)
4742 if (Other->getOpcode() == ISD::AND)
4743 return NotOperand == Other->getOperand(0) ||
4744 NotOperand == Other->getOperand(1);
4748 if (A->getOpcode() == ISD::AND)
4749 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4750 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4754 // FIXME: unify with llvm::haveNoCommonBitsSet.
4755 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4756 assert(A.getValueType() == B.getValueType() &&
4757 "Values must have the same type");
4758 if (haveNoCommonBitsSetCommutative(A, B) ||
4759 haveNoCommonBitsSetCommutative(B, A))
4761 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4762 computeKnownBits(B));
4765 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4766 SelectionDAG &DAG) {
4767 if (cast<ConstantSDNode>(Step)->isZero())
4768 return DAG.getConstant(0, DL, VT);
4773 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4774 ArrayRef<SDValue> Ops,
4775 SelectionDAG &DAG) {
4776 int NumOps = Ops.size();
4777 assert(NumOps != 0 && "Can't build an empty vector!");
4778 assert(!VT.isScalableVector() &&
4779 "BUILD_VECTOR cannot be used with scalable types");
4780 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4781 "Incorrect element count in BUILD_VECTOR!");
4783 // BUILD_VECTOR of UNDEFs is UNDEF.
4784 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4785 return DAG.getUNDEF(VT);
4787 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4788 SDValue IdentitySrc;
4789 bool IsIdentity = true;
4790 for (int i = 0; i != NumOps; ++i) {
4791 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4792 Ops[i].getOperand(0).getValueType() != VT ||
4793 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4794 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4795 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4799 IdentitySrc = Ops[i].getOperand(0);
4807 /// Try to simplify vector concatenation to an input value, undef, or build
4809 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4810 ArrayRef<SDValue> Ops,
4811 SelectionDAG &DAG) {
4812 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4813 assert(llvm::all_of(Ops,
4815 return Ops[0].getValueType() == Op.getValueType();
4817 "Concatenation of vectors with inconsistent value types!");
4818 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4819 VT.getVectorElementCount() &&
4820 "Incorrect element count in vector concatenation!");
4822 if (Ops.size() == 1)
4825 // Concat of UNDEFs is UNDEF.
4826 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4827 return DAG.getUNDEF(VT);
4829 // Scan the operands and look for extract operations from a single source
4830 // that correspond to insertion at the same location via this concatenation:
4831 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4832 SDValue IdentitySrc;
4833 bool IsIdentity = true;
4834 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4835 SDValue Op = Ops[i];
4836 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4837 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4838 Op.getOperand(0).getValueType() != VT ||
4839 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4840 Op.getConstantOperandVal(1) != IdentityIndex) {
4844 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4845 "Unexpected identity source vector for concat of extracts");
4846 IdentitySrc = Op.getOperand(0);
4849 assert(IdentitySrc && "Failed to set source vector of extracts");
4853 // The code below this point is only designed to work for fixed width
4854 // vectors, so we bail out for now.
4855 if (VT.isScalableVector())
4858 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4859 // simplified to one big BUILD_VECTOR.
4860 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4861 EVT SVT = VT.getScalarType();
4862 SmallVector<SDValue, 16> Elts;
4863 for (SDValue Op : Ops) {
4864 EVT OpVT = Op.getValueType();
4866 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4867 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4868 Elts.append(Op->op_begin(), Op->op_end());
4873 // BUILD_VECTOR requires all inputs to be of the same type, find the
4874 // maximum type and extend them all.
4875 for (SDValue Op : Elts)
4876 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4878 if (SVT.bitsGT(VT.getScalarType())) {
4879 for (SDValue &Op : Elts) {
4881 Op = DAG.getUNDEF(SVT);
4883 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4884 ? DAG.getZExtOrTrunc(Op, DL, SVT)
4885 : DAG.getSExtOrTrunc(Op, DL, SVT);
4889 SDValue V = DAG.getBuildVector(VT, DL, Elts);
4890 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4894 /// Gets or creates the specified node.
4895 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4896 FoldingSetNodeID ID;
4897 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4899 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4900 return SDValue(E, 0);
4902 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4904 CSEMap.InsertNode(N, IP);
4907 SDValue V = SDValue(N, 0);
4908 NewSDValueDbgMsg(V, "Creating new node: ", this);
4912 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4916 Flags = Inserter->getFlags();
4917 return getNode(Opcode, DL, VT, Operand, Flags);
4920 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4921 SDValue Operand, const SDNodeFlags Flags) {
4922 assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4923 "Operand is DELETED_NODE!");
4924 // Constant fold unary operations with an integer constant operand. Even
4925 // opaque constant will be folded, because the folding of unary operations
4926 // doesn't create new constants with different values. Nevertheless, the
4927 // opaque flag is preserved during folding to prevent future folding with
4929 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4930 const APInt &Val = C->getAPIntValue();
4933 case ISD::SIGN_EXTEND:
4934 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4935 C->isTargetOpcode(), C->isOpaque());
4940 case ISD::ZERO_EXTEND:
4941 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4942 C->isTargetOpcode(), C->isOpaque());
4943 case ISD::ANY_EXTEND:
4944 // Some targets like RISCV prefer to sign extend some types.
4945 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4946 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4947 C->isTargetOpcode(), C->isOpaque());
4948 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4949 C->isTargetOpcode(), C->isOpaque());
4950 case ISD::UINT_TO_FP:
4951 case ISD::SINT_TO_FP: {
4952 APFloat apf(EVTToAPFloatSemantics(VT),
4953 APInt::getZero(VT.getSizeInBits()));
4954 (void)apf.convertFromAPInt(Val,
4955 Opcode==ISD::SINT_TO_FP,
4956 APFloat::rmNearestTiesToEven);
4957 return getConstantFP(apf, DL, VT);
4960 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4961 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4962 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4963 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4964 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4965 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4966 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4967 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4970 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4972 case ISD::BITREVERSE:
4973 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4976 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4979 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4982 case ISD::CTLZ_ZERO_UNDEF:
4983 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4986 case ISD::CTTZ_ZERO_UNDEF:
4987 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4989 case ISD::FP16_TO_FP:
4990 case ISD::BF16_TO_FP: {
4992 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
4993 : APFloat::BFloat(),
4994 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4996 // This can return overflow, underflow, or inexact; we don't care.
4997 // FIXME need to be more flexible about rounding mode.
4998 (void)FPV.convert(EVTToAPFloatSemantics(VT),
4999 APFloat::rmNearestTiesToEven, &Ignored);
5000 return getConstantFP(FPV, DL, VT);
5002 case ISD::STEP_VECTOR: {
5003 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5010 // Constant fold unary operations with a floating point constant operand.
5011 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5012 APFloat V = C->getValueAPF(); // make copy
5016 return getConstantFP(V, DL, VT);
5019 return getConstantFP(V, DL, VT);
5021 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5022 if (fs == APFloat::opOK || fs == APFloat::opInexact)
5023 return getConstantFP(V, DL, VT);
5027 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5028 if (fs == APFloat::opOK || fs == APFloat::opInexact)
5029 return getConstantFP(V, DL, VT);
5033 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5034 if (fs == APFloat::opOK || fs == APFloat::opInexact)
5035 return getConstantFP(V, DL, VT);
5038 case ISD::FP_EXTEND: {
5040 // This can return overflow, underflow, or inexact; we don't care.
5041 // FIXME need to be more flexible about rounding mode.
5042 (void)V.convert(EVTToAPFloatSemantics(VT),
5043 APFloat::rmNearestTiesToEven, &ignored);
5044 return getConstantFP(V, DL, VT);
5046 case ISD::FP_TO_SINT:
5047 case ISD::FP_TO_UINT: {
5049 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5050 // FIXME need to be more flexible about rounding mode.
5051 APFloat::opStatus s =
5052 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5053 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5055 return getConstant(IntVal, DL, VT);
5058 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5059 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5060 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5061 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5062 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5063 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5064 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5065 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5067 case ISD::FP_TO_FP16:
5068 case ISD::FP_TO_BF16: {
5070 // This can return overflow, underflow, or inexact; we don't care.
5071 // FIXME need to be more flexible about rounding mode.
5072 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5073 : APFloat::BFloat(),
5074 APFloat::rmNearestTiesToEven, &Ignored);
5075 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5080 // Constant fold unary operations with a vector integer or float operand.
5083 // FIXME: Entirely reasonable to perform folding of other unary
5084 // operations here as the need arises.
5091 case ISD::FP_EXTEND:
5092 case ISD::FP_TO_SINT:
5093 case ISD::FP_TO_UINT:
5095 case ISD::ANY_EXTEND:
5096 case ISD::ZERO_EXTEND:
5097 case ISD::SIGN_EXTEND:
5098 case ISD::UINT_TO_FP:
5099 case ISD::SINT_TO_FP:
5101 case ISD::BITREVERSE:
5104 case ISD::CTLZ_ZERO_UNDEF:
5106 case ISD::CTTZ_ZERO_UNDEF:
5108 SDValue Ops = {Operand};
5109 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5114 unsigned OpOpcode = Operand.getNode()->getOpcode();
5116 case ISD::STEP_VECTOR:
5117 assert(VT.isScalableVector() &&
5118 "STEP_VECTOR can only be used with scalable types");
5119 assert(OpOpcode == ISD::TargetConstant &&
5120 VT.getVectorElementType() == Operand.getValueType() &&
5121 "Unexpected step operand");
5124 assert(VT == Operand.getValueType() && "Unexpected VT!");
5125 if (isGuaranteedNotToBeUndefOrPoison(Operand))
5128 case ISD::TokenFactor:
5129 case ISD::MERGE_VALUES:
5130 case ISD::CONCAT_VECTORS:
5131 return Operand; // Factor, merge or concat of one node? No need.
5132 case ISD::BUILD_VECTOR: {
5133 // Attempt to simplify BUILD_VECTOR.
5134 SDValue Ops[] = {Operand};
5135 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5139 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5140 case ISD::FP_EXTEND:
5141 assert(VT.isFloatingPoint() &&
5142 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5143 if (Operand.getValueType() == VT) return Operand; // noop conversion.
5144 assert((!VT.isVector() ||
5145 VT.getVectorElementCount() ==
5146 Operand.getValueType().getVectorElementCount()) &&
5147 "Vector element count mismatch!");
5148 assert(Operand.getValueType().bitsLT(VT) &&
5149 "Invalid fpext node, dst < src!");
5150 if (Operand.isUndef())
5151 return getUNDEF(VT);
5153 case ISD::FP_TO_SINT:
5154 case ISD::FP_TO_UINT:
5155 if (Operand.isUndef())
5156 return getUNDEF(VT);
5158 case ISD::SINT_TO_FP:
5159 case ISD::UINT_TO_FP:
5160 // [us]itofp(undef) = 0, because the result value is bounded.
5161 if (Operand.isUndef())
5162 return getConstantFP(0.0, DL, VT);
5164 case ISD::SIGN_EXTEND:
5165 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5166 "Invalid SIGN_EXTEND!");
5167 assert(VT.isVector() == Operand.getValueType().isVector() &&
5168 "SIGN_EXTEND result type type should be vector iff the operand "
5170 if (Operand.getValueType() == VT) return Operand; // noop extension
5171 assert((!VT.isVector() ||
5172 VT.getVectorElementCount() ==
5173 Operand.getValueType().getVectorElementCount()) &&
5174 "Vector element count mismatch!");
5175 assert(Operand.getValueType().bitsLT(VT) &&
5176 "Invalid sext node, dst < src!");
5177 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5178 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5179 if (OpOpcode == ISD::UNDEF)
5180 // sext(undef) = 0, because the top bits will all be the same.
5181 return getConstant(0, DL, VT);
5183 case ISD::ZERO_EXTEND:
5184 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5185 "Invalid ZERO_EXTEND!");
5186 assert(VT.isVector() == Operand.getValueType().isVector() &&
5187 "ZERO_EXTEND result type type should be vector iff the operand "
5189 if (Operand.getValueType() == VT) return Operand; // noop extension
5190 assert((!VT.isVector() ||
5191 VT.getVectorElementCount() ==
5192 Operand.getValueType().getVectorElementCount()) &&
5193 "Vector element count mismatch!");
5194 assert(Operand.getValueType().bitsLT(VT) &&
5195 "Invalid zext node, dst < src!");
5196 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
5197 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5198 if (OpOpcode == ISD::UNDEF)
5199 // zext(undef) = 0, because the top bits will be zero.
5200 return getConstant(0, DL, VT);
5202 case ISD::ANY_EXTEND:
5203 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5204 "Invalid ANY_EXTEND!");
5205 assert(VT.isVector() == Operand.getValueType().isVector() &&
5206 "ANY_EXTEND result type type should be vector iff the operand "
5208 if (Operand.getValueType() == VT) return Operand; // noop extension
5209 assert((!VT.isVector() ||
5210 VT.getVectorElementCount() ==
5211 Operand.getValueType().getVectorElementCount()) &&
5212 "Vector element count mismatch!");
5213 assert(Operand.getValueType().bitsLT(VT) &&
5214 "Invalid anyext node, dst < src!");
5216 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5217 OpOpcode == ISD::ANY_EXTEND)
5218 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
5219 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5220 if (OpOpcode == ISD::UNDEF)
5221 return getUNDEF(VT);
5223 // (ext (trunc x)) -> x
5224 if (OpOpcode == ISD::TRUNCATE) {
5225 SDValue OpOp = Operand.getOperand(0);
5226 if (OpOp.getValueType() == VT) {
5227 transferDbgValues(Operand, OpOp);
5233 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5234 "Invalid TRUNCATE!");
5235 assert(VT.isVector() == Operand.getValueType().isVector() &&
5236 "TRUNCATE result type type should be vector iff the operand "
5238 if (Operand.getValueType() == VT) return Operand; // noop truncate
5239 assert((!VT.isVector() ||
5240 VT.getVectorElementCount() ==
5241 Operand.getValueType().getVectorElementCount()) &&
5242 "Vector element count mismatch!");
5243 assert(Operand.getValueType().bitsGT(VT) &&
5244 "Invalid truncate node, src < dst!");
5245 if (OpOpcode == ISD::TRUNCATE)
5246 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5247 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5248 OpOpcode == ISD::ANY_EXTEND) {
5249 // If the source is smaller than the dest, we still need an extend.
5250 if (Operand.getOperand(0).getValueType().getScalarType()
5251 .bitsLT(VT.getScalarType()))
5252 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5253 if (Operand.getOperand(0).getValueType().bitsGT(VT))
5254 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5255 return Operand.getOperand(0);
5257 if (OpOpcode == ISD::UNDEF)
5258 return getUNDEF(VT);
5259 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5260 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5262 case ISD::ANY_EXTEND_VECTOR_INREG:
5263 case ISD::ZERO_EXTEND_VECTOR_INREG:
5264 case ISD::SIGN_EXTEND_VECTOR_INREG:
5265 assert(VT.isVector() && "This DAG node is restricted to vector types.");
5266 assert(Operand.getValueType().bitsLE(VT) &&
5267 "The input must be the same size or smaller than the result.");
5268 assert(VT.getVectorMinNumElements() <
5269 Operand.getValueType().getVectorMinNumElements() &&
5270 "The destination vector type must have fewer lanes than the input.");
5273 assert(VT.isInteger() && VT == Operand.getValueType() &&
5275 if (OpOpcode == ISD::UNDEF)
5276 return getConstant(0, DL, VT);
5279 assert(VT.isInteger() && VT == Operand.getValueType() &&
5281 assert((VT.getScalarSizeInBits() % 16 == 0) &&
5282 "BSWAP types must be a multiple of 16 bits!");
5283 if (OpOpcode == ISD::UNDEF)
5284 return getUNDEF(VT);
5285 // bswap(bswap(X)) -> X.
5286 if (OpOpcode == ISD::BSWAP)
5287 return Operand.getOperand(0);
5289 case ISD::BITREVERSE:
5290 assert(VT.isInteger() && VT == Operand.getValueType() &&
5291 "Invalid BITREVERSE!");
5292 if (OpOpcode == ISD::UNDEF)
5293 return getUNDEF(VT);
5296 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5297 "Cannot BITCAST between types of different sizes!");
5298 if (VT == Operand.getValueType()) return Operand; // noop conversion.
5299 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
5300 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5301 if (OpOpcode == ISD::UNDEF)
5302 return getUNDEF(VT);
5304 case ISD::SCALAR_TO_VECTOR:
5305 assert(VT.isVector() && !Operand.getValueType().isVector() &&
5306 (VT.getVectorElementType() == Operand.getValueType() ||
5307 (VT.getVectorElementType().isInteger() &&
5308 Operand.getValueType().isInteger() &&
5309 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5310 "Illegal SCALAR_TO_VECTOR node!");
5311 if (OpOpcode == ISD::UNDEF)
5312 return getUNDEF(VT);
5313 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5314 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5315 isa<ConstantSDNode>(Operand.getOperand(1)) &&
5316 Operand.getConstantOperandVal(1) == 0 &&
5317 Operand.getOperand(0).getValueType() == VT)
5318 return Operand.getOperand(0);
5321 // Negation of an unknown bag of bits is still completely undefined.
5322 if (OpOpcode == ISD::UNDEF)
5323 return getUNDEF(VT);
5325 if (OpOpcode == ISD::FNEG) // --X -> X
5326 return Operand.getOperand(0);
5329 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
5330 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5333 assert(VT == Operand.getValueType() && "Unexpected VT!");
5336 if (Operand.getValueType().getScalarType() == MVT::i1)
5341 if (Operand.getValueType().getScalarType() == MVT::i1)
5342 return getNOT(DL, Operand, Operand.getValueType());
5344 case ISD::VECREDUCE_ADD:
5345 if (Operand.getValueType().getScalarType() == MVT::i1)
5346 return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5348 case ISD::VECREDUCE_SMIN:
5349 case ISD::VECREDUCE_UMAX:
5350 if (Operand.getValueType().getScalarType() == MVT::i1)
5351 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5353 case ISD::VECREDUCE_SMAX:
5354 case ISD::VECREDUCE_UMIN:
5355 if (Operand.getValueType().getScalarType() == MVT::i1)
5356 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5361 SDVTList VTs = getVTList(VT);
5362 SDValue Ops[] = {Operand};
5363 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5364 FoldingSetNodeID ID;
5365 AddNodeIDNode(ID, Opcode, VTs, Ops);
5367 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5368 E->intersectFlagsWith(Flags);
5369 return SDValue(E, 0);
5372 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5374 createOperands(N, Ops);
5375 CSEMap.InsertNode(N, IP);
5377 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5378 createOperands(N, Ops);
5382 SDValue V = SDValue(N, 0);
5383 NewSDValueDbgMsg(V, "Creating new node: ", this);
5387 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5390 case ISD::ADD: return C1 + C2;
5391 case ISD::SUB: return C1 - C2;
5392 case ISD::MUL: return C1 * C2;
5393 case ISD::AND: return C1 & C2;
5394 case ISD::OR: return C1 | C2;
5395 case ISD::XOR: return C1 ^ C2;
5396 case ISD::SHL: return C1 << C2;
5397 case ISD::SRL: return C1.lshr(C2);
5398 case ISD::SRA: return C1.ashr(C2);
5399 case ISD::ROTL: return C1.rotl(C2);
5400 case ISD::ROTR: return C1.rotr(C2);
5401 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5402 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5403 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5404 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5405 case ISD::SADDSAT: return C1.sadd_sat(C2);
5406 case ISD::UADDSAT: return C1.uadd_sat(C2);
5407 case ISD::SSUBSAT: return C1.ssub_sat(C2);
5408 case ISD::USUBSAT: return C1.usub_sat(C2);
5409 case ISD::SSHLSAT: return C1.sshl_sat(C2);
5410 case ISD::USHLSAT: return C1.ushl_sat(C2);
5412 if (!C2.getBoolValue())
5416 if (!C2.getBoolValue())
5420 if (!C2.getBoolValue())
5424 if (!C2.getBoolValue())
5428 unsigned FullWidth = C1.getBitWidth() * 2;
5429 APInt C1Ext = C1.sext(FullWidth);
5430 APInt C2Ext = C2.sext(FullWidth);
5431 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5434 unsigned FullWidth = C1.getBitWidth() * 2;
5435 APInt C1Ext = C1.zext(FullWidth);
5436 APInt C2Ext = C2.zext(FullWidth);
5437 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5439 case ISD::AVGFLOORS: {
5440 unsigned FullWidth = C1.getBitWidth() + 1;
5441 APInt C1Ext = C1.sext(FullWidth);
5442 APInt C2Ext = C2.sext(FullWidth);
5443 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5445 case ISD::AVGFLOORU: {
5446 unsigned FullWidth = C1.getBitWidth() + 1;
5447 APInt C1Ext = C1.zext(FullWidth);
5448 APInt C2Ext = C2.zext(FullWidth);
5449 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5451 case ISD::AVGCEILS: {
5452 unsigned FullWidth = C1.getBitWidth() + 1;
5453 APInt C1Ext = C1.sext(FullWidth);
5454 APInt C2Ext = C2.sext(FullWidth);
5455 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5457 case ISD::AVGCEILU: {
5458 unsigned FullWidth = C1.getBitWidth() + 1;
5459 APInt C1Ext = C1.zext(FullWidth);
5460 APInt C2Ext = C2.zext(FullWidth);
5461 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5467 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5468 const GlobalAddressSDNode *GA,
5470 if (GA->getOpcode() != ISD::GlobalAddress)
5472 if (!TLI->isOffsetFoldingLegal(GA))
5474 auto *C2 = dyn_cast<ConstantSDNode>(N2);
5477 int64_t Offset = C2->getSExtValue();
5479 case ISD::ADD: break;
5480 case ISD::SUB: Offset = -uint64_t(Offset); break;
5481 default: return SDValue();
5483 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5484 GA->getOffset() + uint64_t(Offset));
5487 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5493 // If a divisor is zero/undef or any element of a divisor vector is
5494 // zero/undef, the whole op is undef.
5495 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5496 SDValue Divisor = Ops[1];
5497 if (Divisor.isUndef() || isNullConstant(Divisor))
5500 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5501 llvm::any_of(Divisor->op_values(),
5502 [](SDValue V) { return V.isUndef() ||
5503 isNullConstant(V); });
5504 // TODO: Handle signed overflow.
5506 // TODO: Handle oversized shifts.
5512 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5513 EVT VT, ArrayRef<SDValue> Ops) {
5514 // If the opcode is a target-specific ISD node, there's nothing we can
5515 // do here and the operand rules may not line up with the below, so
5517 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5518 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5519 // foldCONCAT_VECTORS in getNode before this is called.
5520 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5523 unsigned NumOps = Ops.size();
5527 if (isUndef(Opcode, Ops))
5528 return getUNDEF(VT);
5530 // Handle binops special cases.
5532 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5535 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5536 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5537 if (C1->isOpaque() || C2->isOpaque())
5540 Optional<APInt> FoldAttempt =
5541 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5545 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5546 assert((!Folded || !VT.isVector()) &&
5547 "Can't fold vectors ops with scalar operands");
5552 // fold (add Sym, c) -> Sym+c
5553 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5554 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5555 if (TLI->isCommutativeBinOp(Opcode))
5556 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5557 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5560 // This is for vector folding only from here on.
5564 ElementCount NumElts = VT.getVectorElementCount();
5566 // See if we can fold through bitcasted integer ops.
5567 // TODO: Can we handle undef elements?
5568 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5569 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5570 Ops[0].getOpcode() == ISD::BITCAST &&
5571 Ops[1].getOpcode() == ISD::BITCAST) {
5572 SDValue N1 = peekThroughBitcasts(Ops[0]);
5573 SDValue N2 = peekThroughBitcasts(Ops[1]);
5574 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5575 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5576 EVT BVVT = N1.getValueType();
5577 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5578 bool IsLE = getDataLayout().isLittleEndian();
5579 unsigned EltBits = VT.getScalarSizeInBits();
5580 SmallVector<APInt> RawBits1, RawBits2;
5581 BitVector UndefElts1, UndefElts2;
5582 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5583 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5584 UndefElts1.none() && UndefElts2.none()) {
5585 SmallVector<APInt> RawBits;
5586 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5587 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5590 RawBits.push_back(*Fold);
5592 if (RawBits.size() == NumElts.getFixedValue()) {
5593 // We have constant folded, but we need to cast this again back to
5594 // the original (possibly legalized) type.
5595 SmallVector<APInt> DstBits;
5596 BitVector DstUndefs;
5597 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5598 DstBits, RawBits, DstUndefs,
5599 BitVector(RawBits.size(), false));
5600 EVT BVEltVT = BV1->getOperand(0).getValueType();
5601 unsigned BVEltBits = BVEltVT.getSizeInBits();
5602 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5603 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5606 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5608 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5614 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5615 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5616 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5617 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5619 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5620 APInt NewStep = Opcode == ISD::MUL
5621 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5622 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5623 return getStepVector(DL, VT, NewStep);
5627 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5628 return !Op.getValueType().isVector() ||
5629 Op.getValueType().getVectorElementCount() == NumElts;
5632 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5633 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5634 Op.getOpcode() == ISD::BUILD_VECTOR ||
5635 Op.getOpcode() == ISD::SPLAT_VECTOR;
5638 // All operands must be vector types with the same number of elements as
5639 // the result type and must be either UNDEF or a build/splat vector
5640 // or UNDEF scalars.
5641 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5642 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5645 // If we are comparing vectors, then the result needs to be a i1 boolean that
5646 // is then extended back to the legal result type depending on how booleans
5648 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5649 ISD::NodeType ExtendCode =
5650 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5651 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5654 // Find legal integer scalar type for constant promotion and
5655 // ensure that its scalar size is at least as large as source.
5656 EVT LegalSVT = VT.getScalarType();
5657 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5658 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5659 if (LegalSVT.bitsLT(VT.getScalarType()))
5663 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5664 // only have one operand to check. For fixed-length vector types we may have
5665 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5666 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5668 // Constant fold each scalar lane separately.
5669 SmallVector<SDValue, 4> ScalarResults;
5670 for (unsigned I = 0; I != NumVectorElts; I++) {
5671 SmallVector<SDValue, 4> ScalarOps;
5672 for (SDValue Op : Ops) {
5673 EVT InSVT = Op.getValueType().getScalarType();
5674 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5675 Op.getOpcode() != ISD::SPLAT_VECTOR) {
5677 ScalarOps.push_back(getUNDEF(InSVT));
5679 ScalarOps.push_back(Op);
5684 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5685 EVT ScalarVT = ScalarOp.getValueType();
5687 // Build vector (integer) scalar operands may need implicit
5688 // truncation - do this before constant folding.
5689 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5690 // Don't create illegally-typed nodes unless they're constants or undef
5691 // - if we fail to constant fold we can't guarantee the (dead) nodes
5692 // we're creating will be cleaned up before being visited for
5694 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5695 !isa<ConstantSDNode>(ScalarOp) &&
5696 TLI->getTypeAction(*getContext(), InSVT) !=
5697 TargetLowering::TypeLegal)
5699 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5702 ScalarOps.push_back(ScalarOp);
5705 // Constant fold the scalar operands.
5706 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5708 // Legalize the (integer) scalar constant if necessary.
5709 if (LegalSVT != SVT)
5710 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5712 // Scalar folding only succeeded if the result is a constant or UNDEF.
5713 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5714 ScalarResult.getOpcode() != ISD::ConstantFP)
5716 ScalarResults.push_back(ScalarResult);
5719 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5720 : getBuildVector(VT, DL, ScalarResults);
5721 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5725 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5726 EVT VT, SDValue N1, SDValue N2) {
5727 // TODO: We don't do any constant folding for strict FP opcodes here, but we
5728 // should. That will require dealing with a potentially non-default
5729 // rounding mode, checking the "opStatus" return value from the APFloat
5730 // math calculations, and possibly other variations.
5731 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5732 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5733 if (N1CFP && N2CFP) {
5734 APFloat C1 = N1CFP->getValueAPF(); // make copy
5735 const APFloat &C2 = N2CFP->getValueAPF();
5738 C1.add(C2, APFloat::rmNearestTiesToEven);
5739 return getConstantFP(C1, DL, VT);
5741 C1.subtract(C2, APFloat::rmNearestTiesToEven);
5742 return getConstantFP(C1, DL, VT);
5744 C1.multiply(C2, APFloat::rmNearestTiesToEven);
5745 return getConstantFP(C1, DL, VT);
5747 C1.divide(C2, APFloat::rmNearestTiesToEven);
5748 return getConstantFP(C1, DL, VT);
5751 return getConstantFP(C1, DL, VT);
5752 case ISD::FCOPYSIGN:
5754 return getConstantFP(C1, DL, VT);
5756 return getConstantFP(minnum(C1, C2), DL, VT);
5758 return getConstantFP(maxnum(C1, C2), DL, VT);
5760 return getConstantFP(minimum(C1, C2), DL, VT);
5762 return getConstantFP(maximum(C1, C2), DL, VT);
5766 if (N1CFP && Opcode == ISD::FP_ROUND) {
5767 APFloat C1 = N1CFP->getValueAPF(); // make copy
5769 // This can return overflow, underflow, or inexact; we don't care.
5770 // FIXME need to be more flexible about rounding mode.
5771 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5773 return getConstantFP(C1, DL, VT);
5778 // -0.0 - undef --> undef (consistent with "fneg undef")
5779 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5780 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5781 return getUNDEF(VT);
5788 // If both operands are undef, the result is undef. If 1 operand is undef,
5789 // the result is NaN. This should match the behavior of the IR optimizer.
5790 if (N1.isUndef() && N2.isUndef())
5791 return getUNDEF(VT);
5792 if (N1.isUndef() || N2.isUndef())
5793 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5798 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5799 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5801 // There's no need to assert on a byte-aligned pointer. All pointers are at
5802 // least byte aligned.
5806 FoldingSetNodeID ID;
5807 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5808 ID.AddInteger(A.value());
5811 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5812 return SDValue(E, 0);
5814 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5815 Val.getValueType(), A);
5816 createOperands(N, {Val});
5818 CSEMap.InsertNode(N, IP);
5822 NewSDValueDbgMsg(V, "Creating new node: ", this);
5826 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5827 SDValue N1, SDValue N2) {
5830 Flags = Inserter->getFlags();
5831 return getNode(Opcode, DL, VT, N1, N2, Flags);
5834 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5835 SDValue &N2) const {
5836 if (!TLI->isCommutativeBinOp(Opcode))
5840 // binop(const, nonconst) -> binop(nonconst, const)
5841 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5842 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5843 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5844 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5845 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5849 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5850 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5851 N2.getOpcode() == ISD::STEP_VECTOR)
5855 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5856 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5857 assert(N1.getOpcode() != ISD::DELETED_NODE &&
5858 N2.getOpcode() != ISD::DELETED_NODE &&
5859 "Operand is DELETED_NODE!");
5861 canonicalizeCommutativeBinop(Opcode, N1, N2);
5863 auto *N1C = dyn_cast<ConstantSDNode>(N1);
5864 auto *N2C = dyn_cast<ConstantSDNode>(N2);
5866 // Don't allow undefs in vector splats - we might be returning N2 when folding
5868 ConstantSDNode *N2CV =
5869 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5873 case ISD::TokenFactor:
5874 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5875 N2.getValueType() == MVT::Other && "Invalid token factor!");
5876 // Fold trivial token factors.
5877 if (N1.getOpcode() == ISD::EntryToken) return N2;
5878 if (N2.getOpcode() == ISD::EntryToken) return N1;
5879 if (N1 == N2) return N1;
5881 case ISD::BUILD_VECTOR: {
5882 // Attempt to simplify BUILD_VECTOR.
5883 SDValue Ops[] = {N1, N2};
5884 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5888 case ISD::CONCAT_VECTORS: {
5889 SDValue Ops[] = {N1, N2};
5890 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5895 assert(VT.isInteger() && "This operator does not apply to FP types!");
5896 assert(N1.getValueType() == N2.getValueType() &&
5897 N1.getValueType() == VT && "Binary operator types must match!");
5898 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
5899 // worth handling here.
5900 if (N2CV && N2CV->isZero())
5902 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5909 assert(VT.isInteger() && "This operator does not apply to FP types!");
5910 assert(N1.getValueType() == N2.getValueType() &&
5911 N1.getValueType() == VT && "Binary operator types must match!");
5912 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
5913 // it's worth handling here.
5914 if (N2CV && N2CV->isZero())
5916 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5917 VT.getVectorElementType() == MVT::i1)
5918 return getNode(ISD::XOR, DL, VT, N1, N2);
5921 assert(VT.isInteger() && "This operator does not apply to FP types!");
5922 assert(N1.getValueType() == N2.getValueType() &&
5923 N1.getValueType() == VT && "Binary operator types must match!");
5924 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5925 return getNode(ISD::AND, DL, VT, N1, N2);
5926 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5927 const APInt &MulImm = N1->getConstantOperandAPInt(0);
5928 const APInt &N2CImm = N2C->getAPIntValue();
5929 return getVScale(DL, VT, MulImm * N2CImm);
5942 assert(VT.isInteger() && "This operator does not apply to FP types!");
5943 assert(N1.getValueType() == N2.getValueType() &&
5944 N1.getValueType() == VT && "Binary operator types must match!");
5945 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5946 // fold (add_sat x, y) -> (or x, y) for bool types.
5947 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5948 return getNode(ISD::OR, DL, VT, N1, N2);
5949 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5950 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5951 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5956 assert(VT.isInteger() && "This operator does not apply to FP types!");
5957 assert(N1.getValueType() == N2.getValueType() &&
5958 N1.getValueType() == VT && "Binary operator types must match!");
5959 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5960 return getNode(ISD::OR, DL, VT, N1, N2);
5964 assert(VT.isInteger() && "This operator does not apply to FP types!");
5965 assert(N1.getValueType() == N2.getValueType() &&
5966 N1.getValueType() == VT && "Binary operator types must match!");
5967 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5968 return getNode(ISD::AND, DL, VT, N1, N2);
5975 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5976 assert(N1.getValueType() == N2.getValueType() &&
5977 N1.getValueType() == VT && "Binary operator types must match!");
5978 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5981 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
5982 assert(N1.getValueType() == VT &&
5983 N1.getValueType().isFloatingPoint() &&
5984 N2.getValueType().isFloatingPoint() &&
5985 "Invalid FCOPYSIGN!");
5988 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5989 const APInt &MulImm = N1->getConstantOperandAPInt(0);
5990 const APInt &ShiftImm = N2C->getAPIntValue();
5991 return getVScale(DL, VT, MulImm << ShiftImm);
5996 if (SDValue V = simplifyShift(N1, N2))
6001 assert(VT == N1.getValueType() &&
6002 "Shift operators return type must be the same as their first arg");
6003 assert(VT.isInteger() && N2.getValueType().isInteger() &&
6004 "Shifts only work on integers");
6005 assert((!VT.isVector() || VT == N2.getValueType()) &&
6006 "Vector shift amounts must be in the same as their first arg");
6007 // Verify that the shift amount VT is big enough to hold valid shift
6008 // amounts. This catches things like trying to shift an i1024 value by an
6009 // i8, which is easy to fall into in generic code that uses
6010 // TLI.getShiftAmount().
6011 assert(N2.getValueType().getScalarSizeInBits() >=
6012 Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6013 "Invalid use of small shift amount with oversized value!");
6015 // Always fold shifts of i1 values so the code generator doesn't need to
6016 // handle them. Since we know the size of the shift has to be less than the
6017 // size of the value, the shift/rotate count is guaranteed to be zero.
6020 if (N2CV && N2CV->isZero())
6024 assert(VT.isFloatingPoint() &&
6025 N1.getValueType().isFloatingPoint() &&
6026 VT.bitsLE(N1.getValueType()) &&
6027 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6028 "Invalid FP_ROUND!");
6029 if (N1.getValueType() == VT) return N1; // noop conversion.
6031 case ISD::AssertSext:
6032 case ISD::AssertZext: {
6033 EVT EVT = cast<VTSDNode>(N2)->getVT();
6034 assert(VT == N1.getValueType() && "Not an inreg extend!");
6035 assert(VT.isInteger() && EVT.isInteger() &&
6036 "Cannot *_EXTEND_INREG FP types");
6037 assert(!EVT.isVector() &&
6038 "AssertSExt/AssertZExt type should be the vector element type "
6039 "rather than the vector type!");
6040 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6041 if (VT.getScalarType() == EVT) return N1; // noop assertion.
6044 case ISD::SIGN_EXTEND_INREG: {
6045 EVT EVT = cast<VTSDNode>(N2)->getVT();
6046 assert(VT == N1.getValueType() && "Not an inreg extend!");
6047 assert(VT.isInteger() && EVT.isInteger() &&
6048 "Cannot *_EXTEND_INREG FP types");
6049 assert(EVT.isVector() == VT.isVector() &&
6050 "SIGN_EXTEND_INREG type should be vector iff the operand "
6052 assert((!EVT.isVector() ||
6053 EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6054 "Vector element counts must match in SIGN_EXTEND_INREG");
6055 assert(EVT.bitsLE(VT) && "Not extending!");
6056 if (EVT == VT) return N1; // Not actually extending
6058 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6059 unsigned FromBits = EVT.getScalarSizeInBits();
6060 Val <<= Val.getBitWidth() - FromBits;
6061 Val.ashrInPlace(Val.getBitWidth() - FromBits);
6062 return getConstant(Val, DL, ConstantVT);
6066 const APInt &Val = N1C->getAPIntValue();
6067 return SignExtendInReg(Val, VT);
6070 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6071 SmallVector<SDValue, 8> Ops;
6072 llvm::EVT OpVT = N1.getOperand(0).getValueType();
6073 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6074 SDValue Op = N1.getOperand(i);
6076 Ops.push_back(getUNDEF(OpVT));
6079 ConstantSDNode *C = cast<ConstantSDNode>(Op);
6080 APInt Val = C->getAPIntValue();
6081 Ops.push_back(SignExtendInReg(Val, OpVT));
6083 return getBuildVector(VT, DL, Ops);
6087 case ISD::FP_TO_SINT_SAT:
6088 case ISD::FP_TO_UINT_SAT: {
6089 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6090 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6091 assert(N1.getValueType().isVector() == VT.isVector() &&
6092 "FP_TO_*INT_SAT type should be vector iff the operand type is "
6094 assert((!VT.isVector() || VT.getVectorElementCount() ==
6095 N1.getValueType().getVectorElementCount()) &&
6096 "Vector element counts must match in FP_TO_*INT_SAT");
6097 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6098 "Type to saturate to must be a scalar.");
6099 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6103 case ISD::EXTRACT_VECTOR_ELT:
6104 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6105 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6106 element type of the vector.");
6108 // Extract from an undefined value or using an undefined index is undefined.
6109 if (N1.isUndef() || N2.isUndef())
6110 return getUNDEF(VT);
6112 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6113 // vectors. For scalable vectors we will provide appropriate support for
6114 // dealing with arbitrary indices.
6115 if (N2C && N1.getValueType().isFixedLengthVector() &&
6116 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6117 return getUNDEF(VT);
6119 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6120 // expanding copies of large vectors from registers. This only works for
6121 // fixed length vectors, since we need to know the exact number of
6123 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6124 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6126 N1.getOperand(0).getValueType().getVectorNumElements();
6127 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6128 N1.getOperand(N2C->getZExtValue() / Factor),
6129 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6132 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6133 // lowering is expanding large vector constants.
6134 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6135 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6136 assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6137 N1.getValueType().isFixedLengthVector()) &&
6138 "BUILD_VECTOR used for scalable vectors");
6140 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6141 SDValue Elt = N1.getOperand(Index);
6143 if (VT != Elt.getValueType())
6144 // If the vector element type is not legal, the BUILD_VECTOR operands
6145 // are promoted and implicitly truncated, and the result implicitly
6146 // extended. Make that explicit here.
6147 Elt = getAnyExtOrTrunc(Elt, DL, VT);
6152 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6153 // operations are lowered to scalars.
6154 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6155 // If the indices are the same, return the inserted element else
6156 // if the indices are known different, extract the element from
6157 // the original vector.
6158 SDValue N1Op2 = N1.getOperand(2);
6159 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6161 if (N1Op2C && N2C) {
6162 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6163 if (VT == N1.getOperand(1).getValueType())
6164 return N1.getOperand(1);
6165 if (VT.isFloatingPoint()) {
6166 assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6167 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6169 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6171 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6175 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6176 // when vector types are scalarized and v1iX is legal.
6177 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6178 // Here we are completely ignoring the extract element index (N2),
6179 // which is fine for fixed width vectors, since any index other than 0
6180 // is undefined anyway. However, this cannot be ignored for scalable
6181 // vectors - in theory we could support this, but we don't want to do this
6182 // without a profitability check.
6183 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6184 N1.getValueType().isFixedLengthVector() &&
6185 N1.getValueType().getVectorNumElements() == 1) {
6186 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6190 case ISD::EXTRACT_ELEMENT:
6191 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6192 assert(!N1.getValueType().isVector() && !VT.isVector() &&
6193 (N1.getValueType().isInteger() == VT.isInteger()) &&
6194 N1.getValueType() != VT &&
6195 "Wrong types for EXTRACT_ELEMENT!");
6197 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6198 // 64-bit integers into 32-bit parts. Instead of building the extract of
6199 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6200 if (N1.getOpcode() == ISD::BUILD_PAIR)
6201 return N1.getOperand(N2C->getZExtValue());
6203 // EXTRACT_ELEMENT of a constant int is also very common.
6205 unsigned ElementSize = VT.getSizeInBits();
6206 unsigned Shift = ElementSize * N2C->getZExtValue();
6207 const APInt &Val = N1C->getAPIntValue();
6208 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6211 case ISD::EXTRACT_SUBVECTOR: {
6212 EVT N1VT = N1.getValueType();
6213 assert(VT.isVector() && N1VT.isVector() &&
6214 "Extract subvector VTs must be vectors!");
6215 assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6216 "Extract subvector VTs must have the same element type!");
6217 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6218 "Cannot extract a scalable vector from a fixed length vector!");
6219 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6220 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6221 "Extract subvector must be from larger vector to smaller vector!");
6222 assert(N2C && "Extract subvector index must be a constant");
6223 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6224 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6225 N1VT.getVectorMinNumElements()) &&
6226 "Extract subvector overflow!");
6227 assert(N2C->getAPIntValue().getBitWidth() ==
6228 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6229 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6231 // Trivial extraction.
6235 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6237 return getUNDEF(VT);
6239 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6240 // the concat have the same type as the extract.
6241 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6242 VT == N1.getOperand(0).getValueType()) {
6243 unsigned Factor = VT.getVectorMinNumElements();
6244 return N1.getOperand(N2C->getZExtValue() / Factor);
6247 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6248 // during shuffle legalization.
6249 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6250 VT == N1.getOperand(1).getValueType())
6251 return N1.getOperand(1);
6256 // Perform trivial constant folding.
6257 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6260 // Canonicalize an UNDEF to the RHS, even over a constant.
6262 if (TLI->isCommutativeBinOp(Opcode)) {
6267 return getUNDEF(VT); // fold op(undef, arg2) -> undef
6268 case ISD::SIGN_EXTEND_INREG:
6275 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
6280 // Fold a bunch of operators when the RHS is undef.
6285 // Handle undef ^ undef -> 0 special case. This is a common
6287 return getConstant(0, DL, VT);
6295 return getUNDEF(VT); // fold op(arg1, undef) -> undef
6300 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
6304 return getAllOnesConstant(DL, VT);
6308 // Memoize this node if possible.
6310 SDVTList VTs = getVTList(VT);
6311 SDValue Ops[] = {N1, N2};
6312 if (VT != MVT::Glue) {
6313 FoldingSetNodeID ID;
6314 AddNodeIDNode(ID, Opcode, VTs, Ops);
6316 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6317 E->intersectFlagsWith(Flags);
6318 return SDValue(E, 0);
6321 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6323 createOperands(N, Ops);
6324 CSEMap.InsertNode(N, IP);
6326 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6327 createOperands(N, Ops);
6331 SDValue V = SDValue(N, 0);
6332 NewSDValueDbgMsg(V, "Creating new node: ", this);
6336 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6337 SDValue N1, SDValue N2, SDValue N3) {
6340 Flags = Inserter->getFlags();
6341 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6344 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6345 SDValue N1, SDValue N2, SDValue N3,
6346 const SDNodeFlags Flags) {
6347 assert(N1.getOpcode() != ISD::DELETED_NODE &&
6348 N2.getOpcode() != ISD::DELETED_NODE &&
6349 N3.getOpcode() != ISD::DELETED_NODE &&
6350 "Operand is DELETED_NODE!");
6351 // Perform various simplifications.
6354 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6355 assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6356 N3.getValueType() == VT && "FMA types must match!");
6357 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6358 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6359 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6360 if (N1CFP && N2CFP && N3CFP) {
6361 APFloat V1 = N1CFP->getValueAPF();
6362 const APFloat &V2 = N2CFP->getValueAPF();
6363 const APFloat &V3 = N3CFP->getValueAPF();
6364 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6365 return getConstantFP(V1, DL, VT);
6369 case ISD::BUILD_VECTOR: {
6370 // Attempt to simplify BUILD_VECTOR.
6371 SDValue Ops[] = {N1, N2, N3};
6372 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6376 case ISD::CONCAT_VECTORS: {
6377 SDValue Ops[] = {N1, N2, N3};
6378 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6383 assert(VT.isInteger() && "SETCC result type must be an integer!");
6384 assert(N1.getValueType() == N2.getValueType() &&
6385 "SETCC operands must have the same type!");
6386 assert(VT.isVector() == N1.getValueType().isVector() &&
6387 "SETCC type should be vector iff the operand type is vector!");
6388 assert((!VT.isVector() || VT.getVectorElementCount() ==
6389 N1.getValueType().getVectorElementCount()) &&
6390 "SETCC vector element counts must match!");
6391 // Use FoldSetCC to simplify SETCC's.
6392 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6394 // Vector constant folding.
6395 SDValue Ops[] = {N1, N2, N3};
6396 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6397 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6404 if (SDValue V = simplifySelect(N1, N2, N3))
6407 case ISD::VECTOR_SHUFFLE:
6408 llvm_unreachable("should use getVectorShuffle constructor!");
6409 case ISD::VECTOR_SPLICE: {
6410 if (cast<ConstantSDNode>(N3)->isNullValue())
6414 case ISD::INSERT_VECTOR_ELT: {
6415 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6416 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6417 // for scalable vectors where we will generate appropriate code to
6418 // deal with out-of-bounds cases correctly.
6419 if (N3C && N1.getValueType().isFixedLengthVector() &&
6420 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6421 return getUNDEF(VT);
6423 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6425 return getUNDEF(VT);
6427 // If the inserted element is an UNDEF, just use the input vector.
6433 case ISD::INSERT_SUBVECTOR: {
6434 // Inserting undef into undef is still undef.
6435 if (N1.isUndef() && N2.isUndef())
6436 return getUNDEF(VT);
6438 EVT N2VT = N2.getValueType();
6439 assert(VT == N1.getValueType() &&
6440 "Dest and insert subvector source types must match!");
6441 assert(VT.isVector() && N2VT.isVector() &&
6442 "Insert subvector VTs must be vectors!");
6443 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6444 "Cannot insert a scalable vector into a fixed length vector!");
6445 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6446 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6447 "Insert subvector must be from smaller vector to larger vector!");
6448 assert(isa<ConstantSDNode>(N3) &&
6449 "Insert subvector index must be constant");
6450 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6451 (N2VT.getVectorMinNumElements() +
6452 cast<ConstantSDNode>(N3)->getZExtValue()) <=
6453 VT.getVectorMinNumElements()) &&
6454 "Insert subvector overflow!");
6455 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6456 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6457 "Constant index for INSERT_SUBVECTOR has an invalid size");
6459 // Trivial insertion.
6463 // If this is an insert of an extracted vector into an undef vector, we
6464 // can just use the input to the extract.
6465 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6466 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6467 return N2.getOperand(0);
6471 // Fold bit_convert nodes from a type to themselves.
6472 if (N1.getValueType() == VT)
6477 // Memoize node if it doesn't produce a flag.
6479 SDVTList VTs = getVTList(VT);
6480 SDValue Ops[] = {N1, N2, N3};
6481 if (VT != MVT::Glue) {
6482 FoldingSetNodeID ID;
6483 AddNodeIDNode(ID, Opcode, VTs, Ops);
6485 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6486 E->intersectFlagsWith(Flags);
6487 return SDValue(E, 0);
6490 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6492 createOperands(N, Ops);
6493 CSEMap.InsertNode(N, IP);
6495 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6496 createOperands(N, Ops);
6500 SDValue V = SDValue(N, 0);
6501 NewSDValueDbgMsg(V, "Creating new node: ", this);
6505 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6506 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6507 SDValue Ops[] = { N1, N2, N3, N4 };
6508 return getNode(Opcode, DL, VT, Ops);
6511 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6512 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6514 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6515 return getNode(Opcode, DL, VT, Ops);
6518 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6519 /// the incoming stack arguments to be loaded from the stack.
6520 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6521 SmallVector<SDValue, 8> ArgChains;
6523 // Include the original chain at the beginning of the list. When this is
6524 // used by target LowerCall hooks, this helps legalize find the
6525 // CALLSEQ_BEGIN node.
6526 ArgChains.push_back(Chain);
6528 // Add a chain value for each stack argument.
6529 for (SDNode *U : getEntryNode().getNode()->uses())
6530 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6531 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6532 if (FI->getIndex() < 0)
6533 ArgChains.push_back(SDValue(L, 1));
6535 // Build a tokenfactor for all the chains.
6536 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6539 /// getMemsetValue - Vectorized representation of the memset value
6541 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6543 assert(!Value.isUndef());
6545 unsigned NumBits = VT.getScalarSizeInBits();
6546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6547 assert(C->getAPIntValue().getBitWidth() == 8);
6548 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6549 if (VT.isInteger()) {
6550 bool IsOpaque = VT.getSizeInBits() > 64 ||
6551 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6552 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6554 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6558 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6559 EVT IntVT = VT.getScalarType();
6560 if (!IntVT.isInteger())
6561 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6563 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6565 // Use a multiplication with 0x010101... to extend the input to the
6567 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6568 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6569 DAG.getConstant(Magic, dl, IntVT));
6572 if (VT != Value.getValueType() && !VT.isInteger())
6573 Value = DAG.getBitcast(VT.getScalarType(), Value);
6574 if (VT != Value.getValueType())
6575 Value = DAG.getSplatBuildVector(VT, dl, Value);
6580 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6581 /// used when a memcpy is turned into a memset when the source is a constant
6583 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6584 const TargetLowering &TLI,
6585 const ConstantDataArraySlice &Slice) {
6586 // Handle vector with all elements zero.
6587 if (Slice.Array == nullptr) {
6589 return DAG.getConstant(0, dl, VT);
6590 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6591 return DAG.getConstantFP(0.0, dl, VT);
6592 if (VT.isVector()) {
6593 unsigned NumElts = VT.getVectorNumElements();
6594 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6595 return DAG.getNode(ISD::BITCAST, dl, VT,
6596 DAG.getConstant(0, dl,
6597 EVT::getVectorVT(*DAG.getContext(),
6600 llvm_unreachable("Expected type!");
6603 assert(!VT.isVector() && "Can't handle vector type here!");
6604 unsigned NumVTBits = VT.getSizeInBits();
6605 unsigned NumVTBytes = NumVTBits / 8;
6606 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6608 APInt Val(NumVTBits, 0);
6609 if (DAG.getDataLayout().isLittleEndian()) {
6610 for (unsigned i = 0; i != NumBytes; ++i)
6611 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6613 for (unsigned i = 0; i != NumBytes; ++i)
6614 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6617 // If the "cost" of materializing the integer immediate is less than the cost
6618 // of a load, then it is cost effective to turn the load into the immediate.
6619 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6620 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6621 return DAG.getConstant(Val, dl, VT);
6625 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6627 const SDNodeFlags Flags) {
6628 EVT VT = Base.getValueType();
6631 if (Offset.isScalable())
6632 Index = getVScale(DL, Base.getValueType(),
6633 APInt(Base.getValueSizeInBits().getFixedSize(),
6634 Offset.getKnownMinSize()));
6636 Index = getConstant(Offset.getFixedSize(), DL, VT);
6638 return getMemBasePlusOffset(Base, Index, DL, Flags);
6641 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6643 const SDNodeFlags Flags) {
6644 assert(Offset.getValueType().isInteger());
6645 EVT BasePtrVT = Ptr.getValueType();
6646 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6649 /// Returns true if memcpy source is constant data.
6650 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6651 uint64_t SrcDelta = 0;
6652 GlobalAddressSDNode *G = nullptr;
6653 if (Src.getOpcode() == ISD::GlobalAddress)
6654 G = cast<GlobalAddressSDNode>(Src);
6655 else if (Src.getOpcode() == ISD::ADD &&
6656 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6657 Src.getOperand(1).getOpcode() == ISD::Constant) {
6658 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6659 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6664 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6665 SrcDelta + G->getOffset());
6668 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6669 SelectionDAG &DAG) {
6670 // On Darwin, -Os means optimize for size without hurting performance, so
6671 // only really optimize for size when -Oz (MinSize) is used.
6672 if (MF.getTarget().getTargetTriple().isOSDarwin())
6673 return MF.getFunction().hasMinSize();
6674 return DAG.shouldOptForSize();
6677 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6678 SmallVector<SDValue, 32> &OutChains, unsigned From,
6679 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6680 SmallVector<SDValue, 16> &OutStoreChains) {
6681 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6682 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6683 SmallVector<SDValue, 16> GluedLoadChains;
6684 for (unsigned i = From; i < To; ++i) {
6685 OutChains.push_back(OutLoadChains[i]);
6686 GluedLoadChains.push_back(OutLoadChains[i]);
6689 // Chain for all loads.
6690 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6693 for (unsigned i = From; i < To; ++i) {
6694 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6695 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6696 ST->getBasePtr(), ST->getMemoryVT(),
6697 ST->getMemOperand());
6698 OutChains.push_back(NewStore);
6702 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6703 SDValue Chain, SDValue Dst, SDValue Src,
6704 uint64_t Size, Align Alignment,
6705 bool isVol, bool AlwaysInline,
6706 MachinePointerInfo DstPtrInfo,
6707 MachinePointerInfo SrcPtrInfo,
6708 const AAMDNodes &AAInfo, AAResults *AA) {
6709 // Turn a memcpy of undef to nop.
6710 // FIXME: We need to honor volatile even is Src is undef.
6714 // Expand memcpy to a series of load and store ops if the size operand falls
6715 // below a certain threshold.
6716 // TODO: In the AlwaysInline case, if the size is big then generate a loop
6717 // rather than maybe a humongous number of loads and stores.
6718 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6719 const DataLayout &DL = DAG.getDataLayout();
6720 LLVMContext &C = *DAG.getContext();
6721 std::vector<EVT> MemOps;
6722 bool DstAlignCanChange = false;
6723 MachineFunction &MF = DAG.getMachineFunction();
6724 MachineFrameInfo &MFI = MF.getFrameInfo();
6725 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6726 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6727 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6728 DstAlignCanChange = true;
6729 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6730 if (!SrcAlign || Alignment > *SrcAlign)
6731 SrcAlign = Alignment;
6732 assert(SrcAlign && "SrcAlign must be set");
6733 ConstantDataArraySlice Slice;
6734 // If marked as volatile, perform a copy even when marked as constant.
6735 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6736 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6737 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6738 const MemOp Op = isZeroConstant
6739 ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6740 /*IsZeroMemset*/ true, isVol)
6741 : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6742 *SrcAlign, isVol, CopyFromConstant);
6743 if (!TLI.findOptimalMemOpLowering(
6744 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6745 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6748 if (DstAlignCanChange) {
6749 Type *Ty = MemOps[0].getTypeForEVT(C);
6750 Align NewAlign = DL.getABITypeAlign(Ty);
6752 // Don't promote to an alignment that would require dynamic stack
6754 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6755 if (!TRI->hasStackRealignment(MF))
6756 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6757 NewAlign = NewAlign.previous();
6759 if (NewAlign > Alignment) {
6760 // Give the stack frame object a larger alignment if needed.
6761 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6762 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6763 Alignment = NewAlign;
6767 // Prepare AAInfo for loads/stores after lowering this memcpy.
6768 AAMDNodes NewAAInfo = AAInfo;
6769 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6771 const Value *SrcVal = SrcPtrInfo.V.dyn_cast<const Value *>();
6774 AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
6776 MachineMemOperand::Flags MMOFlags =
6777 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6778 SmallVector<SDValue, 16> OutLoadChains;
6779 SmallVector<SDValue, 16> OutStoreChains;
6780 SmallVector<SDValue, 32> OutChains;
6781 unsigned NumMemOps = MemOps.size();
6782 uint64_t SrcOff = 0, DstOff = 0;
6783 for (unsigned i = 0; i != NumMemOps; ++i) {
6785 unsigned VTSize = VT.getSizeInBits() / 8;
6786 SDValue Value, Store;
6788 if (VTSize > Size) {
6789 // Issuing an unaligned load / store pair that overlaps with the previous
6790 // pair. Adjust the offset accordingly.
6791 assert(i == NumMemOps-1 && i != 0);
6792 SrcOff -= VTSize - Size;
6793 DstOff -= VTSize - Size;
6796 if (CopyFromConstant &&
6797 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6798 // It's unlikely a store of a vector immediate can be done in a single
6799 // instruction. It would require a load from a constantpool first.
6800 // We only handle zero vectors here.
6801 // FIXME: Handle other cases where store of vector immediate is done in
6802 // a single instruction.
6803 ConstantDataArraySlice SubSlice;
6804 if (SrcOff < Slice.Length) {
6806 SubSlice.move(SrcOff);
6808 // This is an out-of-bounds access and hence UB. Pretend we read zero.
6809 SubSlice.Array = nullptr;
6810 SubSlice.Offset = 0;
6811 SubSlice.Length = VTSize;
6813 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6814 if (Value.getNode()) {
6815 Store = DAG.getStore(
6817 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6818 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6819 OutChains.push_back(Store);
6823 if (!Store.getNode()) {
6824 // The type might not be legal for the target. This should only happen
6825 // if the type is smaller than a legal type, as on PPC, so the right
6826 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
6827 // to Load/Store if NVT==VT.
6828 // FIXME does the case above also need this?
6829 EVT NVT = TLI.getTypeToTransformTo(C, VT);
6830 assert(NVT.bitsGE(VT));
6832 bool isDereferenceable =
6833 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6834 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6835 if (isDereferenceable)
6836 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6838 SrcMMOFlags |= MachineMemOperand::MOInvariant;
6840 Value = DAG.getExtLoad(
6841 ISD::EXTLOAD, dl, NVT, Chain,
6842 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6843 SrcPtrInfo.getWithOffset(SrcOff), VT,
6844 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6845 OutLoadChains.push_back(Value.getValue(1));
6847 Store = DAG.getTruncStore(
6849 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6850 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6851 OutStoreChains.push_back(Store);
6858 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6859 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6860 unsigned NumLdStInMemcpy = OutStoreChains.size();
6862 if (NumLdStInMemcpy) {
6863 // It may be that memcpy might be converted to memset if it's memcpy
6864 // of constants. In such a case, we won't have loads and stores, but
6865 // just stores. In the absence of loads, there is nothing to gang up.
6866 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6867 // If target does not care, just leave as it.
6868 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6869 OutChains.push_back(OutLoadChains[i]);
6870 OutChains.push_back(OutStoreChains[i]);
6873 // Ld/St less than/equal limit set by target.
6874 if (NumLdStInMemcpy <= GluedLdStLimit) {
6875 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6876 NumLdStInMemcpy, OutLoadChains,
6879 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
6880 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6881 unsigned GlueIter = 0;
6883 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6884 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6885 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
6887 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6888 OutLoadChains, OutStoreChains);
6889 GlueIter += GluedLdStLimit;
6893 if (RemainingLdStInMemcpy) {
6894 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6895 RemainingLdStInMemcpy, OutLoadChains,
6901 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6904 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6905 SDValue Chain, SDValue Dst, SDValue Src,
6906 uint64_t Size, Align Alignment,
6907 bool isVol, bool AlwaysInline,
6908 MachinePointerInfo DstPtrInfo,
6909 MachinePointerInfo SrcPtrInfo,
6910 const AAMDNodes &AAInfo) {
6911 // Turn a memmove of undef to nop.
6912 // FIXME: We need to honor volatile even is Src is undef.
6916 // Expand memmove to a series of load and store ops if the size operand falls
6917 // below a certain threshold.
6918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6919 const DataLayout &DL = DAG.getDataLayout();
6920 LLVMContext &C = *DAG.getContext();
6921 std::vector<EVT> MemOps;
6922 bool DstAlignCanChange = false;
6923 MachineFunction &MF = DAG.getMachineFunction();
6924 MachineFrameInfo &MFI = MF.getFrameInfo();
6925 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6926 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6927 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6928 DstAlignCanChange = true;
6929 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6930 if (!SrcAlign || Alignment > *SrcAlign)
6931 SrcAlign = Alignment;
6932 assert(SrcAlign && "SrcAlign must be set");
6933 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6934 if (!TLI.findOptimalMemOpLowering(
6936 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6937 /*IsVolatile*/ true),
6938 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6939 MF.getFunction().getAttributes()))
6942 if (DstAlignCanChange) {
6943 Type *Ty = MemOps[0].getTypeForEVT(C);
6944 Align NewAlign = DL.getABITypeAlign(Ty);
6945 if (NewAlign > Alignment) {
6946 // Give the stack frame object a larger alignment if needed.
6947 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6948 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6949 Alignment = NewAlign;
6953 // Prepare AAInfo for loads/stores after lowering this memmove.
6954 AAMDNodes NewAAInfo = AAInfo;
6955 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6957 MachineMemOperand::Flags MMOFlags =
6958 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6959 uint64_t SrcOff = 0, DstOff = 0;
6960 SmallVector<SDValue, 8> LoadValues;
6961 SmallVector<SDValue, 8> LoadChains;
6962 SmallVector<SDValue, 8> OutChains;
6963 unsigned NumMemOps = MemOps.size();
6964 for (unsigned i = 0; i < NumMemOps; i++) {
6966 unsigned VTSize = VT.getSizeInBits() / 8;
6969 bool isDereferenceable =
6970 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6971 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6972 if (isDereferenceable)
6973 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6975 Value = DAG.getLoad(
6977 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6978 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6979 LoadValues.push_back(Value);
6980 LoadChains.push_back(Value.getValue(1));
6983 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6985 for (unsigned i = 0; i < NumMemOps; i++) {
6987 unsigned VTSize = VT.getSizeInBits() / 8;
6990 Store = DAG.getStore(
6991 Chain, dl, LoadValues[i],
6992 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6993 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6994 OutChains.push_back(Store);
6998 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7001 /// Lower the call to 'memset' intrinsic function into a series of store
7004 /// \param DAG Selection DAG where lowered code is placed.
7005 /// \param dl Link to corresponding IR location.
7006 /// \param Chain Control flow dependency.
7007 /// \param Dst Pointer to destination memory location.
7008 /// \param Src Value of byte to write into the memory.
7009 /// \param Size Number of bytes to write.
7010 /// \param Alignment Alignment of the destination in bytes.
7011 /// \param isVol True if destination is volatile.
7012 /// \param AlwaysInline Makes sure no function call is generated.
7013 /// \param DstPtrInfo IR information on the memory pointer.
7014 /// \returns New head in the control flow, if lowering was successful, empty
7015 /// SDValue otherwise.
7017 /// The function tries to replace 'llvm.memset' intrinsic with several store
7018 /// operations and value calculation code. This is usually profitable for small
7019 /// memory size or when the semantic requires inlining.
7020 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7021 SDValue Chain, SDValue Dst, SDValue Src,
7022 uint64_t Size, Align Alignment, bool isVol,
7023 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7024 const AAMDNodes &AAInfo) {
7025 // Turn a memset of undef to nop.
7026 // FIXME: We need to honor volatile even is Src is undef.
7030 // Expand memset to a series of load/store ops if the size operand
7031 // falls below a certain threshold.
7032 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7033 std::vector<EVT> MemOps;
7034 bool DstAlignCanChange = false;
7035 MachineFunction &MF = DAG.getMachineFunction();
7036 MachineFrameInfo &MFI = MF.getFrameInfo();
7037 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7038 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7039 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7040 DstAlignCanChange = true;
7042 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7043 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7045 if (!TLI.findOptimalMemOpLowering(
7047 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7048 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7051 if (DstAlignCanChange) {
7052 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7053 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7054 if (NewAlign > Alignment) {
7055 // Give the stack frame object a larger alignment if needed.
7056 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7057 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7058 Alignment = NewAlign;
7062 SmallVector<SDValue, 8> OutChains;
7063 uint64_t DstOff = 0;
7064 unsigned NumMemOps = MemOps.size();
7066 // Find the largest store and generate the bit pattern for it.
7067 EVT LargestVT = MemOps[0];
7068 for (unsigned i = 1; i < NumMemOps; i++)
7069 if (MemOps[i].bitsGT(LargestVT))
7070 LargestVT = MemOps[i];
7071 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7073 // Prepare AAInfo for loads/stores after lowering this memset.
7074 AAMDNodes NewAAInfo = AAInfo;
7075 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7077 for (unsigned i = 0; i < NumMemOps; i++) {
7079 unsigned VTSize = VT.getSizeInBits() / 8;
7080 if (VTSize > Size) {
7081 // Issuing an unaligned load / store pair that overlaps with the previous
7082 // pair. Adjust the offset accordingly.
7083 assert(i == NumMemOps-1 && i != 0);
7084 DstOff -= VTSize - Size;
7087 // If this store is smaller than the largest store see whether we can get
7088 // the smaller value for free with a truncate.
7089 SDValue Value = MemSetValue;
7090 if (VT.bitsLT(LargestVT)) {
7091 if (!LargestVT.isVector() && !VT.isVector() &&
7092 TLI.isTruncateFree(LargestVT, VT))
7093 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7095 Value = getMemsetValue(Src, VT, DAG, dl);
7097 assert(Value.getValueType() == VT && "Value with wrong type.");
7098 SDValue Store = DAG.getStore(
7100 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7101 DstPtrInfo.getWithOffset(DstOff), Alignment,
7102 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7104 OutChains.push_back(Store);
7105 DstOff += VT.getSizeInBits() / 8;
7109 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7112 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7114 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7115 // pointer operands can be losslessly bitcasted to pointers of address space 0
7116 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7117 report_fatal_error("cannot lower memory intrinsic in address space " +
7122 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7123 SDValue Src, SDValue Size, Align Alignment,
7124 bool isVol, bool AlwaysInline, bool isTailCall,
7125 MachinePointerInfo DstPtrInfo,
7126 MachinePointerInfo SrcPtrInfo,
7127 const AAMDNodes &AAInfo, AAResults *AA) {
7128 // Check to see if we should lower the memcpy to loads and stores first.
7129 // For cases within the target-specified limits, this is the best choice.
7130 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7132 // Memcpy with size zero? Just return the original chain.
7133 if (ConstantSize->isZero())
7136 SDValue Result = getMemcpyLoadsAndStores(
7137 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7138 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7139 if (Result.getNode())
7143 // Then check to see if we should lower the memcpy with target-specific
7144 // code. If the target chooses to do this, this is the next best.
7146 SDValue Result = TSI->EmitTargetCodeForMemcpy(
7147 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7148 DstPtrInfo, SrcPtrInfo);
7149 if (Result.getNode())
7153 // If we really need inline code and the target declined to provide it,
7154 // use a (potentially long) sequence of loads and stores.
7156 assert(ConstantSize && "AlwaysInline requires a constant size!");
7157 return getMemcpyLoadsAndStores(
7158 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7159 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7162 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7163 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7165 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7166 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7167 // respect volatile, so they may do things like read or write memory
7168 // beyond the given memory regions. But fixing this isn't easy, and most
7169 // people don't care.
7171 // Emit a library call.
7172 TargetLowering::ArgListTy Args;
7173 TargetLowering::ArgListEntry Entry;
7174 Entry.Ty = Type::getInt8PtrTy(*getContext());
7175 Entry.Node = Dst; Args.push_back(Entry);
7176 Entry.Node = Src; Args.push_back(Entry);
7178 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7179 Entry.Node = Size; Args.push_back(Entry);
7180 // FIXME: pass in SDLoc
7181 TargetLowering::CallLoweringInfo CLI(*this);
7184 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7185 Dst.getValueType().getTypeForEVT(*getContext()),
7186 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7187 TLI->getPointerTy(getDataLayout())),
7190 .setTailCall(isTailCall);
7192 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7193 return CallResult.second;
7196 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7197 SDValue Dst, SDValue Src, SDValue Size,
7198 Type *SizeTy, unsigned ElemSz,
7200 MachinePointerInfo DstPtrInfo,
7201 MachinePointerInfo SrcPtrInfo) {
7202 // Emit a library call.
7203 TargetLowering::ArgListTy Args;
7204 TargetLowering::ArgListEntry Entry;
7205 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7207 Args.push_back(Entry);
7210 Args.push_back(Entry);
7214 Args.push_back(Entry);
7216 RTLIB::Libcall LibraryCall =
7217 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7218 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7219 report_fatal_error("Unsupported element size");
7221 TargetLowering::CallLoweringInfo CLI(*this);
7224 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7225 Type::getVoidTy(*getContext()),
7226 getExternalSymbol(TLI->getLibcallName(LibraryCall),
7227 TLI->getPointerTy(getDataLayout())),
7230 .setTailCall(isTailCall);
7232 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7233 return CallResult.second;
7236 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7237 SDValue Src, SDValue Size, Align Alignment,
7238 bool isVol, bool isTailCall,
7239 MachinePointerInfo DstPtrInfo,
7240 MachinePointerInfo SrcPtrInfo,
7241 const AAMDNodes &AAInfo, AAResults *AA) {
7242 // Check to see if we should lower the memmove to loads and stores first.
7243 // For cases within the target-specified limits, this is the best choice.
7244 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7246 // Memmove with size zero? Just return the original chain.
7247 if (ConstantSize->isZero())
7250 SDValue Result = getMemmoveLoadsAndStores(
7251 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7252 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7253 if (Result.getNode())
7257 // Then check to see if we should lower the memmove with target-specific
7258 // code. If the target chooses to do this, this is the next best.
7261 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7262 Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7263 if (Result.getNode())
7267 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7268 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7270 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7271 // not be safe. See memcpy above for more details.
7273 // Emit a library call.
7274 TargetLowering::ArgListTy Args;
7275 TargetLowering::ArgListEntry Entry;
7276 Entry.Ty = Type::getInt8PtrTy(*getContext());
7277 Entry.Node = Dst; Args.push_back(Entry);
7278 Entry.Node = Src; Args.push_back(Entry);
7280 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7281 Entry.Node = Size; Args.push_back(Entry);
7282 // FIXME: pass in SDLoc
7283 TargetLowering::CallLoweringInfo CLI(*this);
7286 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7287 Dst.getValueType().getTypeForEVT(*getContext()),
7288 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7289 TLI->getPointerTy(getDataLayout())),
7292 .setTailCall(isTailCall);
7294 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7295 return CallResult.second;
7298 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7299 SDValue Dst, SDValue Src, SDValue Size,
7300 Type *SizeTy, unsigned ElemSz,
7302 MachinePointerInfo DstPtrInfo,
7303 MachinePointerInfo SrcPtrInfo) {
7304 // Emit a library call.
7305 TargetLowering::ArgListTy Args;
7306 TargetLowering::ArgListEntry Entry;
7307 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7309 Args.push_back(Entry);
7312 Args.push_back(Entry);
7316 Args.push_back(Entry);
7318 RTLIB::Libcall LibraryCall =
7319 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7320 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7321 report_fatal_error("Unsupported element size");
7323 TargetLowering::CallLoweringInfo CLI(*this);
7326 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7327 Type::getVoidTy(*getContext()),
7328 getExternalSymbol(TLI->getLibcallName(LibraryCall),
7329 TLI->getPointerTy(getDataLayout())),
7332 .setTailCall(isTailCall);
7334 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7335 return CallResult.second;
7338 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7339 SDValue Src, SDValue Size, Align Alignment,
7340 bool isVol, bool AlwaysInline, bool isTailCall,
7341 MachinePointerInfo DstPtrInfo,
7342 const AAMDNodes &AAInfo) {
7343 // Check to see if we should lower the memset to stores first.
7344 // For cases within the target-specified limits, this is the best choice.
7345 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7347 // Memset with size zero? Just return the original chain.
7348 if (ConstantSize->isZero())
7351 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7352 ConstantSize->getZExtValue(), Alignment,
7353 isVol, false, DstPtrInfo, AAInfo);
7355 if (Result.getNode())
7359 // Then check to see if we should lower the memset with target-specific
7360 // code. If the target chooses to do this, this is the next best.
7362 SDValue Result = TSI->EmitTargetCodeForMemset(
7363 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7364 if (Result.getNode())
7368 // If we really need inline code and the target declined to provide it,
7369 // use a (potentially long) sequence of loads and stores.
7371 assert(ConstantSize && "AlwaysInline requires a constant size!");
7372 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7373 ConstantSize->getZExtValue(), Alignment,
7374 isVol, true, DstPtrInfo, AAInfo);
7376 "getMemsetStores must return a valid sequence when AlwaysInline");
7380 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7382 // Emit a library call.
7383 auto &Ctx = *getContext();
7384 const auto& DL = getDataLayout();
7386 TargetLowering::CallLoweringInfo CLI(*this);
7387 // FIXME: pass in SDLoc
7388 CLI.setDebugLoc(dl).setChain(Chain);
7390 ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7391 const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7392 const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7394 // Helper function to create an Entry from Node and Type.
7395 const auto CreateEntry = [](SDValue Node, Type *Ty) {
7396 TargetLowering::ArgListEntry Entry;
7402 // If zeroing out and bzero is present, use it.
7403 if (SrcIsZero && BzeroName) {
7404 TargetLowering::ArgListTy Args;
7405 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7406 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7408 TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7409 getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7411 TargetLowering::ArgListTy Args;
7412 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7413 Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7414 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7415 CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7416 Dst.getValueType().getTypeForEVT(Ctx),
7417 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7418 TLI->getPointerTy(DL)),
7422 CLI.setDiscardResult().setTailCall(isTailCall);
7424 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7425 return CallResult.second;
7428 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7429 SDValue Dst, SDValue Value, SDValue Size,
7430 Type *SizeTy, unsigned ElemSz,
7432 MachinePointerInfo DstPtrInfo) {
7433 // Emit a library call.
7434 TargetLowering::ArgListTy Args;
7435 TargetLowering::ArgListEntry Entry;
7436 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7438 Args.push_back(Entry);
7440 Entry.Ty = Type::getInt8Ty(*getContext());
7442 Args.push_back(Entry);
7446 Args.push_back(Entry);
7448 RTLIB::Libcall LibraryCall =
7449 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7450 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7451 report_fatal_error("Unsupported element size");
7453 TargetLowering::CallLoweringInfo CLI(*this);
7456 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7457 Type::getVoidTy(*getContext()),
7458 getExternalSymbol(TLI->getLibcallName(LibraryCall),
7459 TLI->getPointerTy(getDataLayout())),
7462 .setTailCall(isTailCall);
7464 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7465 return CallResult.second;
7468 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7469 SDVTList VTList, ArrayRef<SDValue> Ops,
7470 MachineMemOperand *MMO) {
7471 FoldingSetNodeID ID;
7472 ID.AddInteger(MemVT.getRawBits());
7473 AddNodeIDNode(ID, Opcode, VTList, Ops);
7474 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7475 ID.AddInteger(MMO->getFlags());
7477 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7478 cast<AtomicSDNode>(E)->refineAlignment(MMO);
7479 return SDValue(E, 0);
7482 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7483 VTList, MemVT, MMO);
7484 createOperands(N, Ops);
7486 CSEMap.InsertNode(N, IP);
7488 return SDValue(N, 0);
7491 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7492 EVT MemVT, SDVTList VTs, SDValue Chain,
7493 SDValue Ptr, SDValue Cmp, SDValue Swp,
7494 MachineMemOperand *MMO) {
7495 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7496 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7497 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7499 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7500 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7503 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7504 SDValue Chain, SDValue Ptr, SDValue Val,
7505 MachineMemOperand *MMO) {
7506 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7507 Opcode == ISD::ATOMIC_LOAD_SUB ||
7508 Opcode == ISD::ATOMIC_LOAD_AND ||
7509 Opcode == ISD::ATOMIC_LOAD_CLR ||
7510 Opcode == ISD::ATOMIC_LOAD_OR ||
7511 Opcode == ISD::ATOMIC_LOAD_XOR ||
7512 Opcode == ISD::ATOMIC_LOAD_NAND ||
7513 Opcode == ISD::ATOMIC_LOAD_MIN ||
7514 Opcode == ISD::ATOMIC_LOAD_MAX ||
7515 Opcode == ISD::ATOMIC_LOAD_UMIN ||
7516 Opcode == ISD::ATOMIC_LOAD_UMAX ||
7517 Opcode == ISD::ATOMIC_LOAD_FADD ||
7518 Opcode == ISD::ATOMIC_LOAD_FSUB ||
7519 Opcode == ISD::ATOMIC_LOAD_FMAX ||
7520 Opcode == ISD::ATOMIC_LOAD_FMIN ||
7521 Opcode == ISD::ATOMIC_SWAP ||
7522 Opcode == ISD::ATOMIC_STORE) &&
7523 "Invalid Atomic Op");
7525 EVT VT = Val.getValueType();
7527 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7528 getVTList(VT, MVT::Other);
7529 SDValue Ops[] = {Chain, Ptr, Val};
7530 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7533 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7534 EVT VT, SDValue Chain, SDValue Ptr,
7535 MachineMemOperand *MMO) {
7536 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7538 SDVTList VTs = getVTList(VT, MVT::Other);
7539 SDValue Ops[] = {Chain, Ptr};
7540 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7543 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7544 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7545 if (Ops.size() == 1)
7548 SmallVector<EVT, 4> VTs;
7549 VTs.reserve(Ops.size());
7550 for (const SDValue &Op : Ops)
7551 VTs.push_back(Op.getValueType());
7552 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7555 SDValue SelectionDAG::getMemIntrinsicNode(
7556 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7557 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7558 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7559 if (!Size && MemVT.isScalableVector())
7560 Size = MemoryLocation::UnknownSize;
7562 Size = MemVT.getStoreSize();
7564 MachineFunction &MF = getMachineFunction();
7565 MachineMemOperand *MMO =
7566 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7568 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7571 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7573 ArrayRef<SDValue> Ops, EVT MemVT,
7574 MachineMemOperand *MMO) {
7575 assert((Opcode == ISD::INTRINSIC_VOID ||
7576 Opcode == ISD::INTRINSIC_W_CHAIN ||
7577 Opcode == ISD::PREFETCH ||
7578 ((int)Opcode <= std::numeric_limits<int>::max() &&
7579 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7580 "Opcode is not a memory-accessing opcode!");
7582 // Memoize the node unless it returns a flag.
7583 MemIntrinsicSDNode *N;
7584 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7585 FoldingSetNodeID ID;
7586 AddNodeIDNode(ID, Opcode, VTList, Ops);
7587 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7588 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7589 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7590 ID.AddInteger(MMO->getFlags());
7592 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7593 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7594 return SDValue(E, 0);
7597 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7598 VTList, MemVT, MMO);
7599 createOperands(N, Ops);
7601 CSEMap.InsertNode(N, IP);
7603 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7604 VTList, MemVT, MMO);
7605 createOperands(N, Ops);
7609 NewSDValueDbgMsg(V, "Creating new node: ", this);
7613 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7614 SDValue Chain, int FrameIndex,
7615 int64_t Size, int64_t Offset) {
7616 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7617 const auto VTs = getVTList(MVT::Other);
7620 getFrameIndex(FrameIndex,
7621 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7624 FoldingSetNodeID ID;
7625 AddNodeIDNode(ID, Opcode, VTs, Ops);
7626 ID.AddInteger(FrameIndex);
7627 ID.AddInteger(Size);
7628 ID.AddInteger(Offset);
7630 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7631 return SDValue(E, 0);
7633 LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7634 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7635 createOperands(N, Ops);
7636 CSEMap.InsertNode(N, IP);
7639 NewSDValueDbgMsg(V, "Creating new node: ", this);
7643 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7644 uint64_t Guid, uint64_t Index,
7646 const unsigned Opcode = ISD::PSEUDO_PROBE;
7647 const auto VTs = getVTList(MVT::Other);
7648 SDValue Ops[] = {Chain};
7649 FoldingSetNodeID ID;
7650 AddNodeIDNode(ID, Opcode, VTs, Ops);
7651 ID.AddInteger(Guid);
7652 ID.AddInteger(Index);
7654 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7655 return SDValue(E, 0);
7657 auto *N = newSDNode<PseudoProbeSDNode>(
7658 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7659 createOperands(N, Ops);
7660 CSEMap.InsertNode(N, IP);
7663 NewSDValueDbgMsg(V, "Creating new node: ", this);
7667 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7668 /// MachinePointerInfo record from it. This is particularly useful because the
7669 /// code generator has many cases where it doesn't bother passing in a
7670 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7671 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7672 SelectionDAG &DAG, SDValue Ptr,
7673 int64_t Offset = 0) {
7674 // If this is FI+Offset, we can model it.
7675 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7676 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7677 FI->getIndex(), Offset);
7679 // If this is (FI+Offset1)+Offset2, we can model it.
7680 if (Ptr.getOpcode() != ISD::ADD ||
7681 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7682 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7685 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7686 return MachinePointerInfo::getFixedStack(
7687 DAG.getMachineFunction(), FI,
7688 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7691 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7692 /// MachinePointerInfo record from it. This is particularly useful because the
7693 /// code generator has many cases where it doesn't bother passing in a
7694 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7695 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7696 SelectionDAG &DAG, SDValue Ptr,
7698 // If the 'Offset' value isn't a constant, we can't handle this.
7699 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7700 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7701 if (OffsetOp.isUndef())
7702 return InferPointerInfo(Info, DAG, Ptr);
7706 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7707 EVT VT, const SDLoc &dl, SDValue Chain,
7708 SDValue Ptr, SDValue Offset,
7709 MachinePointerInfo PtrInfo, EVT MemVT,
7711 MachineMemOperand::Flags MMOFlags,
7712 const AAMDNodes &AAInfo, const MDNode *Ranges) {
7713 assert(Chain.getValueType() == MVT::Other &&
7714 "Invalid chain type");
7716 MMOFlags |= MachineMemOperand::MOLoad;
7717 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7718 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7720 if (PtrInfo.V.isNull())
7721 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7723 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7724 MachineFunction &MF = getMachineFunction();
7725 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7726 Alignment, AAInfo, Ranges);
7727 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7730 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7731 EVT VT, const SDLoc &dl, SDValue Chain,
7732 SDValue Ptr, SDValue Offset, EVT MemVT,
7733 MachineMemOperand *MMO) {
7735 ExtType = ISD::NON_EXTLOAD;
7736 } else if (ExtType == ISD::NON_EXTLOAD) {
7737 assert(VT == MemVT && "Non-extending load from different memory type!");
7740 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7741 "Should only be an extending load, not truncating!");
7742 assert(VT.isInteger() == MemVT.isInteger() &&
7743 "Cannot convert from FP to Int or Int -> FP!");
7744 assert(VT.isVector() == MemVT.isVector() &&
7745 "Cannot use an ext load to convert to or from a vector!");
7746 assert((!VT.isVector() ||
7747 VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7748 "Cannot use an ext load to change the number of vector elements!");
7751 bool Indexed = AM != ISD::UNINDEXED;
7752 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7754 SDVTList VTs = Indexed ?
7755 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7756 SDValue Ops[] = { Chain, Ptr, Offset };
7757 FoldingSetNodeID ID;
7758 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7759 ID.AddInteger(MemVT.getRawBits());
7760 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7761 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7762 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7763 ID.AddInteger(MMO->getFlags());
7765 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7766 cast<LoadSDNode>(E)->refineAlignment(MMO);
7767 return SDValue(E, 0);
7769 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7770 ExtType, MemVT, MMO);
7771 createOperands(N, Ops);
7773 CSEMap.InsertNode(N, IP);
7776 NewSDValueDbgMsg(V, "Creating new node: ", this);
7780 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7781 SDValue Ptr, MachinePointerInfo PtrInfo,
7782 MaybeAlign Alignment,
7783 MachineMemOperand::Flags MMOFlags,
7784 const AAMDNodes &AAInfo, const MDNode *Ranges) {
7785 SDValue Undef = getUNDEF(Ptr.getValueType());
7786 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7787 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7790 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7791 SDValue Ptr, MachineMemOperand *MMO) {
7792 SDValue Undef = getUNDEF(Ptr.getValueType());
7793 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7797 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7798 EVT VT, SDValue Chain, SDValue Ptr,
7799 MachinePointerInfo PtrInfo, EVT MemVT,
7800 MaybeAlign Alignment,
7801 MachineMemOperand::Flags MMOFlags,
7802 const AAMDNodes &AAInfo) {
7803 SDValue Undef = getUNDEF(Ptr.getValueType());
7804 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7805 MemVT, Alignment, MMOFlags, AAInfo);
7808 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7809 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7810 MachineMemOperand *MMO) {
7811 SDValue Undef = getUNDEF(Ptr.getValueType());
7812 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7816 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7817 SDValue Base, SDValue Offset,
7818 ISD::MemIndexedMode AM) {
7819 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7820 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7821 // Don't propagate the invariant or dereferenceable flags.
7823 LD->getMemOperand()->getFlags() &
7824 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7825 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7826 LD->getChain(), Base, Offset, LD->getPointerInfo(),
7827 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7830 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7831 SDValue Ptr, MachinePointerInfo PtrInfo,
7833 MachineMemOperand::Flags MMOFlags,
7834 const AAMDNodes &AAInfo) {
7835 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7837 MMOFlags |= MachineMemOperand::MOStore;
7838 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7840 if (PtrInfo.V.isNull())
7841 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7843 MachineFunction &MF = getMachineFunction();
7845 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7846 MachineMemOperand *MMO =
7847 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7848 return getStore(Chain, dl, Val, Ptr, MMO);
7851 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7852 SDValue Ptr, MachineMemOperand *MMO) {
7853 assert(Chain.getValueType() == MVT::Other &&
7854 "Invalid chain type");
7855 EVT VT = Val.getValueType();
7856 SDVTList VTs = getVTList(MVT::Other);
7857 SDValue Undef = getUNDEF(Ptr.getValueType());
7858 SDValue Ops[] = { Chain, Val, Ptr, Undef };
7859 FoldingSetNodeID ID;
7860 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7861 ID.AddInteger(VT.getRawBits());
7862 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7863 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7864 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7865 ID.AddInteger(MMO->getFlags());
7867 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7868 cast<StoreSDNode>(E)->refineAlignment(MMO);
7869 return SDValue(E, 0);
7871 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7872 ISD::UNINDEXED, false, VT, MMO);
7873 createOperands(N, Ops);
7875 CSEMap.InsertNode(N, IP);
7878 NewSDValueDbgMsg(V, "Creating new node: ", this);
7882 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7883 SDValue Ptr, MachinePointerInfo PtrInfo,
7884 EVT SVT, Align Alignment,
7885 MachineMemOperand::Flags MMOFlags,
7886 const AAMDNodes &AAInfo) {
7887 assert(Chain.getValueType() == MVT::Other &&
7888 "Invalid chain type");
7890 MMOFlags |= MachineMemOperand::MOStore;
7891 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7893 if (PtrInfo.V.isNull())
7894 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7896 MachineFunction &MF = getMachineFunction();
7897 MachineMemOperand *MMO = MF.getMachineMemOperand(
7898 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7900 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7903 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7904 SDValue Ptr, EVT SVT,
7905 MachineMemOperand *MMO) {
7906 EVT VT = Val.getValueType();
7908 assert(Chain.getValueType() == MVT::Other &&
7909 "Invalid chain type");
7911 return getStore(Chain, dl, Val, Ptr, MMO);
7913 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7914 "Should only be a truncating store, not extending!");
7915 assert(VT.isInteger() == SVT.isInteger() &&
7916 "Can't do FP-INT conversion!");
7917 assert(VT.isVector() == SVT.isVector() &&
7918 "Cannot use trunc store to convert to or from a vector!");
7919 assert((!VT.isVector() ||
7920 VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7921 "Cannot use trunc store to change the number of vector elements!");
7923 SDVTList VTs = getVTList(MVT::Other);
7924 SDValue Undef = getUNDEF(Ptr.getValueType());
7925 SDValue Ops[] = { Chain, Val, Ptr, Undef };
7926 FoldingSetNodeID ID;
7927 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7928 ID.AddInteger(SVT.getRawBits());
7929 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7930 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7931 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7932 ID.AddInteger(MMO->getFlags());
7934 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7935 cast<StoreSDNode>(E)->refineAlignment(MMO);
7936 return SDValue(E, 0);
7938 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7939 ISD::UNINDEXED, true, SVT, MMO);
7940 createOperands(N, Ops);
7942 CSEMap.InsertNode(N, IP);
7945 NewSDValueDbgMsg(V, "Creating new node: ", this);
7949 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7950 SDValue Base, SDValue Offset,
7951 ISD::MemIndexedMode AM) {
7952 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7953 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7954 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7955 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7956 FoldingSetNodeID ID;
7957 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7958 ID.AddInteger(ST->getMemoryVT().getRawBits());
7959 ID.AddInteger(ST->getRawSubclassData());
7960 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7961 ID.AddInteger(ST->getMemOperand()->getFlags());
7963 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7964 return SDValue(E, 0);
7966 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7967 ST->isTruncatingStore(), ST->getMemoryVT(),
7968 ST->getMemOperand());
7969 createOperands(N, Ops);
7971 CSEMap.InsertNode(N, IP);
7974 NewSDValueDbgMsg(V, "Creating new node: ", this);
7978 SDValue SelectionDAG::getLoadVP(
7979 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7980 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7981 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7982 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7983 const MDNode *Ranges, bool IsExpanding) {
7984 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7986 MMOFlags |= MachineMemOperand::MOLoad;
7987 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7988 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7990 if (PtrInfo.V.isNull())
7991 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7993 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7994 MachineFunction &MF = getMachineFunction();
7995 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7996 Alignment, AAInfo, Ranges);
7997 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
8001 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8002 ISD::LoadExtType ExtType, EVT VT,
8003 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8004 SDValue Offset, SDValue Mask, SDValue EVL,
8005 EVT MemVT, MachineMemOperand *MMO,
8007 bool Indexed = AM != ISD::UNINDEXED;
8008 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8010 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8011 : getVTList(VT, MVT::Other);
8012 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8013 FoldingSetNodeID ID;
8014 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8015 ID.AddInteger(VT.getRawBits());
8016 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8017 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8018 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8019 ID.AddInteger(MMO->getFlags());
8021 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8022 cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8023 return SDValue(E, 0);
8025 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8026 ExtType, IsExpanding, MemVT, MMO);
8027 createOperands(N, Ops);
8029 CSEMap.InsertNode(N, IP);
8032 NewSDValueDbgMsg(V, "Creating new node: ", this);
8036 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8037 SDValue Ptr, SDValue Mask, SDValue EVL,
8038 MachinePointerInfo PtrInfo,
8039 MaybeAlign Alignment,
8040 MachineMemOperand::Flags MMOFlags,
8041 const AAMDNodes &AAInfo, const MDNode *Ranges,
8043 SDValue Undef = getUNDEF(Ptr.getValueType());
8044 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8045 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8049 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8050 SDValue Ptr, SDValue Mask, SDValue EVL,
8051 MachineMemOperand *MMO, bool IsExpanding) {
8052 SDValue Undef = getUNDEF(Ptr.getValueType());
8053 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8054 Mask, EVL, VT, MMO, IsExpanding);
8057 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8058 EVT VT, SDValue Chain, SDValue Ptr,
8059 SDValue Mask, SDValue EVL,
8060 MachinePointerInfo PtrInfo, EVT MemVT,
8061 MaybeAlign Alignment,
8062 MachineMemOperand::Flags MMOFlags,
8063 const AAMDNodes &AAInfo, bool IsExpanding) {
8064 SDValue Undef = getUNDEF(Ptr.getValueType());
8065 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8066 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8070 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8071 EVT VT, SDValue Chain, SDValue Ptr,
8072 SDValue Mask, SDValue EVL, EVT MemVT,
8073 MachineMemOperand *MMO, bool IsExpanding) {
8074 SDValue Undef = getUNDEF(Ptr.getValueType());
8075 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8076 EVL, MemVT, MMO, IsExpanding);
8079 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8080 SDValue Base, SDValue Offset,
8081 ISD::MemIndexedMode AM) {
8082 auto *LD = cast<VPLoadSDNode>(OrigLoad);
8083 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8084 // Don't propagate the invariant or dereferenceable flags.
8086 LD->getMemOperand()->getFlags() &
8087 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8088 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8089 LD->getChain(), Base, Offset, LD->getMask(),
8090 LD->getVectorLength(), LD->getPointerInfo(),
8091 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8092 nullptr, LD->isExpandingLoad());
8095 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8096 SDValue Ptr, SDValue Offset, SDValue Mask,
8097 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8098 ISD::MemIndexedMode AM, bool IsTruncating,
8099 bool IsCompressing) {
8100 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8101 bool Indexed = AM != ISD::UNINDEXED;
8102 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8103 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8104 : getVTList(MVT::Other);
8105 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8106 FoldingSetNodeID ID;
8107 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8108 ID.AddInteger(MemVT.getRawBits());
8109 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8110 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8111 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8112 ID.AddInteger(MMO->getFlags());
8114 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8115 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8116 return SDValue(E, 0);
8118 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8119 IsTruncating, IsCompressing, MemVT, MMO);
8120 createOperands(N, Ops);
8122 CSEMap.InsertNode(N, IP);
8125 NewSDValueDbgMsg(V, "Creating new node: ", this);
8129 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8130 SDValue Val, SDValue Ptr, SDValue Mask,
8131 SDValue EVL, MachinePointerInfo PtrInfo,
8132 EVT SVT, Align Alignment,
8133 MachineMemOperand::Flags MMOFlags,
8134 const AAMDNodes &AAInfo,
8135 bool IsCompressing) {
8136 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8138 MMOFlags |= MachineMemOperand::MOStore;
8139 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8141 if (PtrInfo.V.isNull())
8142 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8144 MachineFunction &MF = getMachineFunction();
8145 MachineMemOperand *MMO = MF.getMachineMemOperand(
8146 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8148 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8152 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8153 SDValue Val, SDValue Ptr, SDValue Mask,
8154 SDValue EVL, EVT SVT,
8155 MachineMemOperand *MMO,
8156 bool IsCompressing) {
8157 EVT VT = Val.getValueType();
8159 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8161 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8162 EVL, VT, MMO, ISD::UNINDEXED,
8163 /*IsTruncating*/ false, IsCompressing);
8165 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8166 "Should only be a truncating store, not extending!");
8167 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8168 assert(VT.isVector() == SVT.isVector() &&
8169 "Cannot use trunc store to convert to or from a vector!");
8170 assert((!VT.isVector() ||
8171 VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8172 "Cannot use trunc store to change the number of vector elements!");
8174 SDVTList VTs = getVTList(MVT::Other);
8175 SDValue Undef = getUNDEF(Ptr.getValueType());
8176 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8177 FoldingSetNodeID ID;
8178 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8179 ID.AddInteger(SVT.getRawBits());
8180 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8181 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8182 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8183 ID.AddInteger(MMO->getFlags());
8185 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8186 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8187 return SDValue(E, 0);
8190 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8191 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8192 createOperands(N, Ops);
8194 CSEMap.InsertNode(N, IP);
8197 NewSDValueDbgMsg(V, "Creating new node: ", this);
8201 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8202 SDValue Base, SDValue Offset,
8203 ISD::MemIndexedMode AM) {
8204 auto *ST = cast<VPStoreSDNode>(OrigStore);
8205 assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8206 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8207 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8208 Offset, ST->getMask(), ST->getVectorLength()};
8209 FoldingSetNodeID ID;
8210 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8211 ID.AddInteger(ST->getMemoryVT().getRawBits());
8212 ID.AddInteger(ST->getRawSubclassData());
8213 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8214 ID.AddInteger(ST->getMemOperand()->getFlags());
8216 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8217 return SDValue(E, 0);
8219 auto *N = newSDNode<VPStoreSDNode>(
8220 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8221 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8222 createOperands(N, Ops);
8224 CSEMap.InsertNode(N, IP);
8227 NewSDValueDbgMsg(V, "Creating new node: ", this);
8231 SDValue SelectionDAG::getStridedLoadVP(
8232 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8233 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8234 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8235 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8236 const MDNode *Ranges, bool IsExpanding) {
8237 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8239 MMOFlags |= MachineMemOperand::MOLoad;
8240 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8241 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8243 if (PtrInfo.V.isNull())
8244 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8246 uint64_t Size = MemoryLocation::UnknownSize;
8247 MachineFunction &MF = getMachineFunction();
8248 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8249 Alignment, AAInfo, Ranges);
8250 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8251 EVL, MemVT, MMO, IsExpanding);
8254 SDValue SelectionDAG::getStridedLoadVP(
8255 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8256 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8257 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8258 bool Indexed = AM != ISD::UNINDEXED;
8259 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8261 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8262 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8263 : getVTList(VT, MVT::Other);
8264 FoldingSetNodeID ID;
8265 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8266 ID.AddInteger(VT.getRawBits());
8267 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8268 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8269 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8272 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8273 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8274 return SDValue(E, 0);
8278 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8279 ExtType, IsExpanding, MemVT, MMO);
8280 createOperands(N, Ops);
8281 CSEMap.InsertNode(N, IP);
8284 NewSDValueDbgMsg(V, "Creating new node: ", this);
8288 SDValue SelectionDAG::getStridedLoadVP(
8289 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8290 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8291 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8292 const MDNode *Ranges, bool IsExpanding) {
8293 SDValue Undef = getUNDEF(Ptr.getValueType());
8294 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8295 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8296 MMOFlags, AAInfo, Ranges, IsExpanding);
8299 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8300 SDValue Ptr, SDValue Stride,
8301 SDValue Mask, SDValue EVL,
8302 MachineMemOperand *MMO,
8304 SDValue Undef = getUNDEF(Ptr.getValueType());
8305 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8306 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8309 SDValue SelectionDAG::getExtStridedLoadVP(
8310 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8311 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8312 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8313 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8315 SDValue Undef = getUNDEF(Ptr.getValueType());
8316 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8317 Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8318 MMOFlags, AAInfo, nullptr, IsExpanding);
8321 SDValue SelectionDAG::getExtStridedLoadVP(
8322 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8323 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8324 MachineMemOperand *MMO, bool IsExpanding) {
8325 SDValue Undef = getUNDEF(Ptr.getValueType());
8326 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8327 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8330 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8331 SDValue Base, SDValue Offset,
8332 ISD::MemIndexedMode AM) {
8333 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8334 assert(SLD->getOffset().isUndef() &&
8335 "Strided load is already a indexed load!");
8336 // Don't propagate the invariant or dereferenceable flags.
8338 SLD->getMemOperand()->getFlags() &
8339 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8340 return getStridedLoadVP(
8341 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8342 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8343 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8344 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8347 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8348 SDValue Val, SDValue Ptr,
8349 SDValue Offset, SDValue Stride,
8350 SDValue Mask, SDValue EVL, EVT MemVT,
8351 MachineMemOperand *MMO,
8352 ISD::MemIndexedMode AM,
8353 bool IsTruncating, bool IsCompressing) {
8354 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8355 bool Indexed = AM != ISD::UNINDEXED;
8356 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8357 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8358 : getVTList(MVT::Other);
8359 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8360 FoldingSetNodeID ID;
8361 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8362 ID.AddInteger(MemVT.getRawBits());
8363 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8364 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8365 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8367 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8368 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8369 return SDValue(E, 0);
8371 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8372 VTs, AM, IsTruncating,
8373 IsCompressing, MemVT, MMO);
8374 createOperands(N, Ops);
8376 CSEMap.InsertNode(N, IP);
8379 NewSDValueDbgMsg(V, "Creating new node: ", this);
8383 SDValue SelectionDAG::getTruncStridedStoreVP(
8384 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8385 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8386 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8387 bool IsCompressing) {
8388 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8390 MMOFlags |= MachineMemOperand::MOStore;
8391 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8393 if (PtrInfo.V.isNull())
8394 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8396 MachineFunction &MF = getMachineFunction();
8397 MachineMemOperand *MMO = MF.getMachineMemOperand(
8398 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8399 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8400 MMO, IsCompressing);
8403 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8404 SDValue Val, SDValue Ptr,
8405 SDValue Stride, SDValue Mask,
8406 SDValue EVL, EVT SVT,
8407 MachineMemOperand *MMO,
8408 bool IsCompressing) {
8409 EVT VT = Val.getValueType();
8411 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8413 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8414 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8415 /*IsTruncating*/ false, IsCompressing);
8417 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8418 "Should only be a truncating store, not extending!");
8419 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8420 assert(VT.isVector() == SVT.isVector() &&
8421 "Cannot use trunc store to convert to or from a vector!");
8422 assert((!VT.isVector() ||
8423 VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8424 "Cannot use trunc store to change the number of vector elements!");
8426 SDVTList VTs = getVTList(MVT::Other);
8427 SDValue Undef = getUNDEF(Ptr.getValueType());
8428 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8429 FoldingSetNodeID ID;
8430 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8431 ID.AddInteger(SVT.getRawBits());
8432 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8433 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8434 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8436 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8437 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8438 return SDValue(E, 0);
8440 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8441 VTs, ISD::UNINDEXED, true,
8442 IsCompressing, SVT, MMO);
8443 createOperands(N, Ops);
8445 CSEMap.InsertNode(N, IP);
8448 NewSDValueDbgMsg(V, "Creating new node: ", this);
8452 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8453 const SDLoc &DL, SDValue Base,
8455 ISD::MemIndexedMode AM) {
8456 auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8457 assert(SST->getOffset().isUndef() &&
8458 "Strided store is already an indexed store!");
8459 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8461 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(),
8462 SST->getMask(), SST->getVectorLength()};
8463 FoldingSetNodeID ID;
8464 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8465 ID.AddInteger(SST->getMemoryVT().getRawBits());
8466 ID.AddInteger(SST->getRawSubclassData());
8467 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8469 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8470 return SDValue(E, 0);
8472 auto *N = newSDNode<VPStridedStoreSDNode>(
8473 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8474 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8475 createOperands(N, Ops);
8477 CSEMap.InsertNode(N, IP);
8480 NewSDValueDbgMsg(V, "Creating new node: ", this);
8484 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8485 ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8486 ISD::MemIndexType IndexType) {
8487 assert(Ops.size() == 6 && "Incompatible number of operands");
8489 FoldingSetNodeID ID;
8490 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8491 ID.AddInteger(VT.getRawBits());
8492 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8493 dl.getIROrder(), VTs, VT, MMO, IndexType));
8494 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8495 ID.AddInteger(MMO->getFlags());
8497 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8498 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8499 return SDValue(E, 0);
8502 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8503 VT, MMO, IndexType);
8504 createOperands(N, Ops);
8506 assert(N->getMask().getValueType().getVectorElementCount() ==
8507 N->getValueType(0).getVectorElementCount() &&
8508 "Vector width mismatch between mask and data");
8509 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8510 N->getValueType(0).getVectorElementCount().isScalable() &&
8511 "Scalable flags of index and data do not match");
8512 assert(ElementCount::isKnownGE(
8513 N->getIndex().getValueType().getVectorElementCount(),
8514 N->getValueType(0).getVectorElementCount()) &&
8515 "Vector width mismatch between index and data");
8516 assert(isa<ConstantSDNode>(N->getScale()) &&
8517 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8518 "Scale should be a constant power of 2");
8520 CSEMap.InsertNode(N, IP);
8523 NewSDValueDbgMsg(V, "Creating new node: ", this);
8527 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8528 ArrayRef<SDValue> Ops,
8529 MachineMemOperand *MMO,
8530 ISD::MemIndexType IndexType) {
8531 assert(Ops.size() == 7 && "Incompatible number of operands");
8533 FoldingSetNodeID ID;
8534 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8535 ID.AddInteger(VT.getRawBits());
8536 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8537 dl.getIROrder(), VTs, VT, MMO, IndexType));
8538 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8539 ID.AddInteger(MMO->getFlags());
8541 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8542 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8543 return SDValue(E, 0);
8545 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8546 VT, MMO, IndexType);
8547 createOperands(N, Ops);
8549 assert(N->getMask().getValueType().getVectorElementCount() ==
8550 N->getValue().getValueType().getVectorElementCount() &&
8551 "Vector width mismatch between mask and data");
8553 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8554 N->getValue().getValueType().getVectorElementCount().isScalable() &&
8555 "Scalable flags of index and data do not match");
8556 assert(ElementCount::isKnownGE(
8557 N->getIndex().getValueType().getVectorElementCount(),
8558 N->getValue().getValueType().getVectorElementCount()) &&
8559 "Vector width mismatch between index and data");
8560 assert(isa<ConstantSDNode>(N->getScale()) &&
8561 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8562 "Scale should be a constant power of 2");
8564 CSEMap.InsertNode(N, IP);
8567 NewSDValueDbgMsg(V, "Creating new node: ", this);
8571 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8572 SDValue Base, SDValue Offset, SDValue Mask,
8573 SDValue PassThru, EVT MemVT,
8574 MachineMemOperand *MMO,
8575 ISD::MemIndexedMode AM,
8576 ISD::LoadExtType ExtTy, bool isExpanding) {
8577 bool Indexed = AM != ISD::UNINDEXED;
8578 assert((Indexed || Offset.isUndef()) &&
8579 "Unindexed masked load with an offset!");
8580 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8581 : getVTList(VT, MVT::Other);
8582 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8583 FoldingSetNodeID ID;
8584 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8585 ID.AddInteger(MemVT.getRawBits());
8586 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8587 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8588 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8589 ID.AddInteger(MMO->getFlags());
8591 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8592 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8593 return SDValue(E, 0);
8595 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8596 AM, ExtTy, isExpanding, MemVT, MMO);
8597 createOperands(N, Ops);
8599 CSEMap.InsertNode(N, IP);
8602 NewSDValueDbgMsg(V, "Creating new node: ", this);
8606 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8607 SDValue Base, SDValue Offset,
8608 ISD::MemIndexedMode AM) {
8609 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8610 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8611 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8612 Offset, LD->getMask(), LD->getPassThru(),
8613 LD->getMemoryVT(), LD->getMemOperand(), AM,
8614 LD->getExtensionType(), LD->isExpandingLoad());
8617 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8618 SDValue Val, SDValue Base, SDValue Offset,
8619 SDValue Mask, EVT MemVT,
8620 MachineMemOperand *MMO,
8621 ISD::MemIndexedMode AM, bool IsTruncating,
8622 bool IsCompressing) {
8623 assert(Chain.getValueType() == MVT::Other &&
8624 "Invalid chain type");
8625 bool Indexed = AM != ISD::UNINDEXED;
8626 assert((Indexed || Offset.isUndef()) &&
8627 "Unindexed masked store with an offset!");
8628 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8629 : getVTList(MVT::Other);
8630 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8631 FoldingSetNodeID ID;
8632 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8633 ID.AddInteger(MemVT.getRawBits());
8634 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8635 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8636 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8637 ID.AddInteger(MMO->getFlags());
8639 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8640 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8641 return SDValue(E, 0);
8644 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8645 IsTruncating, IsCompressing, MemVT, MMO);
8646 createOperands(N, Ops);
8648 CSEMap.InsertNode(N, IP);
8651 NewSDValueDbgMsg(V, "Creating new node: ", this);
8655 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8656 SDValue Base, SDValue Offset,
8657 ISD::MemIndexedMode AM) {
8658 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8659 assert(ST->getOffset().isUndef() &&
8660 "Masked store is already a indexed store!");
8661 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8662 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8663 AM, ST->isTruncatingStore(), ST->isCompressingStore());
8666 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8667 ArrayRef<SDValue> Ops,
8668 MachineMemOperand *MMO,
8669 ISD::MemIndexType IndexType,
8670 ISD::LoadExtType ExtTy) {
8671 assert(Ops.size() == 6 && "Incompatible number of operands");
8673 FoldingSetNodeID ID;
8674 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8675 ID.AddInteger(MemVT.getRawBits());
8676 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8677 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8678 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8679 ID.AddInteger(MMO->getFlags());
8681 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8682 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8683 return SDValue(E, 0);
8686 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8687 VTs, MemVT, MMO, IndexType, ExtTy);
8688 createOperands(N, Ops);
8690 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8691 "Incompatible type of the PassThru value in MaskedGatherSDNode");
8692 assert(N->getMask().getValueType().getVectorElementCount() ==
8693 N->getValueType(0).getVectorElementCount() &&
8694 "Vector width mismatch between mask and data");
8695 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8696 N->getValueType(0).getVectorElementCount().isScalable() &&
8697 "Scalable flags of index and data do not match");
8698 assert(ElementCount::isKnownGE(
8699 N->getIndex().getValueType().getVectorElementCount(),
8700 N->getValueType(0).getVectorElementCount()) &&
8701 "Vector width mismatch between index and data");
8702 assert(isa<ConstantSDNode>(N->getScale()) &&
8703 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8704 "Scale should be a constant power of 2");
8706 CSEMap.InsertNode(N, IP);
8709 NewSDValueDbgMsg(V, "Creating new node: ", this);
8713 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8714 ArrayRef<SDValue> Ops,
8715 MachineMemOperand *MMO,
8716 ISD::MemIndexType IndexType,
8718 assert(Ops.size() == 6 && "Incompatible number of operands");
8720 FoldingSetNodeID ID;
8721 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8722 ID.AddInteger(MemVT.getRawBits());
8723 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8724 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8725 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8726 ID.AddInteger(MMO->getFlags());
8728 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8729 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8730 return SDValue(E, 0);
8733 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8734 VTs, MemVT, MMO, IndexType, IsTrunc);
8735 createOperands(N, Ops);
8737 assert(N->getMask().getValueType().getVectorElementCount() ==
8738 N->getValue().getValueType().getVectorElementCount() &&
8739 "Vector width mismatch between mask and data");
8741 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8742 N->getValue().getValueType().getVectorElementCount().isScalable() &&
8743 "Scalable flags of index and data do not match");
8744 assert(ElementCount::isKnownGE(
8745 N->getIndex().getValueType().getVectorElementCount(),
8746 N->getValue().getValueType().getVectorElementCount()) &&
8747 "Vector width mismatch between index and data");
8748 assert(isa<ConstantSDNode>(N->getScale()) &&
8749 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8750 "Scale should be a constant power of 2");
8752 CSEMap.InsertNode(N, IP);
8755 NewSDValueDbgMsg(V, "Creating new node: ", this);
8759 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8760 // select undef, T, F --> T (if T is a constant), otherwise F
8761 // select, ?, undef, F --> F
8762 // select, ?, T, undef --> T
8764 return isConstantValueOfAnyType(T) ? T : F;
8770 // select true, T, F --> T
8771 // select false, T, F --> F
8772 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8773 return CondC->isZero() ? F : T;
8775 // TODO: This should simplify VSELECT with constant condition using something
8776 // like this (but check boolean contents to be complete?):
8777 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8779 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8782 // select ?, T, T --> T
8789 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8790 // shift undef, Y --> 0 (can always assume that the undef value is 0)
8792 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8793 // shift X, undef --> undef (because it may shift by the bitwidth)
8795 return getUNDEF(X.getValueType());
8799 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8802 // shift X, C >= bitwidth(X) --> undef
8803 // All vector elements must be too big (or undef) to avoid partial undefs.
8804 auto isShiftTooBig = [X](ConstantSDNode *Val) {
8805 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8807 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8808 return getUNDEF(X.getValueType());
8813 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8814 SDNodeFlags Flags) {
8815 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8816 // (an undef operand can be chosen to be Nan/Inf), then the result of this
8817 // operation is poison. That result can be relaxed to undef.
8818 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8819 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8820 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8821 (YC && YC->getValueAPF().isNaN());
8822 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8823 (YC && YC->getValueAPF().isInfinity());
8825 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8826 return getUNDEF(X.getValueType());
8828 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8829 return getUNDEF(X.getValueType());
8835 if (Opcode == ISD::FADD)
8836 if (YC->getValueAPF().isNegZero())
8840 if (Opcode == ISD::FSUB)
8841 if (YC->getValueAPF().isPosZero())
8846 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8847 if (YC->getValueAPF().isExactlyValue(1.0))
8851 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8852 if (YC->getValueAPF().isZero())
8853 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8858 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8859 SDValue Ptr, SDValue SV, unsigned Align) {
8860 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8861 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8864 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8865 ArrayRef<SDUse> Ops) {
8866 switch (Ops.size()) {
8867 case 0: return getNode(Opcode, DL, VT);
8868 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8869 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8870 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8874 // Copy from an SDUse array into an SDValue array for use with
8875 // the regular getNode logic.
8876 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8877 return getNode(Opcode, DL, VT, NewOps);
8880 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8881 ArrayRef<SDValue> Ops) {
8884 Flags = Inserter->getFlags();
8885 return getNode(Opcode, DL, VT, Ops, Flags);
8888 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8889 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8890 unsigned NumOps = Ops.size();
8892 case 0: return getNode(Opcode, DL, VT);
8893 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8894 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8895 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8900 for (const auto &Op : Ops)
8901 assert(Op.getOpcode() != ISD::DELETED_NODE &&
8902 "Operand is DELETED_NODE!");
8907 case ISD::BUILD_VECTOR:
8908 // Attempt to simplify BUILD_VECTOR.
8909 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8912 case ISD::CONCAT_VECTORS:
8913 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8916 case ISD::SELECT_CC:
8917 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8918 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8919 "LHS and RHS of condition must have same type!");
8920 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8921 "True and False arms of SelectCC must have same type!");
8922 assert(Ops[2].getValueType() == VT &&
8923 "select_cc node must be of same type as true and false value!");
8924 assert((!Ops[0].getValueType().isVector() ||
8925 Ops[0].getValueType().getVectorElementCount() ==
8926 VT.getVectorElementCount()) &&
8927 "Expected select_cc with vector result to have the same sized "
8928 "comparison type!");
8931 assert(NumOps == 5 && "BR_CC takes 5 operands!");
8932 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8933 "LHS/RHS of comparison should match types!");
8937 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8938 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8939 Opcode = ISD::VP_XOR;
8942 // If it is VP_MUL mask operation then turn it to VP_AND
8943 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8944 Opcode = ISD::VP_AND;
8946 case ISD::VP_REDUCE_MUL:
8947 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8949 Opcode = ISD::VP_REDUCE_AND;
8951 case ISD::VP_REDUCE_ADD:
8952 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8954 Opcode = ISD::VP_REDUCE_XOR;
8956 case ISD::VP_REDUCE_SMAX:
8957 case ISD::VP_REDUCE_UMIN:
8958 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8961 Opcode = ISD::VP_REDUCE_AND;
8963 case ISD::VP_REDUCE_SMIN:
8964 case ISD::VP_REDUCE_UMAX:
8965 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8968 Opcode = ISD::VP_REDUCE_OR;
8974 SDVTList VTs = getVTList(VT);
8976 if (VT != MVT::Glue) {
8977 FoldingSetNodeID ID;
8978 AddNodeIDNode(ID, Opcode, VTs, Ops);
8981 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8982 return SDValue(E, 0);
8984 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8985 createOperands(N, Ops);
8987 CSEMap.InsertNode(N, IP);
8989 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8990 createOperands(N, Ops);
8996 NewSDValueDbgMsg(V, "Creating new node: ", this);
9000 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9001 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
9002 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
9005 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9006 ArrayRef<SDValue> Ops) {
9009 Flags = Inserter->getFlags();
9010 return getNode(Opcode, DL, VTList, Ops, Flags);
9013 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9014 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9015 if (VTList.NumVTs == 1)
9016 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9019 for (const auto &Op : Ops)
9020 assert(Op.getOpcode() != ISD::DELETED_NODE &&
9021 "Operand is DELETED_NODE!");
9029 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9030 "Invalid add/sub overflow op!");
9031 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
9032 Ops[0].getValueType() == Ops[1].getValueType() &&
9033 Ops[0].getValueType() == VTList.VTs[0] &&
9034 "Binary operator types must match!");
9035 SDValue N1 = Ops[0], N2 = Ops[1];
9036 canonicalizeCommutativeBinop(Opcode, N1, N2);
9038 // (X +- 0) -> X with zero-overflow.
9039 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
9040 /*AllowTruncation*/ true);
9041 if (N2CV && N2CV->isZero()) {
9042 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
9043 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
9047 case ISD::SMUL_LOHI:
9048 case ISD::UMUL_LOHI: {
9049 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
9050 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
9051 VTList.VTs[0] == Ops[0].getValueType() &&
9052 VTList.VTs[0] == Ops[1].getValueType() &&
9053 "Binary operator types must match!");
9056 case ISD::STRICT_FP_EXTEND:
9057 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9058 "Invalid STRICT_FP_EXTEND!");
9059 assert(VTList.VTs[0].isFloatingPoint() &&
9060 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9061 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9062 "STRICT_FP_EXTEND result type should be vector iff the operand "
9064 assert((!VTList.VTs[0].isVector() ||
9065 VTList.VTs[0].getVectorNumElements() ==
9066 Ops[1].getValueType().getVectorNumElements()) &&
9067 "Vector element count mismatch!");
9068 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9069 "Invalid fpext node, dst <= src!");
9071 case ISD::STRICT_FP_ROUND:
9072 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9073 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9074 "STRICT_FP_ROUND result type should be vector iff the operand "
9076 assert((!VTList.VTs[0].isVector() ||
9077 VTList.VTs[0].getVectorNumElements() ==
9078 Ops[1].getValueType().getVectorNumElements()) &&
9079 "Vector element count mismatch!");
9080 assert(VTList.VTs[0].isFloatingPoint() &&
9081 Ops[1].getValueType().isFloatingPoint() &&
9082 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9083 isa<ConstantSDNode>(Ops[2]) &&
9084 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9085 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9086 "Invalid STRICT_FP_ROUND!");
9089 // FIXME: figure out how to safely handle things like
9090 // int foo(int x) { return 1 << (x & 255); }
9091 // int bar() { return foo(256); }
9092 case ISD::SRA_PARTS:
9093 case ISD::SRL_PARTS:
9094 case ISD::SHL_PARTS:
9095 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9096 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9097 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9098 else if (N3.getOpcode() == ISD::AND)
9099 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9100 // If the and is only masking out bits that cannot effect the shift,
9101 // eliminate the and.
9102 unsigned NumBits = VT.getScalarSizeInBits()*2;
9103 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9104 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9110 // Memoize the node unless it returns a flag.
9112 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9113 FoldingSetNodeID ID;
9114 AddNodeIDNode(ID, Opcode, VTList, Ops);
9116 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9117 return SDValue(E, 0);
9119 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9120 createOperands(N, Ops);
9121 CSEMap.InsertNode(N, IP);
9123 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9124 createOperands(N, Ops);
9130 NewSDValueDbgMsg(V, "Creating new node: ", this);
9134 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9136 return getNode(Opcode, DL, VTList, None);
9139 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9141 SDValue Ops[] = { N1 };
9142 return getNode(Opcode, DL, VTList, Ops);
9145 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9146 SDValue N1, SDValue N2) {
9147 SDValue Ops[] = { N1, N2 };
9148 return getNode(Opcode, DL, VTList, Ops);
9151 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9152 SDValue N1, SDValue N2, SDValue N3) {
9153 SDValue Ops[] = { N1, N2, N3 };
9154 return getNode(Opcode, DL, VTList, Ops);
9157 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9158 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9159 SDValue Ops[] = { N1, N2, N3, N4 };
9160 return getNode(Opcode, DL, VTList, Ops);
9163 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9164 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9166 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9167 return getNode(Opcode, DL, VTList, Ops);
9170 SDVTList SelectionDAG::getVTList(EVT VT) {
9171 return makeVTList(SDNode::getValueTypeList(VT), 1);
9174 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9175 FoldingSetNodeID ID;
9177 ID.AddInteger(VT1.getRawBits());
9178 ID.AddInteger(VT2.getRawBits());
9181 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9183 EVT *Array = Allocator.Allocate<EVT>(2);
9186 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9187 VTListMap.InsertNode(Result, IP);
9189 return Result->getSDVTList();
9192 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9193 FoldingSetNodeID ID;
9195 ID.AddInteger(VT1.getRawBits());
9196 ID.AddInteger(VT2.getRawBits());
9197 ID.AddInteger(VT3.getRawBits());
9200 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9202 EVT *Array = Allocator.Allocate<EVT>(3);
9206 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9207 VTListMap.InsertNode(Result, IP);
9209 return Result->getSDVTList();
9212 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9213 FoldingSetNodeID ID;
9215 ID.AddInteger(VT1.getRawBits());
9216 ID.AddInteger(VT2.getRawBits());
9217 ID.AddInteger(VT3.getRawBits());
9218 ID.AddInteger(VT4.getRawBits());
9221 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9223 EVT *Array = Allocator.Allocate<EVT>(4);
9228 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9229 VTListMap.InsertNode(Result, IP);
9231 return Result->getSDVTList();
9234 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9235 unsigned NumVTs = VTs.size();
9236 FoldingSetNodeID ID;
9237 ID.AddInteger(NumVTs);
9238 for (unsigned index = 0; index < NumVTs; index++) {
9239 ID.AddInteger(VTs[index].getRawBits());
9243 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9245 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9246 llvm::copy(VTs, Array);
9247 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9248 VTListMap.InsertNode(Result, IP);
9250 return Result->getSDVTList();
9254 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9255 /// specified operands. If the resultant node already exists in the DAG,
9256 /// this does not modify the specified node, instead it returns the node that
9257 /// already exists. If the resultant node does not exist in the DAG, the
9258 /// input node is returned. As a degenerate case, if you specify the same
9259 /// input operands as the node already has, the input node is returned.
9260 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9261 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9263 // Check to see if there is no change.
9264 if (Op == N->getOperand(0)) return N;
9266 // See if the modified node already exists.
9267 void *InsertPos = nullptr;
9268 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9271 // Nope it doesn't. Remove the node from its current place in the maps.
9273 if (!RemoveNodeFromCSEMaps(N))
9274 InsertPos = nullptr;
9276 // Now we update the operands.
9277 N->OperandList[0].set(Op);
9279 updateDivergence(N);
9280 // If this gets put into a CSE map, add it.
9281 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9285 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9286 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9288 // Check to see if there is no change.
9289 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9290 return N; // No operands changed, just return the input node.
9292 // See if the modified node already exists.
9293 void *InsertPos = nullptr;
9294 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9297 // Nope it doesn't. Remove the node from its current place in the maps.
9299 if (!RemoveNodeFromCSEMaps(N))
9300 InsertPos = nullptr;
9302 // Now we update the operands.
9303 if (N->OperandList[0] != Op1)
9304 N->OperandList[0].set(Op1);
9305 if (N->OperandList[1] != Op2)
9306 N->OperandList[1].set(Op2);
9308 updateDivergence(N);
9309 // If this gets put into a CSE map, add it.
9310 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9314 SDNode *SelectionDAG::
9315 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9316 SDValue Ops[] = { Op1, Op2, Op3 };
9317 return UpdateNodeOperands(N, Ops);
9320 SDNode *SelectionDAG::
9321 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9322 SDValue Op3, SDValue Op4) {
9323 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9324 return UpdateNodeOperands(N, Ops);
9327 SDNode *SelectionDAG::
9328 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9329 SDValue Op3, SDValue Op4, SDValue Op5) {
9330 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9331 return UpdateNodeOperands(N, Ops);
9334 SDNode *SelectionDAG::
9335 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9336 unsigned NumOps = Ops.size();
9337 assert(N->getNumOperands() == NumOps &&
9338 "Update with wrong number of operands");
9340 // If no operands changed just return the input node.
9341 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9344 // See if the modified node already exists.
9345 void *InsertPos = nullptr;
9346 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9349 // Nope it doesn't. Remove the node from its current place in the maps.
9351 if (!RemoveNodeFromCSEMaps(N))
9352 InsertPos = nullptr;
9354 // Now we update the operands.
9355 for (unsigned i = 0; i != NumOps; ++i)
9356 if (N->OperandList[i] != Ops[i])
9357 N->OperandList[i].set(Ops[i]);
9359 updateDivergence(N);
9360 // If this gets put into a CSE map, add it.
9361 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9365 /// DropOperands - Release the operands and set this node to have
9367 void SDNode::DropOperands() {
9368 // Unlike the code in MorphNodeTo that does this, we don't need to
9369 // watch for dead nodes here.
9370 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9376 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9377 ArrayRef<MachineMemOperand *> NewMemRefs) {
9378 if (NewMemRefs.empty()) {
9383 // Check if we can avoid allocating by storing a single reference directly.
9384 if (NewMemRefs.size() == 1) {
9385 N->MemRefs = NewMemRefs[0];
9390 MachineMemOperand **MemRefsBuffer =
9391 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9392 llvm::copy(NewMemRefs, MemRefsBuffer);
9393 N->MemRefs = MemRefsBuffer;
9394 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9397 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9402 SDVTList VTs = getVTList(VT);
9403 return SelectNodeTo(N, MachineOpc, VTs, None);
9406 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9407 EVT VT, SDValue Op1) {
9408 SDVTList VTs = getVTList(VT);
9409 SDValue Ops[] = { Op1 };
9410 return SelectNodeTo(N, MachineOpc, VTs, Ops);
9413 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9414 EVT VT, SDValue Op1,
9416 SDVTList VTs = getVTList(VT);
9417 SDValue Ops[] = { Op1, Op2 };
9418 return SelectNodeTo(N, MachineOpc, VTs, Ops);
9421 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9422 EVT VT, SDValue Op1,
9423 SDValue Op2, SDValue Op3) {
9424 SDVTList VTs = getVTList(VT);
9425 SDValue Ops[] = { Op1, Op2, Op3 };
9426 return SelectNodeTo(N, MachineOpc, VTs, Ops);
9429 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9430 EVT VT, ArrayRef<SDValue> Ops) {
9431 SDVTList VTs = getVTList(VT);
9432 return SelectNodeTo(N, MachineOpc, VTs, Ops);
9435 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9436 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9437 SDVTList VTs = getVTList(VT1, VT2);
9438 return SelectNodeTo(N, MachineOpc, VTs, Ops);
9441 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9443 SDVTList VTs = getVTList(VT1, VT2);
9444 return SelectNodeTo(N, MachineOpc, VTs, None);
9447 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9448 EVT VT1, EVT VT2, EVT VT3,
9449 ArrayRef<SDValue> Ops) {
9450 SDVTList VTs = getVTList(VT1, VT2, VT3);
9451 return SelectNodeTo(N, MachineOpc, VTs, Ops);
9454 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9456 SDValue Op1, SDValue Op2) {
9457 SDVTList VTs = getVTList(VT1, VT2);
9458 SDValue Ops[] = { Op1, Op2 };
9459 return SelectNodeTo(N, MachineOpc, VTs, Ops);
9462 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9463 SDVTList VTs,ArrayRef<SDValue> Ops) {
9464 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9465 // Reset the NodeID to -1.
9468 ReplaceAllUsesWith(N, New);
9474 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9475 /// the line number information on the merged node since it is not possible to
9476 /// preserve the information that operation is associated with multiple lines.
9477 /// This will make the debugger working better at -O0, were there is a higher
9478 /// probability having other instructions associated with that line.
9480 /// For IROrder, we keep the smaller of the two
9481 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9482 DebugLoc NLoc = N->getDebugLoc();
9483 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9484 N->setDebugLoc(DebugLoc());
9486 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9487 N->setIROrder(Order);
9491 /// MorphNodeTo - This *mutates* the specified node to have the specified
9492 /// return type, opcode, and operands.
9494 /// Note that MorphNodeTo returns the resultant node. If there is already a
9495 /// node of the specified opcode and operands, it returns that node instead of
9496 /// the current one. Note that the SDLoc need not be the same.
9498 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9499 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9500 /// node, and because it doesn't require CSE recalculation for any of
9501 /// the node's users.
9503 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9504 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9505 /// the legalizer which maintain worklists that would need to be updated when
9506 /// deleting things.
9507 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9508 SDVTList VTs, ArrayRef<SDValue> Ops) {
9509 // If an identical node already exists, use it.
9511 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9512 FoldingSetNodeID ID;
9513 AddNodeIDNode(ID, Opc, VTs, Ops);
9514 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9515 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9518 if (!RemoveNodeFromCSEMaps(N))
9521 // Start the morphing.
9523 N->ValueList = VTs.VTs;
9524 N->NumValues = VTs.NumVTs;
9526 // Clear the operands list, updating used nodes to remove this from their
9527 // use list. Keep track of any operands that become dead as a result.
9528 SmallPtrSet<SDNode*, 16> DeadNodeSet;
9529 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9531 SDNode *Used = Use.getNode();
9533 if (Used->use_empty())
9534 DeadNodeSet.insert(Used);
9537 // For MachineNode, initialize the memory references information.
9538 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9541 // Swap for an appropriately sized array from the recycler.
9543 createOperands(N, Ops);
9545 // Delete any nodes that are still dead after adding the uses for the
9547 if (!DeadNodeSet.empty()) {
9548 SmallVector<SDNode *, 16> DeadNodes;
9549 for (SDNode *N : DeadNodeSet)
9551 DeadNodes.push_back(N);
9552 RemoveDeadNodes(DeadNodes);
9556 CSEMap.InsertNode(N, IP); // Memoize the new node.
9560 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9561 unsigned OrigOpc = Node->getOpcode();
9565 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9566 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
9567 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9568 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
9569 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9570 #include "llvm/IR/ConstrainedOps.def"
9573 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9575 // We're taking this node out of the chain, so we need to re-link things.
9576 SDValue InputChain = Node->getOperand(0);
9577 SDValue OutputChain = SDValue(Node, 1);
9578 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9580 SmallVector<SDValue, 3> Ops;
9581 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9582 Ops.push_back(Node->getOperand(i));
9584 SDVTList VTs = getVTList(Node->getValueType(0));
9585 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9587 // MorphNodeTo can operate in two ways: if an existing node with the
9588 // specified operands exists, it can just return it. Otherwise, it
9589 // updates the node in place to have the requested operands.
9591 // If we updated the node in place, reset the node ID. To the isel,
9592 // this should be just like a newly allocated machine node.
9595 ReplaceAllUsesWith(Node, Res);
9596 RemoveDeadNode(Node);
9602 /// getMachineNode - These are used for target selectors to create a new node
9603 /// with specified return type(s), MachineInstr opcode, and operands.
9605 /// Note that getMachineNode returns the resultant node. If there is already a
9606 /// node of the specified opcode and operands, it returns that node instead of
9607 /// the current one.
9608 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9610 SDVTList VTs = getVTList(VT);
9611 return getMachineNode(Opcode, dl, VTs, None);
9614 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9615 EVT VT, SDValue Op1) {
9616 SDVTList VTs = getVTList(VT);
9617 SDValue Ops[] = { Op1 };
9618 return getMachineNode(Opcode, dl, VTs, Ops);
9621 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9622 EVT VT, SDValue Op1, SDValue Op2) {
9623 SDVTList VTs = getVTList(VT);
9624 SDValue Ops[] = { Op1, Op2 };
9625 return getMachineNode(Opcode, dl, VTs, Ops);
9628 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9629 EVT VT, SDValue Op1, SDValue Op2,
9631 SDVTList VTs = getVTList(VT);
9632 SDValue Ops[] = { Op1, Op2, Op3 };
9633 return getMachineNode(Opcode, dl, VTs, Ops);
9636 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9637 EVT VT, ArrayRef<SDValue> Ops) {
9638 SDVTList VTs = getVTList(VT);
9639 return getMachineNode(Opcode, dl, VTs, Ops);
9642 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9643 EVT VT1, EVT VT2, SDValue Op1,
9645 SDVTList VTs = getVTList(VT1, VT2);
9646 SDValue Ops[] = { Op1, Op2 };
9647 return getMachineNode(Opcode, dl, VTs, Ops);
9650 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9651 EVT VT1, EVT VT2, SDValue Op1,
9652 SDValue Op2, SDValue Op3) {
9653 SDVTList VTs = getVTList(VT1, VT2);
9654 SDValue Ops[] = { Op1, Op2, Op3 };
9655 return getMachineNode(Opcode, dl, VTs, Ops);
9658 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9660 ArrayRef<SDValue> Ops) {
9661 SDVTList VTs = getVTList(VT1, VT2);
9662 return getMachineNode(Opcode, dl, VTs, Ops);
9665 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9666 EVT VT1, EVT VT2, EVT VT3,
9667 SDValue Op1, SDValue Op2) {
9668 SDVTList VTs = getVTList(VT1, VT2, VT3);
9669 SDValue Ops[] = { Op1, Op2 };
9670 return getMachineNode(Opcode, dl, VTs, Ops);
9673 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9674 EVT VT1, EVT VT2, EVT VT3,
9675 SDValue Op1, SDValue Op2,
9677 SDVTList VTs = getVTList(VT1, VT2, VT3);
9678 SDValue Ops[] = { Op1, Op2, Op3 };
9679 return getMachineNode(Opcode, dl, VTs, Ops);
9682 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9683 EVT VT1, EVT VT2, EVT VT3,
9684 ArrayRef<SDValue> Ops) {
9685 SDVTList VTs = getVTList(VT1, VT2, VT3);
9686 return getMachineNode(Opcode, dl, VTs, Ops);
9689 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9690 ArrayRef<EVT> ResultTys,
9691 ArrayRef<SDValue> Ops) {
9692 SDVTList VTs = getVTList(ResultTys);
9693 return getMachineNode(Opcode, dl, VTs, Ops);
9696 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9698 ArrayRef<SDValue> Ops) {
9699 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9704 FoldingSetNodeID ID;
9705 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9707 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9708 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9712 // Allocate a new MachineSDNode.
9713 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9714 createOperands(N, Ops);
9717 CSEMap.InsertNode(N, IP);
9720 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9724 /// getTargetExtractSubreg - A convenience function for creating
9725 /// TargetOpcode::EXTRACT_SUBREG nodes.
9726 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9728 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9729 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9730 VT, Operand, SRIdxVal);
9731 return SDValue(Subreg, 0);
9734 /// getTargetInsertSubreg - A convenience function for creating
9735 /// TargetOpcode::INSERT_SUBREG nodes.
9736 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9737 SDValue Operand, SDValue Subreg) {
9738 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9739 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9740 VT, Operand, Subreg, SRIdxVal);
9741 return SDValue(Result, 0);
9744 /// getNodeIfExists - Get the specified node if it's already available, or
9745 /// else return NULL.
9746 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9747 ArrayRef<SDValue> Ops) {
9750 Flags = Inserter->getFlags();
9751 return getNodeIfExists(Opcode, VTList, Ops, Flags);
9754 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9755 ArrayRef<SDValue> Ops,
9756 const SDNodeFlags Flags) {
9757 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9758 FoldingSetNodeID ID;
9759 AddNodeIDNode(ID, Opcode, VTList, Ops);
9761 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9762 E->intersectFlagsWith(Flags);
9769 /// doesNodeExist - Check if a node exists without modifying its flags.
9770 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9771 ArrayRef<SDValue> Ops) {
9772 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9773 FoldingSetNodeID ID;
9774 AddNodeIDNode(ID, Opcode, VTList, Ops);
9776 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9782 /// getDbgValue - Creates a SDDbgValue node.
9785 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9786 SDNode *N, unsigned R, bool IsIndirect,
9787 const DebugLoc &DL, unsigned O) {
9788 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9789 "Expected inlined-at fields to agree");
9790 return new (DbgInfo->getAlloc())
9791 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9792 {}, IsIndirect, DL, O,
9793 /*IsVariadic=*/false);
9797 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9800 const DebugLoc &DL, unsigned O) {
9801 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9802 "Expected inlined-at fields to agree");
9803 return new (DbgInfo->getAlloc())
9804 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9805 /*IsIndirect=*/false, DL, O,
9806 /*IsVariadic=*/false);
9810 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9811 DIExpression *Expr, unsigned FI,
9815 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9816 "Expected inlined-at fields to agree");
9817 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9820 /// FrameIndex with dependencies
9821 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9822 DIExpression *Expr, unsigned FI,
9823 ArrayRef<SDNode *> Dependencies,
9827 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9828 "Expected inlined-at fields to agree");
9829 return new (DbgInfo->getAlloc())
9830 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9831 Dependencies, IsIndirect, DL, O,
9832 /*IsVariadic=*/false);
9836 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9837 unsigned VReg, bool IsIndirect,
9838 const DebugLoc &DL, unsigned O) {
9839 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9840 "Expected inlined-at fields to agree");
9841 return new (DbgInfo->getAlloc())
9842 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9843 {}, IsIndirect, DL, O,
9844 /*IsVariadic=*/false);
9847 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9848 ArrayRef<SDDbgOperand> Locs,
9849 ArrayRef<SDNode *> Dependencies,
9850 bool IsIndirect, const DebugLoc &DL,
9851 unsigned O, bool IsVariadic) {
9852 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9853 "Expected inlined-at fields to agree");
9854 return new (DbgInfo->getAlloc())
9855 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9859 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9860 unsigned OffsetInBits, unsigned SizeInBits,
9861 bool InvalidateDbg) {
9862 SDNode *FromNode = From.getNode();
9863 SDNode *ToNode = To.getNode();
9864 assert(FromNode && ToNode && "Can't modify dbg values");
9867 // TODO: assert(From != To && "Redundant dbg value transfer");
9868 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9869 if (From == To || FromNode == ToNode)
9872 if (!FromNode->getHasDebugValue())
9875 SDDbgOperand FromLocOp =
9876 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9877 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9879 SmallVector<SDDbgValue *, 2> ClonedDVs;
9880 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9881 if (Dbg->isInvalidated())
9884 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9886 // Create a new location ops vector that is equal to the old vector, but
9887 // with each instance of FromLocOp replaced with ToLocOp.
9888 bool Changed = false;
9889 auto NewLocOps = Dbg->copyLocationOps();
9891 NewLocOps.begin(), NewLocOps.end(),
9892 [&Changed, FromLocOp](const SDDbgOperand &Op) {
9893 bool Match = Op == FromLocOp;
9898 // Ignore this SDDbgValue if we didn't find a matching location.
9902 DIVariable *Var = Dbg->getVariable();
9903 auto *Expr = Dbg->getExpression();
9904 // If a fragment is requested, update the expression.
9906 // When splitting a larger (e.g., sign-extended) value whose
9907 // lower bits are described with an SDDbgValue, do not attempt
9908 // to transfer the SDDbgValue to the upper bits.
9909 if (auto FI = Expr->getFragmentInfo())
9910 if (OffsetInBits + SizeInBits > FI->SizeInBits)
9912 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9919 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9920 // Clone the SDDbgValue and move it to To.
9921 SDDbgValue *Clone = getDbgValueList(
9922 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9923 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9925 ClonedDVs.push_back(Clone);
9927 if (InvalidateDbg) {
9928 // Invalidate value and indicate the SDDbgValue should not be emitted.
9929 Dbg->setIsInvalidated();
9930 Dbg->setIsEmitted();
9934 for (SDDbgValue *Dbg : ClonedDVs) {
9935 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9936 "Transferred DbgValues should depend on the new SDNode");
9937 AddDbgValue(Dbg, false);
9941 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9942 if (!N.getHasDebugValue())
9945 SmallVector<SDDbgValue *, 2> ClonedDVs;
9946 for (auto *DV : GetDbgValues(&N)) {
9947 if (DV->isInvalidated())
9949 switch (N.getOpcode()) {
9953 SDValue N0 = N.getOperand(0);
9954 SDValue N1 = N.getOperand(1);
9955 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9956 isConstantIntBuildVectorOrConstantInt(N1)) {
9957 uint64_t Offset = N.getConstantOperandVal(1);
9959 // Rewrite an ADD constant node into a DIExpression. Since we are
9960 // performing arithmetic to compute the variable's *value* in the
9961 // DIExpression, we need to mark the expression with a
9962 // DW_OP_stack_value.
9963 auto *DIExpr = DV->getExpression();
9964 auto NewLocOps = DV->copyLocationOps();
9965 bool Changed = false;
9966 for (size_t i = 0; i < NewLocOps.size(); ++i) {
9967 // We're not given a ResNo to compare against because the whole
9968 // node is going away. We know that any ISD::ADD only has one
9969 // result, so we can assume any node match is using the result.
9970 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9971 NewLocOps[i].getSDNode() != &N)
9973 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9974 SmallVector<uint64_t, 3> ExprOps;
9975 DIExpression::appendOffset(ExprOps, Offset);
9976 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9980 assert(Changed && "Salvage target doesn't use N");
9982 auto AdditionalDependencies = DV->getAdditionalDependencies();
9983 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9984 NewLocOps, AdditionalDependencies,
9985 DV->isIndirect(), DV->getDebugLoc(),
9986 DV->getOrder(), DV->isVariadic());
9987 ClonedDVs.push_back(Clone);
9988 DV->setIsInvalidated();
9990 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9991 N0.getNode()->dumprFull(this);
9992 dbgs() << " into " << *DIExpr << '\n');
9997 for (SDDbgValue *Dbg : ClonedDVs) {
9998 assert(!Dbg->getSDNodes().empty() &&
9999 "Salvaged DbgValue should depend on a new SDNode");
10000 AddDbgValue(Dbg, false);
10004 /// Creates a SDDbgLabel node.
10005 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
10006 const DebugLoc &DL, unsigned O) {
10007 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
10008 "Expected inlined-at fields to agree");
10009 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
10014 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
10015 /// pointed to by a use iterator is deleted, increment the use iterator
10016 /// so that it doesn't dangle.
10018 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
10019 SDNode::use_iterator &UI;
10020 SDNode::use_iterator &UE;
10022 void NodeDeleted(SDNode *N, SDNode *E) override {
10023 // Increment the iterator as needed.
10024 while (UI != UE && N == *UI)
10029 RAUWUpdateListener(SelectionDAG &d,
10030 SDNode::use_iterator &ui,
10031 SDNode::use_iterator &ue)
10032 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
10035 } // end anonymous namespace
10037 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10038 /// This can cause recursive merging of nodes in the DAG.
10040 /// This version assumes From has a single result value.
10042 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10043 SDNode *From = FromN.getNode();
10044 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10045 "Cannot replace with this method!");
10046 assert(From != To.getNode() && "Cannot replace uses of with self");
10048 // Preserve Debug Values
10049 transferDbgValues(FromN, To);
10051 // Iterate over all the existing uses of From. New uses will be added
10052 // to the beginning of the use list, which we avoid visiting.
10053 // This specifically avoids visiting uses of From that arise while the
10054 // replacement is happening, because any such uses would be the result
10055 // of CSE: If an existing node looks like From after one of its operands
10056 // is replaced by To, we don't want to replace of all its users with To
10057 // too. See PR3018 for more info.
10058 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10059 RAUWUpdateListener Listener(*this, UI, UE);
10061 SDNode *User = *UI;
10063 // This node is about to morph, remove its old self from the CSE maps.
10064 RemoveNodeFromCSEMaps(User);
10066 // A user can appear in a use list multiple times, and when this
10067 // happens the uses are usually next to each other in the list.
10068 // To help reduce the number of CSE recomputations, process all
10069 // the uses of this user that we can find this way.
10071 SDUse &Use = UI.getUse();
10074 if (To->isDivergent() != From->isDivergent())
10075 updateDivergence(User);
10076 } while (UI != UE && *UI == User);
10077 // Now that we have modified User, add it back to the CSE maps. If it
10078 // already exists there, recursively merge the results together.
10079 AddModifiedNodeToCSEMaps(User);
10082 // If we just RAUW'd the root, take note.
10083 if (FromN == getRoot())
10087 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10088 /// This can cause recursive merging of nodes in the DAG.
10090 /// This version assumes that for each value of From, there is a
10091 /// corresponding value in To in the same position with the same type.
10093 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10095 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10096 assert((!From->hasAnyUseOfValue(i) ||
10097 From->getValueType(i) == To->getValueType(i)) &&
10098 "Cannot use this version of ReplaceAllUsesWith!");
10101 // Handle the trivial case.
10105 // Preserve Debug Info. Only do this if there's a use.
10106 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10107 if (From->hasAnyUseOfValue(i)) {
10108 assert((i < To->getNumValues()) && "Invalid To location");
10109 transferDbgValues(SDValue(From, i), SDValue(To, i));
10112 // Iterate over just the existing users of From. See the comments in
10113 // the ReplaceAllUsesWith above.
10114 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10115 RAUWUpdateListener Listener(*this, UI, UE);
10117 SDNode *User = *UI;
10119 // This node is about to morph, remove its old self from the CSE maps.
10120 RemoveNodeFromCSEMaps(User);
10122 // A user can appear in a use list multiple times, and when this
10123 // happens the uses are usually next to each other in the list.
10124 // To help reduce the number of CSE recomputations, process all
10125 // the uses of this user that we can find this way.
10127 SDUse &Use = UI.getUse();
10130 if (To->isDivergent() != From->isDivergent())
10131 updateDivergence(User);
10132 } while (UI != UE && *UI == User);
10134 // Now that we have modified User, add it back to the CSE maps. If it
10135 // already exists there, recursively merge the results together.
10136 AddModifiedNodeToCSEMaps(User);
10139 // If we just RAUW'd the root, take note.
10140 if (From == getRoot().getNode())
10141 setRoot(SDValue(To, getRoot().getResNo()));
10144 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10145 /// This can cause recursive merging of nodes in the DAG.
10147 /// This version can replace From with any result values. To must match the
10148 /// number and types of values returned by From.
10149 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10150 if (From->getNumValues() == 1) // Handle the simple case efficiently.
10151 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10153 // Preserve Debug Info.
10154 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10155 transferDbgValues(SDValue(From, i), To[i]);
10157 // Iterate over just the existing users of From. See the comments in
10158 // the ReplaceAllUsesWith above.
10159 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10160 RAUWUpdateListener Listener(*this, UI, UE);
10162 SDNode *User = *UI;
10164 // This node is about to morph, remove its old self from the CSE maps.
10165 RemoveNodeFromCSEMaps(User);
10167 // A user can appear in a use list multiple times, and when this happens the
10168 // uses are usually next to each other in the list. To help reduce the
10169 // number of CSE and divergence recomputations, process all the uses of this
10170 // user that we can find this way.
10171 bool To_IsDivergent = false;
10173 SDUse &Use = UI.getUse();
10174 const SDValue &ToOp = To[Use.getResNo()];
10177 To_IsDivergent |= ToOp->isDivergent();
10178 } while (UI != UE && *UI == User);
10180 if (To_IsDivergent != From->isDivergent())
10181 updateDivergence(User);
10183 // Now that we have modified User, add it back to the CSE maps. If it
10184 // already exists there, recursively merge the results together.
10185 AddModifiedNodeToCSEMaps(User);
10188 // If we just RAUW'd the root, take note.
10189 if (From == getRoot().getNode())
10190 setRoot(SDValue(To[getRoot().getResNo()]));
10193 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10194 /// uses of other values produced by From.getNode() alone. The Deleted
10195 /// vector is handled the same way as for ReplaceAllUsesWith.
10196 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10197 // Handle the really simple, really trivial case efficiently.
10198 if (From == To) return;
10200 // Handle the simple, trivial, case efficiently.
10201 if (From.getNode()->getNumValues() == 1) {
10202 ReplaceAllUsesWith(From, To);
10206 // Preserve Debug Info.
10207 transferDbgValues(From, To);
10209 // Iterate over just the existing users of From. See the comments in
10210 // the ReplaceAllUsesWith above.
10211 SDNode::use_iterator UI = From.getNode()->use_begin(),
10212 UE = From.getNode()->use_end();
10213 RAUWUpdateListener Listener(*this, UI, UE);
10215 SDNode *User = *UI;
10216 bool UserRemovedFromCSEMaps = false;
10218 // A user can appear in a use list multiple times, and when this
10219 // happens the uses are usually next to each other in the list.
10220 // To help reduce the number of CSE recomputations, process all
10221 // the uses of this user that we can find this way.
10223 SDUse &Use = UI.getUse();
10225 // Skip uses of different values from the same node.
10226 if (Use.getResNo() != From.getResNo()) {
10231 // If this node hasn't been modified yet, it's still in the CSE maps,
10232 // so remove its old self from the CSE maps.
10233 if (!UserRemovedFromCSEMaps) {
10234 RemoveNodeFromCSEMaps(User);
10235 UserRemovedFromCSEMaps = true;
10240 if (To->isDivergent() != From->isDivergent())
10241 updateDivergence(User);
10242 } while (UI != UE && *UI == User);
10243 // We are iterating over all uses of the From node, so if a use
10244 // doesn't use the specific value, no changes are made.
10245 if (!UserRemovedFromCSEMaps)
10248 // Now that we have modified User, add it back to the CSE maps. If it
10249 // already exists there, recursively merge the results together.
10250 AddModifiedNodeToCSEMaps(User);
10253 // If we just RAUW'd the root, take note.
10254 if (From == getRoot())
10260 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10261 /// to record information about a use.
10268 /// operator< - Sort Memos by User.
10269 bool operator<(const UseMemo &L, const UseMemo &R) {
10270 return (intptr_t)L.User < (intptr_t)R.User;
10273 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10274 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10275 /// the node already has been taken care of recursively.
10276 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10277 SmallVector<UseMemo, 4> &Uses;
10279 void NodeDeleted(SDNode *N, SDNode *E) override {
10280 for (UseMemo &Memo : Uses)
10281 if (Memo.User == N)
10282 Memo.User = nullptr;
10286 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10287 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10290 } // end anonymous namespace
10292 bool SelectionDAG::calculateDivergence(SDNode *N) {
10293 if (TLI->isSDNodeAlwaysUniform(N)) {
10294 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10295 "Conflicting divergence information!");
10298 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10300 for (const auto &Op : N->ops()) {
10301 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10307 void SelectionDAG::updateDivergence(SDNode *N) {
10308 SmallVector<SDNode *, 16> Worklist(1, N);
10310 N = Worklist.pop_back_val();
10311 bool IsDivergent = calculateDivergence(N);
10312 if (N->SDNodeBits.IsDivergent != IsDivergent) {
10313 N->SDNodeBits.IsDivergent = IsDivergent;
10314 llvm::append_range(Worklist, N->uses());
10316 } while (!Worklist.empty());
10319 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10320 DenseMap<SDNode *, unsigned> Degree;
10321 Order.reserve(AllNodes.size());
10322 for (auto &N : allnodes()) {
10323 unsigned NOps = N.getNumOperands();
10326 Order.push_back(&N);
10328 for (size_t I = 0; I != Order.size(); ++I) {
10329 SDNode *N = Order[I];
10330 for (auto *U : N->uses()) {
10331 unsigned &UnsortedOps = Degree[U];
10332 if (0 == --UnsortedOps)
10333 Order.push_back(U);
10339 void SelectionDAG::VerifyDAGDivergence() {
10340 std::vector<SDNode *> TopoOrder;
10341 CreateTopologicalOrder(TopoOrder);
10342 for (auto *N : TopoOrder) {
10343 assert(calculateDivergence(N) == N->isDivergent() &&
10344 "Divergence bit inconsistency detected");
10349 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10350 /// uses of other values produced by From.getNode() alone. The same value
10351 /// may appear in both the From and To list. The Deleted vector is
10352 /// handled the same way as for ReplaceAllUsesWith.
10353 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10356 // Handle the simple, trivial case efficiently.
10358 return ReplaceAllUsesOfValueWith(*From, *To);
10360 transferDbgValues(*From, *To);
10362 // Read up all the uses and make records of them. This helps
10363 // processing new uses that are introduced during the
10364 // replacement process.
10365 SmallVector<UseMemo, 4> Uses;
10366 for (unsigned i = 0; i != Num; ++i) {
10367 unsigned FromResNo = From[i].getResNo();
10368 SDNode *FromNode = From[i].getNode();
10369 for (SDNode::use_iterator UI = FromNode->use_begin(),
10370 E = FromNode->use_end(); UI != E; ++UI) {
10371 SDUse &Use = UI.getUse();
10372 if (Use.getResNo() == FromResNo) {
10373 UseMemo Memo = { *UI, i, &Use };
10374 Uses.push_back(Memo);
10379 // Sort the uses, so that all the uses from a given User are together.
10381 RAUOVWUpdateListener Listener(*this, Uses);
10383 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10384 UseIndex != UseIndexEnd; ) {
10385 // We know that this user uses some value of From. If it is the right
10386 // value, update it.
10387 SDNode *User = Uses[UseIndex].User;
10388 // If the node has been deleted by recursive CSE updates when updating
10389 // another node, then just skip this entry.
10390 if (User == nullptr) {
10395 // This node is about to morph, remove its old self from the CSE maps.
10396 RemoveNodeFromCSEMaps(User);
10398 // The Uses array is sorted, so all the uses for a given User
10399 // are next to each other in the list.
10400 // To help reduce the number of CSE recomputations, process all
10401 // the uses of this user that we can find this way.
10403 unsigned i = Uses[UseIndex].Index;
10404 SDUse &Use = *Uses[UseIndex].Use;
10408 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10410 // Now that we have modified User, add it back to the CSE maps. If it
10411 // already exists there, recursively merge the results together.
10412 AddModifiedNodeToCSEMaps(User);
10416 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10417 /// based on their topological order. It returns the maximum id and a vector
10418 /// of the SDNodes* in assigned order by reference.
10419 unsigned SelectionDAG::AssignTopologicalOrder() {
10420 unsigned DAGSize = 0;
10422 // SortedPos tracks the progress of the algorithm. Nodes before it are
10423 // sorted, nodes after it are unsorted. When the algorithm completes
10424 // it is at the end of the list.
10425 allnodes_iterator SortedPos = allnodes_begin();
10427 // Visit all the nodes. Move nodes with no operands to the front of
10428 // the list immediately. Annotate nodes that do have operands with their
10429 // operand count. Before we do this, the Node Id fields of the nodes
10430 // may contain arbitrary values. After, the Node Id fields for nodes
10431 // before SortedPos will contain the topological sort index, and the
10432 // Node Id fields for nodes At SortedPos and after will contain the
10433 // count of outstanding operands.
10434 for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10435 checkForCycles(&N, this);
10436 unsigned Degree = N.getNumOperands();
10438 // A node with no uses, add it to the result array immediately.
10439 N.setNodeId(DAGSize++);
10440 allnodes_iterator Q(&N);
10441 if (Q != SortedPos)
10442 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10443 assert(SortedPos != AllNodes.end() && "Overran node list");
10446 // Temporarily use the Node Id as scratch space for the degree count.
10447 N.setNodeId(Degree);
10451 // Visit all the nodes. As we iterate, move nodes into sorted order,
10452 // such that by the time the end is reached all nodes will be sorted.
10453 for (SDNode &Node : allnodes()) {
10455 checkForCycles(N, this);
10456 // N is in sorted position, so all its uses have one less operand
10457 // that needs to be sorted.
10458 for (SDNode *P : N->uses()) {
10459 unsigned Degree = P->getNodeId();
10460 assert(Degree != 0 && "Invalid node degree");
10463 // All of P's operands are sorted, so P may sorted now.
10464 P->setNodeId(DAGSize++);
10465 if (P->getIterator() != SortedPos)
10466 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10467 assert(SortedPos != AllNodes.end() && "Overran node list");
10470 // Update P's outstanding operand count.
10471 P->setNodeId(Degree);
10474 if (Node.getIterator() == SortedPos) {
10476 allnodes_iterator I(N);
10478 dbgs() << "Overran sorted position:\n";
10479 S->dumprFull(this); dbgs() << "\n";
10480 dbgs() << "Checking if this is due to cycles\n";
10481 checkForCycles(this, true);
10483 llvm_unreachable(nullptr);
10487 assert(SortedPos == AllNodes.end() &&
10488 "Topological sort incomplete!");
10489 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10490 "First node in topological sort is not the entry token!");
10491 assert(AllNodes.front().getNodeId() == 0 &&
10492 "First node in topological sort has non-zero id!");
10493 assert(AllNodes.front().getNumOperands() == 0 &&
10494 "First node in topological sort has operands!");
10495 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10496 "Last node in topologic sort has unexpected id!");
10497 assert(AllNodes.back().use_empty() &&
10498 "Last node in topologic sort has users!");
10499 assert(DAGSize == allnodes_size() && "Node count mismatch!");
10503 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10504 /// value is produced by SD.
10505 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10506 for (SDNode *SD : DB->getSDNodes()) {
10509 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10510 SD->setHasDebugValue(true);
10512 DbgInfo->add(DB, isParameter);
10515 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10517 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10518 SDValue NewMemOpChain) {
10519 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10520 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10521 // The new memory operation must have the same position as the old load in
10522 // terms of memory dependency. Create a TokenFactor for the old load and new
10523 // memory operation and update uses of the old load's output chain to use that
10525 if (OldChain == NewMemOpChain || OldChain.use_empty())
10526 return NewMemOpChain;
10528 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10529 OldChain, NewMemOpChain);
10530 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10531 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10532 return TokenFactor;
10535 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10536 SDValue NewMemOp) {
10537 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10538 SDValue OldChain = SDValue(OldLoad, 1);
10539 SDValue NewMemOpChain = NewMemOp.getValue(1);
10540 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10543 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10544 Function **OutFunction) {
10545 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10547 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10548 auto *Module = MF->getFunction().getParent();
10549 auto *Function = Module->getFunction(Symbol);
10551 if (OutFunction != nullptr)
10552 *OutFunction = Function;
10554 if (Function != nullptr) {
10555 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10556 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10559 std::string ErrorStr;
10560 raw_string_ostream ErrorFormatter(ErrorStr);
10561 ErrorFormatter << "Undefined external symbol ";
10562 ErrorFormatter << '"' << Symbol << '"';
10563 report_fatal_error(Twine(ErrorFormatter.str()));
10566 //===----------------------------------------------------------------------===//
10568 //===----------------------------------------------------------------------===//
10570 bool llvm::isNullConstant(SDValue V) {
10571 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10572 return Const != nullptr && Const->isZero();
10575 bool llvm::isNullFPConstant(SDValue V) {
10576 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10577 return Const != nullptr && Const->isZero() && !Const->isNegative();
10580 bool llvm::isAllOnesConstant(SDValue V) {
10581 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10582 return Const != nullptr && Const->isAllOnes();
10585 bool llvm::isOneConstant(SDValue V) {
10586 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10587 return Const != nullptr && Const->isOne();
10590 bool llvm::isMinSignedConstant(SDValue V) {
10591 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10592 return Const != nullptr && Const->isMinSignedValue();
10595 SDValue llvm::peekThroughBitcasts(SDValue V) {
10596 while (V.getOpcode() == ISD::BITCAST)
10597 V = V.getOperand(0);
10601 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10602 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10603 V = V.getOperand(0);
10607 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10608 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10609 V = V.getOperand(0);
10613 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10614 if (V.getOpcode() != ISD::XOR)
10616 V = peekThroughBitcasts(V.getOperand(1));
10617 unsigned NumBits = V.getScalarValueSizeInBits();
10618 ConstantSDNode *C =
10619 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10620 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10623 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10624 bool AllowTruncation) {
10625 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10628 // SplatVectors can truncate their operands. Ignore that case here unless
10629 // AllowTruncation is set.
10630 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10631 EVT VecEltVT = N->getValueType(0).getVectorElementType();
10632 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10633 EVT CVT = CN->getValueType(0);
10634 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10635 if (AllowTruncation || CVT == VecEltVT)
10640 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10641 BitVector UndefElements;
10642 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10644 // BuildVectors can truncate their operands. Ignore that case here unless
10645 // AllowTruncation is set.
10646 if (CN && (UndefElements.none() || AllowUndefs)) {
10647 EVT CVT = CN->getValueType(0);
10648 EVT NSVT = N.getValueType().getScalarType();
10649 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10650 if (AllowTruncation || (CVT == NSVT))
10658 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10660 bool AllowTruncation) {
10661 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10664 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10665 BitVector UndefElements;
10666 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10668 // BuildVectors can truncate their operands. Ignore that case here unless
10669 // AllowTruncation is set.
10670 if (CN && (UndefElements.none() || AllowUndefs)) {
10671 EVT CVT = CN->getValueType(0);
10672 EVT NSVT = N.getValueType().getScalarType();
10673 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10674 if (AllowTruncation || (CVT == NSVT))
10682 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10683 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10686 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10687 BitVector UndefElements;
10688 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10689 if (CN && (UndefElements.none() || AllowUndefs))
10693 if (N.getOpcode() == ISD::SPLAT_VECTOR)
10694 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10700 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10701 const APInt &DemandedElts,
10702 bool AllowUndefs) {
10703 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10706 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10707 BitVector UndefElements;
10708 ConstantFPSDNode *CN =
10709 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10710 if (CN && (UndefElements.none() || AllowUndefs))
10717 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10718 // TODO: may want to use peekThroughBitcast() here.
10719 ConstantSDNode *C =
10720 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10721 return C && C->isZero();
10724 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10725 ConstantSDNode *C =
10726 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10727 return C && C->isOne();
10730 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10731 N = peekThroughBitcasts(N);
10732 unsigned BitWidth = N.getScalarValueSizeInBits();
10733 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10734 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10737 HandleSDNode::~HandleSDNode() {
10741 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10742 const DebugLoc &DL,
10743 const GlobalValue *GA, EVT VT,
10744 int64_t o, unsigned TF)
10745 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10749 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10750 EVT VT, unsigned SrcAS,
10752 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10753 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10755 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10756 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10757 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10758 MemSDNodeBits.IsVolatile = MMO->isVolatile();
10759 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10760 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10761 MemSDNodeBits.IsInvariant = MMO->isInvariant();
10763 // We check here that the size of the memory operand fits within the size of
10764 // the MMO. This is because the MMO might indicate only a possible address
10765 // range instead of specifying the affected memory addresses precisely.
10766 // TODO: Make MachineMemOperands aware of scalable vectors.
10767 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10771 /// Profile - Gather unique data for the node.
10773 void SDNode::Profile(FoldingSetNodeID &ID) const {
10774 AddNodeIDNode(ID, this);
10780 std::vector<EVT> VTs;
10783 VTs.reserve(MVT::VALUETYPE_SIZE);
10784 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10785 VTs.push_back(MVT((MVT::SimpleValueType)i));
10789 } // end anonymous namespace
10791 /// getValueTypeList - Return a pointer to the specified value type.
10793 const EVT *SDNode::getValueTypeList(EVT VT) {
10794 static std::set<EVT, EVT::compareRawBits> EVTs;
10795 static EVTArray SimpleVTArray;
10796 static sys::SmartMutex<true> VTMutex;
10798 if (VT.isExtended()) {
10799 sys::SmartScopedLock<true> Lock(VTMutex);
10800 return &(*EVTs.insert(VT).first);
10802 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10803 return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
10806 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10807 /// indicated value. This method ignores uses of other values defined by this
10809 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10810 assert(Value < getNumValues() && "Bad value!");
10812 // TODO: Only iterate over uses of a given value of the node
10813 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10814 if (UI.getUse().getResNo() == Value) {
10821 // Found exactly the right number of uses?
10825 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10826 /// value. This method ignores uses of other values defined by this operation.
10827 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10828 assert(Value < getNumValues() && "Bad value!");
10830 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10831 if (UI.getUse().getResNo() == Value)
10837 /// isOnlyUserOf - Return true if this node is the only use of N.
10838 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10840 for (const SDNode *User : N->uses()) {
10850 /// Return true if the only users of N are contained in Nodes.
10851 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10853 for (const SDNode *User : N->uses()) {
10854 if (llvm::is_contained(Nodes, User))
10863 /// isOperand - Return true if this node is an operand of N.
10864 bool SDValue::isOperandOf(const SDNode *N) const {
10865 return is_contained(N->op_values(), *this);
10868 bool SDNode::isOperandOf(const SDNode *N) const {
10869 return any_of(N->op_values(),
10870 [this](SDValue Op) { return this == Op.getNode(); });
10873 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10874 /// be a chain) reaches the specified operand without crossing any
10875 /// side-effecting instructions on any chain path. In practice, this looks
10876 /// through token factors and non-volatile loads. In order to remain efficient,
10877 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10879 /// Note that we only need to examine chains when we're searching for
10880 /// side-effects; SelectionDAG requires that all side-effects are represented
10881 /// by chains, even if another operand would force a specific ordering. This
10882 /// constraint is necessary to allow transformations like splitting loads.
10883 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10884 unsigned Depth) const {
10885 if (*this == Dest) return true;
10887 // Don't search too deeply, we just want to be able to see through
10888 // TokenFactor's etc.
10889 if (Depth == 0) return false;
10891 // If this is a token factor, all inputs to the TF happen in parallel.
10892 if (getOpcode() == ISD::TokenFactor) {
10893 // First, try a shallow search.
10894 if (is_contained((*this)->ops(), Dest)) {
10895 // We found the chain we want as an operand of this TokenFactor.
10896 // Essentially, we reach the chain without side-effects if we could
10897 // serialize the TokenFactor into a simple chain of operations with
10898 // Dest as the last operation. This is automatically true if the
10899 // chain has one use: there are no other ordering constraints.
10900 // If the chain has more than one use, we give up: some other
10901 // use of Dest might force a side-effect between Dest and the current
10903 if (Dest.hasOneUse())
10906 // Next, try a deep search: check whether every operand of the TokenFactor
10908 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10909 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10913 // Loads don't have side effects, look through them.
10914 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10915 if (Ld->isUnordered())
10916 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10921 bool SDNode::hasPredecessor(const SDNode *N) const {
10922 SmallPtrSet<const SDNode *, 32> Visited;
10923 SmallVector<const SDNode *, 16> Worklist;
10924 Worklist.push_back(this);
10925 return hasPredecessorHelper(N, Visited, Worklist);
10928 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10929 this->Flags.intersectWith(Flags);
10933 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10934 ArrayRef<ISD::NodeType> CandidateBinOps,
10935 bool AllowPartials) {
10936 // The pattern must end in an extract from index 0.
10937 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10938 !isNullConstant(Extract->getOperand(1)))
10941 // Match against one of the candidate binary ops.
10942 SDValue Op = Extract->getOperand(0);
10943 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10944 return Op.getOpcode() == unsigned(BinOp);
10948 // Floating-point reductions may require relaxed constraints on the final step
10949 // of the reduction because they may reorder intermediate operations.
10950 unsigned CandidateBinOp = Op.getOpcode();
10951 if (Op.getValueType().isFloatingPoint()) {
10952 SDNodeFlags Flags = Op->getFlags();
10953 switch (CandidateBinOp) {
10955 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10959 llvm_unreachable("Unhandled FP opcode for binop reduction");
10963 // Matching failed - attempt to see if we did enough stages that a partial
10964 // reduction from a subvector is possible.
10965 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10966 if (!AllowPartials || !Op)
10968 EVT OpVT = Op.getValueType();
10969 EVT OpSVT = OpVT.getScalarType();
10970 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10971 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10973 BinOp = (ISD::NodeType)CandidateBinOp;
10974 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10975 getVectorIdxConstant(0, SDLoc(Op)));
10978 // At each stage, we're looking for something that looks like:
10979 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10980 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10981 // i32 undef, i32 undef, i32 undef, i32 undef>
10982 // %a = binop <8 x i32> %op, %s
10983 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10984 // we expect something like:
10985 // <4,5,6,7,u,u,u,u>
10986 // <2,3,u,u,u,u,u,u>
10987 // <1,u,u,u,u,u,u,u>
10988 // While a partial reduction match would be:
10989 // <2,3,u,u,u,u,u,u>
10990 // <1,u,u,u,u,u,u,u>
10991 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10993 for (unsigned i = 0; i < Stages; ++i) {
10994 unsigned MaskEnd = (1 << i);
10996 if (Op.getOpcode() != CandidateBinOp)
10997 return PartialReduction(PrevOp, MaskEnd);
10999 SDValue Op0 = Op.getOperand(0);
11000 SDValue Op1 = Op.getOperand(1);
11002 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
11006 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
11010 // The first operand of the shuffle should be the same as the other operand
11012 if (!Shuffle || Shuffle->getOperand(0) != Op)
11013 return PartialReduction(PrevOp, MaskEnd);
11015 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
11016 for (int Index = 0; Index < (int)MaskEnd; ++Index)
11017 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
11018 return PartialReduction(PrevOp, MaskEnd);
11023 // Handle subvector reductions, which tend to appear after the shuffle
11024 // reduction stages.
11025 while (Op.getOpcode() == CandidateBinOp) {
11026 unsigned NumElts = Op.getValueType().getVectorNumElements();
11027 SDValue Op0 = Op.getOperand(0);
11028 SDValue Op1 = Op.getOperand(1);
11029 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11030 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11031 Op0.getOperand(0) != Op1.getOperand(0))
11033 SDValue Src = Op0.getOperand(0);
11034 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11035 if (NumSrcElts != (2 * NumElts))
11037 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11038 Op1.getConstantOperandAPInt(1) == NumElts) &&
11039 !(Op1.getConstantOperandAPInt(1) == 0 &&
11040 Op0.getConstantOperandAPInt(1) == NumElts))
11045 BinOp = (ISD::NodeType)CandidateBinOp;
11049 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11050 assert(N->getNumValues() == 1 &&
11051 "Can't unroll a vector with multiple results!");
11053 EVT VT = N->getValueType(0);
11054 unsigned NE = VT.getVectorNumElements();
11055 EVT EltVT = VT.getVectorElementType();
11058 SmallVector<SDValue, 8> Scalars;
11059 SmallVector<SDValue, 4> Operands(N->getNumOperands());
11061 // If ResNE is 0, fully unroll the vector op.
11064 else if (NE > ResNE)
11068 for (i= 0; i != NE; ++i) {
11069 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11070 SDValue Operand = N->getOperand(j);
11071 EVT OperandVT = Operand.getValueType();
11072 if (OperandVT.isVector()) {
11073 // A vector operand; extract a single element.
11074 EVT OperandEltVT = OperandVT.getVectorElementType();
11075 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11076 Operand, getVectorIdxConstant(i, dl));
11078 // A scalar operand; just use it as is.
11079 Operands[j] = Operand;
11083 switch (N->getOpcode()) {
11085 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11090 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11097 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11098 getShiftAmountOperand(Operands[0].getValueType(),
11101 case ISD::SIGN_EXTEND_INREG: {
11102 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11103 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11105 getValueType(ExtVT)));
11110 for (; i < ResNE; ++i)
11111 Scalars.push_back(getUNDEF(EltVT));
11113 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11114 return getBuildVector(VecVT, dl, Scalars);
11117 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11118 SDNode *N, unsigned ResNE) {
11119 unsigned Opcode = N->getOpcode();
11120 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11121 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11122 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11123 "Expected an overflow opcode");
11125 EVT ResVT = N->getValueType(0);
11126 EVT OvVT = N->getValueType(1);
11127 EVT ResEltVT = ResVT.getVectorElementType();
11128 EVT OvEltVT = OvVT.getVectorElementType();
11131 // If ResNE is 0, fully unroll the vector op.
11132 unsigned NE = ResVT.getVectorNumElements();
11135 else if (NE > ResNE)
11138 SmallVector<SDValue, 8> LHSScalars;
11139 SmallVector<SDValue, 8> RHSScalars;
11140 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11141 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11143 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11144 SDVTList VTs = getVTList(ResEltVT, SVT);
11145 SmallVector<SDValue, 8> ResScalars;
11146 SmallVector<SDValue, 8> OvScalars;
11147 for (unsigned i = 0; i < NE; ++i) {
11148 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11150 getSelect(dl, OvEltVT, Res.getValue(1),
11151 getBoolConstant(true, dl, OvEltVT, ResVT),
11152 getConstant(0, dl, OvEltVT));
11154 ResScalars.push_back(Res);
11155 OvScalars.push_back(Ov);
11158 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11159 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11161 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11162 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11163 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11164 getBuildVector(NewOvVT, dl, OvScalars));
11167 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11171 if (LD->isVolatile() || Base->isVolatile())
11173 // TODO: probably too restrictive for atomics, revisit
11174 if (!LD->isSimple())
11176 if (LD->isIndexed() || Base->isIndexed())
11178 if (LD->getChain() != Base->getChain())
11180 EVT VT = LD->getValueType(0);
11181 if (VT.getSizeInBits() / 8 != Bytes)
11184 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11185 auto LocDecomp = BaseIndexOffset::match(LD, *this);
11187 int64_t Offset = 0;
11188 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11189 return (Dist * Bytes == Offset);
11193 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11194 /// if it cannot be inferred.
11195 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11196 // If this is a GlobalAddress + cst, return the alignment.
11197 const GlobalValue *GV = nullptr;
11198 int64_t GVOffset = 0;
11199 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11200 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11201 KnownBits Known(PtrWidth);
11202 llvm::computeKnownBits(GV, Known, getDataLayout());
11203 unsigned AlignBits = Known.countMinTrailingZeros();
11205 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11208 // If this is a direct reference to a stack slot, use information about the
11209 // stack slot's alignment.
11210 int FrameIdx = INT_MIN;
11211 int64_t FrameOffset = 0;
11212 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11213 FrameIdx = FI->getIndex();
11214 } else if (isBaseWithConstantOffset(Ptr) &&
11215 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11217 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11218 FrameOffset = Ptr.getConstantOperandVal(1);
11221 if (FrameIdx != INT_MIN) {
11222 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11223 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11229 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11230 /// which is split (or expanded) into two not necessarily identical pieces.
11231 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11232 // Currently all types are split in half.
11234 if (!VT.isVector())
11235 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11237 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11239 return std::make_pair(LoVT, HiVT);
11242 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11243 /// type, dependent on an enveloping VT that has been split into two identical
11244 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11245 std::pair<EVT, EVT>
11246 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11247 bool *HiIsEmpty) const {
11248 EVT EltTp = VT.getVectorElementType();
11250 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
11251 // custom VL=9 with enveloping VL=8/8 yields 8/1
11252 // custom VL=10 with enveloping VL=8/8 yields 8/2
11254 ElementCount VTNumElts = VT.getVectorElementCount();
11255 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11256 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11257 "Mixing fixed width and scalable vectors when enveloping a type");
11259 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11260 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11261 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11262 *HiIsEmpty = false;
11264 // Flag that hi type has zero storage size, but return split envelop type
11265 // (this would be easier if vector types with zero elements were allowed).
11266 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11267 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11270 return std::make_pair(LoVT, HiVT);
11273 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11275 std::pair<SDValue, SDValue>
11276 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11278 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11279 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11280 "Splitting vector with an invalid mixture of fixed and scalable "
11282 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11283 N.getValueType().getVectorMinNumElements() &&
11284 "More vector elements requested than available!");
11287 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11288 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11289 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11290 // IDX with the runtime scaling factor of the result vector type. For
11291 // fixed-width result vectors, that runtime scaling factor is 1.
11292 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11293 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11294 return std::make_pair(Lo, Hi);
11297 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11299 // Split the vector length parameter.
11300 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11301 EVT VT = N.getValueType();
11302 assert(VecVT.getVectorElementCount().isKnownEven() &&
11303 "Expecting the mask to be an evenly-sized vector");
11304 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11305 SDValue HalfNumElts =
11306 VecVT.isFixedLengthVector()
11307 ? getConstant(HalfMinNumElts, DL, VT)
11308 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11309 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11310 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11311 return std::make_pair(Lo, Hi);
11314 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11315 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11316 EVT VT = N.getValueType();
11317 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11318 NextPowerOf2(VT.getVectorNumElements()));
11319 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11320 getVectorIdxConstant(0, DL));
11323 void SelectionDAG::ExtractVectorElements(SDValue Op,
11324 SmallVectorImpl<SDValue> &Args,
11325 unsigned Start, unsigned Count,
11327 EVT VT = Op.getValueType();
11329 Count = VT.getVectorNumElements();
11330 if (EltVT == EVT())
11331 EltVT = VT.getVectorElementType();
11333 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11334 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11335 getVectorIdxConstant(i, SL)));
11339 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11340 unsigned GlobalAddressSDNode::getAddressSpace() const {
11341 return getGlobal()->getType()->getAddressSpace();
11344 Type *ConstantPoolSDNode::getType() const {
11345 if (isMachineConstantPoolEntry())
11346 return Val.MachineCPVal->getType();
11347 return Val.ConstVal->getType();
11350 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11351 unsigned &SplatBitSize,
11352 bool &HasAnyUndefs,
11353 unsigned MinSplatBits,
11354 bool IsBigEndian) const {
11355 EVT VT = getValueType(0);
11356 assert(VT.isVector() && "Expected a vector type");
11357 unsigned VecWidth = VT.getSizeInBits();
11358 if (MinSplatBits > VecWidth)
11361 // FIXME: The widths are based on this node's type, but build vectors can
11362 // truncate their operands.
11363 SplatValue = APInt(VecWidth, 0);
11364 SplatUndef = APInt(VecWidth, 0);
11366 // Get the bits. Bits with undefined values (when the corresponding element
11367 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11368 // in SplatValue. If any of the values are not constant, give up and return
11370 unsigned int NumOps = getNumOperands();
11371 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11372 unsigned EltWidth = VT.getScalarSizeInBits();
11374 for (unsigned j = 0; j < NumOps; ++j) {
11375 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11376 SDValue OpVal = getOperand(i);
11377 unsigned BitPos = j * EltWidth;
11379 if (OpVal.isUndef())
11380 SplatUndef.setBits(BitPos, BitPos + EltWidth);
11381 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11382 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11383 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11384 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11389 // The build_vector is all constants or undefs. Find the smallest element
11390 // size that splats the vector.
11391 HasAnyUndefs = (SplatUndef != 0);
11393 // FIXME: This does not work for vectors with elements less than 8 bits.
11394 while (VecWidth > 8) {
11395 unsigned HalfSize = VecWidth / 2;
11396 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11397 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11398 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11399 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11401 // If the two halves do not match (ignoring undef bits), stop here.
11402 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11403 MinSplatBits > HalfSize)
11406 SplatValue = HighValue | LowValue;
11407 SplatUndef = HighUndef & LowUndef;
11409 VecWidth = HalfSize;
11412 SplatBitSize = VecWidth;
11416 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11417 BitVector *UndefElements) const {
11418 unsigned NumOps = getNumOperands();
11419 if (UndefElements) {
11420 UndefElements->clear();
11421 UndefElements->resize(NumOps);
11423 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11427 for (unsigned i = 0; i != NumOps; ++i) {
11428 if (!DemandedElts[i])
11430 SDValue Op = getOperand(i);
11431 if (Op.isUndef()) {
11433 (*UndefElements)[i] = true;
11434 } else if (!Splatted) {
11436 } else if (Splatted != Op) {
11442 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11443 assert(getOperand(FirstDemandedIdx).isUndef() &&
11444 "Can only have a splat without a constant for all undefs.");
11445 return getOperand(FirstDemandedIdx);
11451 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11452 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11453 return getSplatValue(DemandedElts, UndefElements);
11456 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11457 SmallVectorImpl<SDValue> &Sequence,
11458 BitVector *UndefElements) const {
11459 unsigned NumOps = getNumOperands();
11461 if (UndefElements) {
11462 UndefElements->clear();
11463 UndefElements->resize(NumOps);
11465 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11466 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11469 // Set the undefs even if we don't find a sequence (like getSplatValue).
11471 for (unsigned I = 0; I != NumOps; ++I)
11472 if (DemandedElts[I] && getOperand(I).isUndef())
11473 (*UndefElements)[I] = true;
11475 // Iteratively widen the sequence length looking for repetitions.
11476 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11477 Sequence.append(SeqLen, SDValue());
11478 for (unsigned I = 0; I != NumOps; ++I) {
11479 if (!DemandedElts[I])
11481 SDValue &SeqOp = Sequence[I % SeqLen];
11482 SDValue Op = getOperand(I);
11483 if (Op.isUndef()) {
11488 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11494 if (!Sequence.empty())
11498 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11502 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11503 BitVector *UndefElements) const {
11504 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11505 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11509 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11510 BitVector *UndefElements) const {
11511 return dyn_cast_or_null<ConstantSDNode>(
11512 getSplatValue(DemandedElts, UndefElements));
11516 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11517 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11521 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11522 BitVector *UndefElements) const {
11523 return dyn_cast_or_null<ConstantFPSDNode>(
11524 getSplatValue(DemandedElts, UndefElements));
11528 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11529 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11533 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11534 uint32_t BitWidth) const {
11535 if (ConstantFPSDNode *CN =
11536 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11538 APSInt IntVal(BitWidth);
11539 const APFloat &APF = CN->getValueAPF();
11540 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11545 return IntVal.exactLogBase2();
11550 bool BuildVectorSDNode::getConstantRawBits(
11551 bool IsLittleEndian, unsigned DstEltSizeInBits,
11552 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11553 // Early-out if this contains anything but Undef/Constant/ConstantFP.
11557 unsigned NumSrcOps = getNumOperands();
11558 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11559 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11560 "Invalid bitcast scale");
11562 // Extract raw src bits.
11563 SmallVector<APInt> SrcBitElements(NumSrcOps,
11564 APInt::getNullValue(SrcEltSizeInBits));
11565 BitVector SrcUndeElements(NumSrcOps, false);
11567 for (unsigned I = 0; I != NumSrcOps; ++I) {
11568 SDValue Op = getOperand(I);
11569 if (Op.isUndef()) {
11570 SrcUndeElements.set(I);
11573 auto *CInt = dyn_cast<ConstantSDNode>(Op);
11574 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11575 assert((CInt || CFP) && "Unknown constant");
11576 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11577 : CFP->getValueAPF().bitcastToAPInt();
11580 // Recast to dst width.
11581 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11582 SrcBitElements, UndefElements, SrcUndeElements);
11586 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11587 unsigned DstEltSizeInBits,
11588 SmallVectorImpl<APInt> &DstBitElements,
11589 ArrayRef<APInt> SrcBitElements,
11590 BitVector &DstUndefElements,
11591 const BitVector &SrcUndefElements) {
11592 unsigned NumSrcOps = SrcBitElements.size();
11593 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11594 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11595 "Invalid bitcast scale");
11596 assert(NumSrcOps == SrcUndefElements.size() &&
11597 "Vector size mismatch");
11599 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11600 DstUndefElements.clear();
11601 DstUndefElements.resize(NumDstOps, false);
11602 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11604 // Concatenate src elements constant bits together into dst element.
11605 if (SrcEltSizeInBits <= DstEltSizeInBits) {
11606 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11607 for (unsigned I = 0; I != NumDstOps; ++I) {
11608 DstUndefElements.set(I);
11609 APInt &DstBits = DstBitElements[I];
11610 for (unsigned J = 0; J != Scale; ++J) {
11611 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11612 if (SrcUndefElements[Idx])
11614 DstUndefElements.reset(I);
11615 const APInt &SrcBits = SrcBitElements[Idx];
11616 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11617 "Illegal constant bitwidths");
11618 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11624 // Split src element constant bits into dst elements.
11625 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11626 for (unsigned I = 0; I != NumSrcOps; ++I) {
11627 if (SrcUndefElements[I]) {
11628 DstUndefElements.set(I * Scale, (I + 1) * Scale);
11631 const APInt &SrcBits = SrcBitElements[I];
11632 for (unsigned J = 0; J != Scale; ++J) {
11633 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11634 APInt &DstBits = DstBitElements[Idx];
11635 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11640 bool BuildVectorSDNode::isConstant() const {
11641 for (const SDValue &Op : op_values()) {
11642 unsigned Opc = Op.getOpcode();
11643 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11649 Optional<std::pair<APInt, APInt>>
11650 BuildVectorSDNode::isConstantSequence() const {
11651 unsigned NumOps = getNumOperands();
11655 if (!isa<ConstantSDNode>(getOperand(0)) ||
11656 !isa<ConstantSDNode>(getOperand(1)))
11659 unsigned EltSize = getValueType(0).getScalarSizeInBits();
11660 APInt Start = getConstantOperandAPInt(0).trunc(EltSize);
11661 APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start;
11663 if (Stride.isZero())
11666 for (unsigned i = 2; i < NumOps; ++i) {
11667 if (!isa<ConstantSDNode>(getOperand(i)))
11670 APInt Val = getConstantOperandAPInt(i).trunc(EltSize);
11671 if (Val != (Start + (Stride * i)))
11675 return std::make_pair(Start, Stride);
11678 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11679 // Find the first non-undef value in the shuffle mask.
11681 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11684 // If all elements are undefined, this shuffle can be considered a splat
11685 // (although it should eventually get simplified away completely).
11689 // Make sure all remaining elements are either undef or the same as the first
11690 // non-undef value.
11691 for (int Idx = Mask[i]; i != e; ++i)
11692 if (Mask[i] >= 0 && Mask[i] != Idx)
11697 // Returns the SDNode if it is a constant integer BuildVector
11698 // or constant integer.
11699 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11700 if (isa<ConstantSDNode>(N))
11701 return N.getNode();
11702 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11703 return N.getNode();
11704 // Treat a GlobalAddress supporting constant offset folding as a
11705 // constant integer.
11706 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11707 if (GA->getOpcode() == ISD::GlobalAddress &&
11708 TLI->isOffsetFoldingLegal(GA))
11710 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11711 isa<ConstantSDNode>(N.getOperand(0)))
11712 return N.getNode();
11716 // Returns the SDNode if it is a constant float BuildVector
11717 // or constant float.
11718 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11719 if (isa<ConstantFPSDNode>(N))
11720 return N.getNode();
11722 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11723 return N.getNode();
11725 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11726 isa<ConstantFPSDNode>(N.getOperand(0)))
11727 return N.getNode();
11732 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11733 assert(!Node->OperandList && "Node already has operands");
11734 assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11735 "too many operands to fit into SDNode");
11736 SDUse *Ops = OperandRecycler.allocate(
11737 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11739 bool IsDivergent = false;
11740 for (unsigned I = 0; I != Vals.size(); ++I) {
11741 Ops[I].setUser(Node);
11742 Ops[I].setInitial(Vals[I]);
11743 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11744 IsDivergent |= Ops[I].getNode()->isDivergent();
11746 Node->NumOperands = Vals.size();
11747 Node->OperandList = Ops;
11748 if (!TLI->isSDNodeAlwaysUniform(Node)) {
11749 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11750 Node->SDNodeBits.IsDivergent = IsDivergent;
11752 checkForCycles(Node);
11755 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11756 SmallVectorImpl<SDValue> &Vals) {
11757 size_t Limit = SDNode::getMaxNumOperands();
11758 while (Vals.size() > Limit) {
11759 unsigned SliceIdx = Vals.size() - Limit;
11760 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11761 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11762 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11763 Vals.emplace_back(NewTF);
11765 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11768 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11769 EVT VT, SDNodeFlags Flags) {
11777 return getConstant(0, DL, VT);
11779 return getConstant(1, DL, VT);
11782 return getAllOnesConstant(DL, VT);
11784 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11786 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11788 return getConstantFP(-0.0, DL, VT);
11790 return getConstantFP(1.0, DL, VT);
11792 case ISD::FMAXNUM: {
11793 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11794 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11795 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11796 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11797 APFloat::getLargest(Semantics);
11798 if (Opcode == ISD::FMAXNUM)
11799 NeutralAF.changeSign();
11801 return getConstantFP(NeutralAF, DL, VT);
11807 static void checkForCyclesHelper(const SDNode *N,
11808 SmallPtrSetImpl<const SDNode*> &Visited,
11809 SmallPtrSetImpl<const SDNode*> &Checked,
11810 const llvm::SelectionDAG *DAG) {
11811 // If this node has already been checked, don't check it again.
11812 if (Checked.count(N))
11815 // If a node has already been visited on this depth-first walk, reject it as
11817 if (!Visited.insert(N).second) {
11818 errs() << "Detected cycle in SelectionDAG\n";
11819 dbgs() << "Offending node:\n";
11820 N->dumprFull(DAG); dbgs() << "\n";
11824 for (const SDValue &Op : N->op_values())
11825 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11832 void llvm::checkForCycles(const llvm::SDNode *N,
11833 const llvm::SelectionDAG *DAG,
11836 bool check = force;
11837 #ifdef EXPENSIVE_CHECKS
11839 #endif // EXPENSIVE_CHECKS
11841 assert(N && "Checking nonexistent SDNode");
11842 SmallPtrSet<const SDNode*, 32> visited;
11843 SmallPtrSet<const SDNode*, 32> checked;
11844 checkForCyclesHelper(N, visited, checked, DAG);
11849 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11850 checkForCycles(DAG->getRoot().getNode(), DAG, force);