LLVM 24.0.0git
SelectionDAG.cpp
Go to the documentation of this file.
1//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the SelectionDAG class.
10//
11//===----------------------------------------------------------------------===//
12
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/DenseSet.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Twine.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/GlobalValue.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Type.h"
65#include "llvm/Support/Debug.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <cstdlib>
79#include <limits>
80#include <optional>
81#include <string>
82#include <utility>
83#include <vector>
84
85using namespace llvm;
86using namespace llvm::SDPatternMatch;
87
88/// makeVTList - Return an instance of the SDVTList struct initialized with the
89/// specified members.
90static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
91 SDVTList Res = {VTs, NumVTs};
92 return Res;
93}
94
95// Default null implementations of the callbacks.
99
100void SelectionDAG::DAGNodeDeletedListener::anchor() {}
101void SelectionDAG::DAGNodeInsertedListener::anchor() {}
102
103#define DEBUG_TYPE "selectiondag"
104
105static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
106 cl::Hidden, cl::init(true),
107 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
108
109static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
110 cl::desc("Number limit for gluing ld/st of memcpy."),
111 cl::Hidden, cl::init(0));
112
114 MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192),
115 cl::desc("DAG combiner limit number of steps when searching DAG "
116 "for predecessor nodes"));
117
119 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
120}
121
123
124//===----------------------------------------------------------------------===//
125// ConstantFPSDNode Class
126//===----------------------------------------------------------------------===//
127
128/// isExactlyValue - We don't rely on operator== working on double values, as
129/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
130/// As such, this method can be used to do an exact bit-for-bit comparison of
131/// two floating point values.
133 return getValueAPF().bitwiseIsEqual(V);
134}
135
137 const APFloat& Val) {
138 assert(VT.isFloatingPoint() && "Can only convert between FP types");
139
140 // convert modifies in place, so make a copy.
141 APFloat Val2 = APFloat(Val);
142 bool losesInfo;
144 &losesInfo);
145 return !losesInfo;
146}
147
148//===----------------------------------------------------------------------===//
149// ISD Namespace
150//===----------------------------------------------------------------------===//
151
152bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
153 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
154 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
155 unsigned EltSize =
156 N->getValueType(0).getVectorElementType().getSizeInBits();
157 SplatVal = OptAPInt->trunc(EltSize);
158 return true;
159 }
160 }
161
162 auto *BV = dyn_cast<BuildVectorSDNode>(N);
163 if (!BV)
164 return false;
165
166 APInt SplatUndef;
167 unsigned SplatBitSize;
168 bool HasUndefs;
169 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
170 // Endianness does not matter here. We are checking for a splat given the
171 // element size of the vector, and if we find such a splat for little endian
172 // layout, then that should be valid also for big endian (as the full vector
173 // size is known to be a multiple of the element size).
174 const bool IsBigEndian = false;
175 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
176 EltSize, IsBigEndian) &&
177 EltSize == SplatBitSize;
178}
179
180// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
181// specializations of the more general isConstantSplatVector()?
182
183bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
184 // Look through a bit convert.
185 while (N->getOpcode() == ISD::BITCAST)
186 N = N->getOperand(0).getNode();
187
188 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
189 APInt SplatVal;
190 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
191 }
192
193 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
194
195 unsigned i = 0, e = N->getNumOperands();
196
197 // Skip over all of the undef values.
198 while (i != e && N->getOperand(i).isUndef())
199 ++i;
200
201 // Do not accept an all-undef vector.
202 if (i == e) return false;
203
204 // Do not accept build_vectors that aren't all constants or which have non-~0
205 // elements. We have to be a bit careful here, as the type of the constant
206 // may not be the same as the type of the vector elements due to type
207 // legalization (the elements are promoted to a legal type for the target and
208 // a vector of a type may be legal when the base element type is not).
209 // We only want to check enough bits to cover the vector elements, because
210 // we care if the resultant vector is all ones, not whether the individual
211 // constants are.
212 SDValue NotZero = N->getOperand(i);
213 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
214 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
215 if (OptAPInt->countr_one() < EltSize)
216 return false;
217 } else
218 return false;
219
220 // Okay, we have at least one ~0 value, check to see if the rest match or are
221 // undefs. Even with the above element type twiddling, this should be OK, as
222 // the same type legalization should have applied to all the elements.
223 for (++i; i != e; ++i)
224 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
225 return false;
226 return true;
227}
228
229bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
230 // Look through a bit convert.
231 while (N->getOpcode() == ISD::BITCAST)
232 N = N->getOperand(0).getNode();
233
234 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
235 APInt SplatVal;
236 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
237 }
238
239 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
240
241 bool IsAllUndef = true;
242 for (const SDValue &Op : N->op_values()) {
243 if (Op.isUndef())
244 continue;
245 IsAllUndef = false;
246 // Do not accept build_vectors that aren't all constants or which have non-0
247 // elements. We have to be a bit careful here, as the type of the constant
248 // may not be the same as the type of the vector elements due to type
249 // legalization (the elements are promoted to a legal type for the target
250 // and a vector of a type may be legal when the base element type is not).
251 // We only want to check enough bits to cover the vector elements, because
252 // we care if the resultant vector is all zeros, not whether the individual
253 // constants are.
254 if (auto OptAPInt = Op->bitcastToAPInt()) {
255 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
256 if (OptAPInt->countr_zero() < EltSize)
257 return false;
258 } else
259 return false;
260 }
261
262 // Do not accept an all-undef vector.
263 if (IsAllUndef)
264 return false;
265 return true;
266}
267
269 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
270}
271
273 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
274}
275
277 if (N->getOpcode() != ISD::BUILD_VECTOR)
278 return false;
279
280 for (const SDValue &Op : N->op_values()) {
281 if (Op.isUndef())
282 continue;
284 return false;
285 }
286 return true;
287}
288
290 if (N->getOpcode() != ISD::BUILD_VECTOR)
291 return false;
292
293 for (const SDValue &Op : N->op_values()) {
294 if (Op.isUndef())
295 continue;
297 return false;
298 }
299 return true;
300}
301
302bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
303 bool Signed) {
304 assert(N->getValueType(0).isVector() && "Expected a vector!");
305
306 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
307 if (EltSize <= NewEltSize)
308 return false;
309
310 if (N->getOpcode() == ISD::ZERO_EXTEND) {
311 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
312 NewEltSize) &&
313 !Signed;
314 }
315 if (N->getOpcode() == ISD::SIGN_EXTEND) {
316 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
317 NewEltSize) &&
318 Signed;
319 }
320 if (N->getOpcode() != ISD::BUILD_VECTOR)
321 return false;
322
323 for (const SDValue &Op : N->op_values()) {
324 if (Op.isUndef())
325 continue;
327 return false;
328
329 APInt C = Op->getAsAPIntVal().trunc(EltSize);
330 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
331 return false;
332 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
333 return false;
334 }
335
336 return true;
337}
338
340 // Return false if the node has no operands.
341 // This is "logically inconsistent" with the definition of "all" but
342 // is probably the desired behavior.
343 if (N->getNumOperands() == 0)
344 return false;
345 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
346}
347
349 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
350}
351
352template <typename ConstNodeType>
354 std::function<bool(ConstNodeType *)> Match,
355 bool AllowUndefs, bool AllowTruncation) {
356 // FIXME: Add support for scalar UNDEF cases?
357 if (auto *C = dyn_cast<ConstNodeType>(Op))
358 return Match(C);
359
360 // FIXME: Add support for vector UNDEF cases?
361 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
362 ISD::SPLAT_VECTOR != Op.getOpcode())
363 return false;
364
365 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
366 return true;
367
368 EVT SVT = Op.getValueType().getScalarType();
369 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
370 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
371 continue;
372
373 if (AllowUndefs && Op.getOperand(i).isUndef()) {
374 if (!Match(nullptr))
375 return false;
376 continue;
377 }
378
379 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
380 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
381 !Match(Cst))
382 return false;
383 }
384 return true;
385}
386// Build used template types.
388 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
390 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
391 bool);
392
394 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
395 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
396 bool AllowUndefs, bool AllowTypeMismatch) {
397 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
398 return false;
399
400 // TODO: Add support for scalar UNDEF cases?
401 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
402 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
403 return Match(LHSCst, RHSCst);
404
405 // TODO: Add support for vector UNDEF cases?
406 if (LHS.getOpcode() != RHS.getOpcode() ||
407 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
408 LHS.getOpcode() != ISD::SPLAT_VECTOR))
409 return false;
410
411 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
412 return true;
413
414 EVT SVT = LHS.getValueType().getScalarType();
415 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
416 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
417 continue;
418 SDValue LHSOp = LHS.getOperand(i);
419 SDValue RHSOp = RHS.getOperand(i);
420 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
421 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
422 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
423 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
424 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
425 return false;
426 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
427 LHSOp.getValueType() != RHSOp.getValueType()))
428 return false;
429 if (!Match(LHSCst, RHSCst))
430 return false;
431 }
432 return true;
433}
434
436 switch (MinMaxOpc) {
437 default:
438 llvm_unreachable("unrecognized opcode");
439 case ISD::UMIN:
440 return ISD::UMAX;
441 case ISD::UMAX:
442 return ISD::UMIN;
443 case ISD::SMIN:
444 return ISD::SMAX;
445 case ISD::SMAX:
446 return ISD::SMIN;
447 }
448}
449
451 switch (MinMaxOpc) {
452 default:
453 llvm_unreachable("unrecognized min/max opcode");
454 case ISD::SMIN:
455 return ISD::UMIN;
456 case ISD::SMAX:
457 return ISD::UMAX;
458 case ISD::UMIN:
459 return ISD::SMIN;
460 case ISD::UMAX:
461 return ISD::SMAX;
462 }
463}
464
466 switch (VecReduceOpcode) {
467 default:
468 llvm_unreachable("Expected VECREDUCE opcode");
471 case ISD::VP_REDUCE_FADD:
472 case ISD::VP_REDUCE_SEQ_FADD:
473 return ISD::FADD;
476 case ISD::VP_REDUCE_FMUL:
477 case ISD::VP_REDUCE_SEQ_FMUL:
478 return ISD::FMUL;
480 case ISD::VP_REDUCE_ADD:
481 return ISD::ADD;
483 case ISD::VP_REDUCE_MUL:
484 return ISD::MUL;
486 case ISD::VP_REDUCE_AND:
487 return ISD::AND;
489 case ISD::VP_REDUCE_OR:
490 return ISD::OR;
492 case ISD::VP_REDUCE_XOR:
493 return ISD::XOR;
495 case ISD::VP_REDUCE_SMAX:
496 return ISD::SMAX;
498 case ISD::VP_REDUCE_SMIN:
499 return ISD::SMIN;
501 case ISD::VP_REDUCE_UMAX:
502 return ISD::UMAX;
504 case ISD::VP_REDUCE_UMIN:
505 return ISD::UMIN;
507 case ISD::VP_REDUCE_FMAX:
508 return ISD::FMAXNUM;
510 case ISD::VP_REDUCE_FMIN:
511 return ISD::FMINNUM;
513 case ISD::VP_REDUCE_FMAXIMUM:
514 return ISD::FMAXIMUM;
516 case ISD::VP_REDUCE_FMINIMUM:
517 return ISD::FMINIMUM;
519 return ISD::FMAXIMUMNUM;
521 return ISD::FMINIMUMNUM;
522 }
523}
524
526 switch (MaskedOpc) {
527 case ISD::MASKED_UDIV:
528 return ISD::UDIV;
529 case ISD::MASKED_SDIV:
530 return ISD::SDIV;
531 case ISD::MASKED_UREM:
532 return ISD::UREM;
533 case ISD::MASKED_SREM:
534 return ISD::SREM;
535 default:
536 llvm_unreachable("Expected masked binop opcode");
537 }
538}
539
540bool ISD::isVPOpcode(unsigned Opcode) {
541 switch (Opcode) {
542 default:
543 return false;
544#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
545 case ISD::VPSD: \
546 return true;
547#include "llvm/IR/VPIntrinsics.def"
548 }
549}
550
551bool ISD::isVPBinaryOp(unsigned Opcode) {
552 switch (Opcode) {
553 default:
554 break;
555#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
556#define VP_PROPERTY_BINARYOP return true;
557#define END_REGISTER_VP_SDNODE(VPSD) break;
558#include "llvm/IR/VPIntrinsics.def"
559 }
560 return false;
561}
562
563bool ISD::isVPReduction(unsigned Opcode) {
564 switch (Opcode) {
565 default:
566 return false;
567 case ISD::VP_REDUCE_ADD:
568 case ISD::VP_REDUCE_MUL:
569 case ISD::VP_REDUCE_AND:
570 case ISD::VP_REDUCE_OR:
571 case ISD::VP_REDUCE_XOR:
572 case ISD::VP_REDUCE_SMAX:
573 case ISD::VP_REDUCE_SMIN:
574 case ISD::VP_REDUCE_UMAX:
575 case ISD::VP_REDUCE_UMIN:
576 case ISD::VP_REDUCE_FMAX:
577 case ISD::VP_REDUCE_FMIN:
578 case ISD::VP_REDUCE_FMAXIMUM:
579 case ISD::VP_REDUCE_FMINIMUM:
580 case ISD::VP_REDUCE_FADD:
581 case ISD::VP_REDUCE_FMUL:
582 case ISD::VP_REDUCE_SEQ_FADD:
583 case ISD::VP_REDUCE_SEQ_FMUL:
584 return true;
585 }
586}
587
588/// The operand position of the vector mask.
589std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
590 switch (Opcode) {
591 default:
592 return std::nullopt;
593#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
594 case ISD::VPSD: \
595 return MASKPOS;
596#include "llvm/IR/VPIntrinsics.def"
597 }
598}
599
600/// The operand position of the explicit vector length parameter.
601std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
602 switch (Opcode) {
603 default:
604 return std::nullopt;
605#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
606 case ISD::VPSD: \
607 return EVLPOS;
608#include "llvm/IR/VPIntrinsics.def"
609 }
610}
611
612std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
613 bool hasFPExcept) {
614 // FIXME: Return strict opcodes in case of fp exceptions.
615 switch (VPOpcode) {
616 default:
617 return std::nullopt;
618#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
619#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
620#define END_REGISTER_VP_SDNODE(VPOPC) break;
621#include "llvm/IR/VPIntrinsics.def"
622 }
623 return std::nullopt;
624}
625
626std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
627 switch (Opcode) {
628 default:
629 return std::nullopt;
630#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
631#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
632#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
633#include "llvm/IR/VPIntrinsics.def"
634 }
635}
636
638 switch (ExtType) {
639 case ISD::EXTLOAD:
640 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
641 case ISD::SEXTLOAD:
642 return ISD::SIGN_EXTEND;
643 case ISD::ZEXTLOAD:
644 return ISD::ZERO_EXTEND;
645 default:
646 break;
647 }
648
649 llvm_unreachable("Invalid LoadExtType");
650}
651
653 // To perform this operation, we just need to swap the L and G bits of the
654 // operation.
655 unsigned OldL = (Operation >> 2) & 1;
656 unsigned OldG = (Operation >> 1) & 1;
657 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
658 (OldL << 1) | // New G bit
659 (OldG << 2)); // New L bit.
660}
661
663 unsigned Operation = Op;
664 if (isIntegerLike)
665 Operation ^= 7; // Flip L, G, E bits, but not U.
666 else
667 Operation ^= 15; // Flip all of the condition bits.
668
670 Operation &= ~8; // Don't let N and U bits get set.
671
672 return ISD::CondCode(Operation);
673}
674
678
680 bool isIntegerLike) {
681 return getSetCCInverseImpl(Op, isIntegerLike);
682}
683
684/// For an integer comparison, return 1 if the comparison is a signed operation
685/// and 2 if the result is an unsigned comparison. Return zero if the operation
686/// does not depend on the sign of the input (setne and seteq).
687static int isSignedOp(ISD::CondCode Opcode) {
688 switch (Opcode) {
689 default: llvm_unreachable("Illegal integer setcc operation!");
690 case ISD::SETEQ:
691 case ISD::SETNE: return 0;
692 case ISD::SETLT:
693 case ISD::SETLE:
694 case ISD::SETGT:
695 case ISD::SETGE: return 1;
696 case ISD::SETULT:
697 case ISD::SETULE:
698 case ISD::SETUGT:
699 case ISD::SETUGE: return 2;
700 }
701}
702
704 EVT Type) {
705 bool IsInteger = Type.isInteger();
706 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
707 // Cannot fold a signed integer setcc with an unsigned integer setcc.
708 return ISD::SETCC_INVALID;
709
710 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
711
712 // If the N and U bits get set, then the resultant comparison DOES suddenly
713 // care about orderedness, and it is true when ordered.
714 if (Op > ISD::SETTRUE2)
715 Op &= ~16; // Clear the U bit if the N bit is set.
716
717 // Canonicalize illegal integer setcc's.
718 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
719 Op = ISD::SETNE;
720
721 return ISD::CondCode(Op);
722}
723
725 EVT Type) {
726 bool IsInteger = Type.isInteger();
727 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
728 // Cannot fold a signed setcc with an unsigned setcc.
729 return ISD::SETCC_INVALID;
730
731 // Combine all of the condition bits.
732 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
733
734 // Canonicalize illegal integer setcc's.
735 if (IsInteger) {
736 switch (Result) {
737 default: break;
738 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
739 case ISD::SETOEQ: // SETEQ & SETU[LG]E
740 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
741 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
742 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
743 }
744 }
745
746 return Result;
747}
748
749//===----------------------------------------------------------------------===//
750// SDNode Profile Support
751//===----------------------------------------------------------------------===//
752
753/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
754static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
755 ID.AddInteger(OpC);
756}
757
758/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
759/// solely with their pointer.
761 ID.AddPointer(VTList.VTs);
762}
763
764/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
767 for (const auto &Op : Ops) {
768 ID.AddPointer(Op.getNode());
769 ID.AddInteger(Op.getResNo());
770 }
771}
772
773/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
776 for (const auto &Op : Ops) {
777 ID.AddPointer(Op.getNode());
778 ID.AddInteger(Op.getResNo());
779 }
780}
781
782static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
783 SDVTList VTList, ArrayRef<SDValue> OpList) {
784 AddNodeIDOpcode(ID, OpC);
785 AddNodeIDValueTypes(ID, VTList);
786 AddNodeIDOperands(ID, OpList);
787}
788
789/// If this is an SDNode with special info, add this info to the NodeID data.
790static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
791 switch (N->getOpcode()) {
794 case ISD::MCSymbol:
795 llvm_unreachable("Should only be used on nodes with operands");
796 default: break; // Normal nodes don't need extra info.
798 case ISD::Constant: {
800 ID.AddPointer(C->getConstantIntValue());
801 ID.AddBoolean(C->isOpaque());
802 break;
803 }
805 case ISD::ConstantFP:
806 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
807 break;
813 ID.AddPointer(GA->getGlobal());
814 ID.AddInteger(GA->getOffset());
815 ID.AddInteger(GA->getTargetFlags());
816 break;
817 }
818 case ISD::BasicBlock:
819 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
820 break;
821 case ISD::Register:
822 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
823 break;
825 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
826 break;
827 case ISD::SRCVALUE:
828 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
829 break;
830 case ISD::FrameIndex:
832 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
833 break;
835 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
836 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
837 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
838 break;
839 case ISD::JumpTable:
841 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
842 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
843 break;
847 ID.AddInteger(CP->getAlign().value());
848 ID.AddInteger(CP->getOffset());
851 else
852 ID.AddPointer(CP->getConstVal());
853 ID.AddInteger(CP->getTargetFlags());
854 break;
855 }
856 case ISD::TargetIndex: {
858 ID.AddInteger(TI->getIndex());
859 ID.AddInteger(TI->getOffset());
860 ID.AddInteger(TI->getTargetFlags());
861 break;
862 }
863 case ISD::LOAD: {
864 const LoadSDNode *LD = cast<LoadSDNode>(N);
865 ID.AddInteger(LD->getMemoryVT().getRawBits());
866 ID.AddInteger(LD->getRawSubclassData());
867 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
868 ID.AddInteger(LD->getMemOperand()->getFlags());
869 break;
870 }
871 case ISD::STORE: {
872 const StoreSDNode *ST = cast<StoreSDNode>(N);
873 ID.AddInteger(ST->getMemoryVT().getRawBits());
874 ID.AddInteger(ST->getRawSubclassData());
875 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
876 ID.AddInteger(ST->getMemOperand()->getFlags());
877 break;
878 }
879 case ISD::VP_LOAD: {
880 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
881 ID.AddInteger(ELD->getMemoryVT().getRawBits());
882 ID.AddInteger(ELD->getRawSubclassData());
883 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
884 ID.AddInteger(ELD->getMemOperand()->getFlags());
885 break;
886 }
887 case ISD::VP_LOAD_FF: {
888 const auto *LD = cast<VPLoadFFSDNode>(N);
889 ID.AddInteger(LD->getMemoryVT().getRawBits());
890 ID.AddInteger(LD->getRawSubclassData());
891 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
892 ID.AddInteger(LD->getMemOperand()->getFlags());
893 break;
894 }
895 case ISD::VP_STORE: {
896 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
897 ID.AddInteger(EST->getMemoryVT().getRawBits());
898 ID.AddInteger(EST->getRawSubclassData());
899 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
900 ID.AddInteger(EST->getMemOperand()->getFlags());
901 break;
902 }
903 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
905 ID.AddInteger(SLD->getMemoryVT().getRawBits());
906 ID.AddInteger(SLD->getRawSubclassData());
907 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
908 break;
909 }
910 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
912 ID.AddInteger(SST->getMemoryVT().getRawBits());
913 ID.AddInteger(SST->getRawSubclassData());
914 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
915 break;
916 }
917 case ISD::VP_GATHER: {
919 ID.AddInteger(EG->getMemoryVT().getRawBits());
920 ID.AddInteger(EG->getRawSubclassData());
921 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
922 ID.AddInteger(EG->getMemOperand()->getFlags());
923 break;
924 }
925 case ISD::VP_SCATTER: {
927 ID.AddInteger(ES->getMemoryVT().getRawBits());
928 ID.AddInteger(ES->getRawSubclassData());
929 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
930 ID.AddInteger(ES->getMemOperand()->getFlags());
931 break;
932 }
933 case ISD::MLOAD: {
935 ID.AddInteger(MLD->getMemoryVT().getRawBits());
936 ID.AddInteger(MLD->getRawSubclassData());
937 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
938 ID.AddInteger(MLD->getMemOperand()->getFlags());
939 break;
940 }
941 case ISD::MSTORE: {
943 ID.AddInteger(MST->getMemoryVT().getRawBits());
944 ID.AddInteger(MST->getRawSubclassData());
945 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
946 ID.AddInteger(MST->getMemOperand()->getFlags());
947 break;
948 }
949 case ISD::MGATHER: {
951 ID.AddInteger(MG->getMemoryVT().getRawBits());
952 ID.AddInteger(MG->getRawSubclassData());
953 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
954 ID.AddInteger(MG->getMemOperand()->getFlags());
955 break;
956 }
957 case ISD::MSCATTER: {
959 ID.AddInteger(MS->getMemoryVT().getRawBits());
960 ID.AddInteger(MS->getRawSubclassData());
961 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
962 ID.AddInteger(MS->getMemOperand()->getFlags());
963 break;
964 }
967 case ISD::ATOMIC_SWAP:
979 case ISD::ATOMIC_LOAD:
980 case ISD::ATOMIC_STORE: {
981 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
982 ID.AddInteger(AT->getMemoryVT().getRawBits());
983 ID.AddInteger(AT->getRawSubclassData());
984 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
985 ID.AddInteger(AT->getMemOperand()->getFlags());
986 break;
987 }
988 case ISD::VECTOR_SHUFFLE: {
989 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
990 for (int M : Mask)
991 ID.AddInteger(M);
992 break;
993 }
994 case ISD::ADDRSPACECAST: {
996 ID.AddInteger(ASC->getSrcAddressSpace());
997 ID.AddInteger(ASC->getDestAddressSpace());
998 break;
999 }
1001 case ISD::BlockAddress: {
1003 ID.AddPointer(BA->getBlockAddress());
1004 ID.AddInteger(BA->getOffset());
1005 ID.AddInteger(BA->getTargetFlags());
1006 break;
1007 }
1008 case ISD::AssertAlign:
1009 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
1010 break;
1011 case ISD::PREFETCH:
1014 // Handled by MemIntrinsicSDNode check after the switch.
1015 break;
1016 case ISD::MDNODE_SDNODE:
1017 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
1018 break;
1019 } // end switch (N->getOpcode())
1020
1021 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
1022 // to check.
1023 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
1024 ID.AddInteger(MN->getRawSubclassData());
1025 ID.AddInteger(MN->getMemoryVT().getRawBits());
1026 for (const MachineMemOperand *MMO : MN->memoperands()) {
1027 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1028 ID.AddInteger(MMO->getFlags());
1029 }
1030 }
1031}
1032
1033/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
1034/// data.
1035static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1036 AddNodeIDOpcode(ID, N->getOpcode());
1037 // Add the return value info.
1038 AddNodeIDValueTypes(ID, N->getVTList());
1039 // Add the operand info.
1040 AddNodeIDOperands(ID, N->ops());
1041
1042 // Handle SDNode leafs with special info.
1043 AddNodeIDCustom(ID, N);
1044}
1045
1046//===----------------------------------------------------------------------===//
1047// SelectionDAG Class
1048//===----------------------------------------------------------------------===//
1049
1050/// doNotCSE - Return true if CSE should not be performed for this node.
1051static bool doNotCSE(SDNode *N) {
1052 if (N->getValueType(0) == MVT::Glue)
1053 return true; // Never CSE anything that produces a glue result.
1054
1055 switch (N->getOpcode()) {
1056 default: break;
1057 case ISD::HANDLENODE:
1058 case ISD::EH_LABEL:
1059 return true; // Never CSE these nodes.
1060 }
1061
1062 // Check that remaining values produced are not flags.
1063 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1064 if (N->getValueType(i) == MVT::Glue)
1065 return true; // Never CSE anything that produces a glue result.
1066
1067 return false;
1068}
1069
1070/// Construct a DemandedElts mask which demands all elements of \p V.
1071/// If \p V is not a fixed-length vector, then this will return a single bit.
1073 EVT VT = V.getValueType();
1074 // Since the number of lanes in a scalable vector is unknown at compile time,
1075 // we track one bit which is implicitly broadcast to all lanes. This means
1076 // that all lanes in a scalable vector are considered demanded.
1078 : APInt(1, 1);
1079}
1080
1081/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1082/// SelectionDAG.
1084 // Create a dummy node (which is not added to allnodes), that adds a reference
1085 // to the root node, preventing it from being deleted.
1086 HandleSDNode Dummy(getRoot());
1087
1088 SmallVector<SDNode*, 128> DeadNodes;
1089
1090 // Add all obviously-dead nodes to the DeadNodes worklist.
1091 for (SDNode &Node : allnodes())
1092 if (Node.use_empty())
1093 DeadNodes.push_back(&Node);
1094
1095 RemoveDeadNodes(DeadNodes);
1096
1097 // If the root changed (e.g. it was a dead load, update the root).
1098 setRoot(Dummy.getValue());
1099}
1100
1101/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1102/// given list, and any nodes that become unreachable as a result.
1104
1105 // Process the worklist, deleting the nodes and adding their uses to the
1106 // worklist.
1107 while (!DeadNodes.empty()) {
1108 SDNode *N = DeadNodes.pop_back_val();
1109 // Skip to next node if we've already managed to delete the node. This could
1110 // happen if replacing a node causes a node previously added to the node to
1111 // be deleted.
1112 if (N->getOpcode() == ISD::DELETED_NODE)
1113 continue;
1114
1115 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1116 DUL->NodeDeleted(N, nullptr);
1117
1118 // Take the node out of the appropriate CSE map.
1119 RemoveNodeFromCSEMaps(N);
1120
1121 // Next, brutally remove the operand list. This is safe to do, as there are
1122 // no cycles in the graph.
1123 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1124 SDUse &Use = *I++;
1125 SDNode *Operand = Use.getNode();
1126 Use.set(SDValue());
1127
1128 // Now that we removed this operand, see if there are no uses of it left.
1129 if (Operand->use_empty())
1130 DeadNodes.push_back(Operand);
1131 }
1132
1133 DeallocateNode(N);
1134 }
1135}
1136
1138 SmallVector<SDNode*, 16> DeadNodes(1, N);
1139
1140 // Create a dummy node that adds a reference to the root node, preventing
1141 // it from being deleted. (This matters if the root is an operand of the
1142 // dead node.)
1143 HandleSDNode Dummy(getRoot());
1144
1145 RemoveDeadNodes(DeadNodes);
1146}
1147
1149 // First take this out of the appropriate CSE map.
1150 RemoveNodeFromCSEMaps(N);
1151
1152 // Finally, remove uses due to operands of this node, remove from the
1153 // AllNodes list, and delete the node.
1154 DeleteNodeNotInCSEMaps(N);
1155}
1156
1157void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1158 assert(N->getIterator() != AllNodes.begin() &&
1159 "Cannot delete the entry node!");
1160 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1161
1162 // Drop all of the operands and decrement used node's use counts.
1163 N->DropOperands();
1164
1165 DeallocateNode(N);
1166}
1167
1168void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1169 assert(!(V->isVariadic() && isParameter));
1170 if (isParameter)
1171 ByvalParmDbgValues.push_back(V);
1172 else
1173 DbgValues.push_back(V);
1174 for (const SDNode *Node : V->getSDNodes())
1175 if (Node)
1176 DbgValMap[Node].push_back(V);
1177}
1178
1180 DbgValMapType::iterator I = DbgValMap.find(Node);
1181 if (I == DbgValMap.end())
1182 return;
1183 for (auto &Val: I->second)
1184 Val->setIsInvalidated();
1185 DbgValMap.erase(I);
1186}
1187
1188void SelectionDAG::DeallocateNode(SDNode *N) {
1189 // If we have operands, deallocate them.
1191
1192 NodeAllocator.Deallocate(AllNodes.remove(N));
1193
1194 // Set the opcode to DELETED_NODE to help catch bugs when node
1195 // memory is reallocated.
1196 // FIXME: There are places in SDag that have grown a dependency on the opcode
1197 // value in the released node.
1198 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1199 N->NodeType = ISD::DELETED_NODE;
1200
1201 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1202 // them and forget about that node.
1203 DbgInfo->erase(N);
1204
1205 // Invalidate extra info.
1206 SDEI.erase(N);
1207}
1208
1209#ifndef NDEBUG
1210/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1211void SelectionDAG::verifyNode(SDNode *N) const {
1212 switch (N->getOpcode()) {
1213 default:
1214 if (N->isTargetOpcode())
1216 break;
1217 case ISD::BUILD_PAIR: {
1218 EVT VT = N->getValueType(0);
1219 assert(N->getNumValues() == 1 && "Too many results!");
1220 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1221 "Wrong return type!");
1222 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1223 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1224 "Mismatched operand types!");
1225 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1226 "Wrong operand type!");
1227 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1228 "Wrong return type size");
1229 break;
1230 }
1231 case ISD::BUILD_VECTOR: {
1232 assert(N->getNumValues() == 1 && "Too many results!");
1233 assert(N->getValueType(0).isVector() && "Wrong return type!");
1234 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1235 "Wrong number of operands!");
1236 EVT EltVT = N->getValueType(0).getVectorElementType();
1237 for (const SDUse &Op : N->ops()) {
1238 assert((Op.getValueType() == EltVT ||
1239 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1240 EltVT.bitsLE(Op.getValueType()))) &&
1241 "Wrong operand type!");
1242 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1243 "Operands must all have the same type");
1244 }
1245 break;
1246 }
1247 case ISD::SADDO:
1248 case ISD::UADDO:
1249 case ISD::SSUBO:
1250 case ISD::USUBO:
1251 assert(N->getNumValues() == 2 && "Wrong number of results!");
1252 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1253 "Invalid add/sub overflow op!");
1254 assert(N->getVTList().VTs[0].isInteger() &&
1255 N->getVTList().VTs[1].isInteger() &&
1256 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1257 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1258 "Binary operator types must match!");
1259 break;
1260 }
1261}
1262#endif // NDEBUG
1263
1264/// Insert a newly allocated node into the DAG.
1265///
1266/// Handles insertion into the all nodes list and CSE map, as well as
1267/// verification and other common operations when a new node is allocated.
1268void SelectionDAG::InsertNode(SDNode *N) {
1269 AllNodes.push_back(N);
1270#ifndef NDEBUG
1271 N->PersistentId = NextPersistentId++;
1272 verifyNode(N);
1273#endif
1274 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1275 DUL->NodeInserted(N);
1276}
1277
1278/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1279/// correspond to it. This is useful when we're about to delete or repurpose
1280/// the node. We don't want future request for structurally identical nodes
1281/// to return N anymore.
1282bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1283 bool Erased = false;
1284 switch (N->getOpcode()) {
1285 case ISD::HANDLENODE: return false; // noop.
1286 case ISD::CONDCODE:
1287 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1288 "Cond code doesn't exist!");
1289 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1290 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1291 break;
1293 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1294 break;
1296 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1297 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1298 ESN->getSymbol(), ESN->getTargetFlags()));
1299 break;
1300 }
1301 case ISD::MCSymbol: {
1302 auto *MCSN = cast<MCSymbolSDNode>(N);
1303 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1304 break;
1305 }
1306 case ISD::VALUETYPE: {
1307 EVT VT = cast<VTSDNode>(N)->getVT();
1308 if (VT.isExtended()) {
1309 Erased = ExtendedValueTypeNodes.erase(VT);
1310 } else {
1311 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1312 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1313 }
1314 break;
1315 }
1316 default:
1317 // Remove it from the CSE Map.
1318 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1319 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1320 Erased = CSEMap.erase(N);
1321 break;
1322 }
1323#ifndef NDEBUG
1324 // Verify that the node was actually in one of the CSE maps, unless it has a
1325 // glue result (which cannot be CSE'd) or is one of the special cases that are
1326 // not subject to CSE.
1327 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1328 !N->isMachineOpcode() && !doNotCSE(N)) {
1329 N->dump(this);
1330 dbgs() << "\n";
1331 llvm_unreachable("Node is not in map!");
1332 }
1333#endif
1334 return Erased;
1335}
1336
1337/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1338/// maps and modified in place. Add it back to the CSE maps, unless an identical
1339/// node already exists, in which case transfer all its users to the existing
1340/// node. This transfer can potentially trigger recursive merging.
1341void
1342SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1343 // For node types that aren't CSE'd, just act as if no identical node
1344 // already exists.
1345 if (!doNotCSE(N)) {
1346 SDNode *Existing = CSEMap.getOrInsert(N);
1347 if (Existing != N) {
1348 // If there was already an existing matching node, use ReplaceAllUsesWith
1349 // to replace the dead one with the existing one. This can cause
1350 // recursive merging of other unrelated nodes down the line.
1351 Existing->intersectFlagsWith(N->getFlags());
1352 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1354 cast<MemSDNode>(N)->memoperands();
1355 // Range and cache hint metadata are not part of the DAG CSE key because
1356 // we prefer to CSE even when metadata does not match. Merge potentially
1357 // differing metadata conservatively.
1358 MemNode->refineMMOMetadata(NewMMOs);
1359 }
1360 ReplaceAllUsesWith(N, Existing);
1361
1362 // N is now dead. Inform the listeners and delete it.
1363 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1364 DUL->NodeDeleted(N, Existing);
1365 DeleteNodeNotInCSEMaps(N);
1366 return;
1367 }
1368 }
1369
1370 // If the node doesn't already exist, we updated it. Inform listeners.
1371 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1372 DUL->NodeUpdated(N);
1373}
1374
1375/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1376/// were replaced with those specified. If this node is never memoized,
1377/// return null, otherwise return a pointer to the slot it would take. If a
1378/// node already exists with these operands, the slot will be non-null.
1379SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1380 FoldingSetInsertToken &InsertToken) {
1381 if (doNotCSE(N))
1382 return nullptr;
1383
1384 SDValue Ops[] = { Op };
1385 FoldingSetNodeID ID;
1386 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1387 AddNodeIDCustom(ID, N);
1388 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1389 if (Node)
1390 Node->intersectFlagsWith(N->getFlags());
1391 return Node;
1392}
1393
1394/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1395/// were replaced with those specified. If this node is never memoized,
1396/// return null, otherwise return a pointer to the slot it would take. If a
1397/// node already exists with these operands, the slot will be non-null.
1398SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1399 FoldingSetInsertToken &InsertToken) {
1400 if (doNotCSE(N))
1401 return nullptr;
1402
1403 SDValue Ops[] = { Op1, Op2 };
1404 FoldingSetNodeID ID;
1405 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1406 AddNodeIDCustom(ID, N);
1407 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1408 if (Node)
1409 Node->intersectFlagsWith(N->getFlags());
1410 return Node;
1411}
1412
1413/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1414/// were replaced with those specified. If this node is never memoized,
1415/// return null, otherwise return a pointer to the slot it would take. If a
1416/// node already exists with these operands, the slot will be non-null.
1417SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1418 FoldingSetInsertToken &InsertToken) {
1419 if (doNotCSE(N))
1420 return nullptr;
1421
1422 FoldingSetNodeID ID;
1423 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1424 AddNodeIDCustom(ID, N);
1425 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1426 if (Node)
1427 Node->intersectFlagsWith(N->getFlags());
1428 return Node;
1429}
1430
1432 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1433 : VT.getTypeForEVT(*getContext());
1434
1435 return getDataLayout().getABITypeAlign(Ty);
1436}
1437
1438// EntryNode could meaningfully have debug info if we can find it...
1440 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1441 getVTList(MVT::Other, MVT::Glue)),
1442 Root(getEntryNode()) {
1443 InsertNode(&EntryNode);
1444 DbgInfo = new SDDbgInfo();
1445}
1446
1448 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1449 const TargetLibraryInfo *LibraryInfo,
1450 const LibcallLoweringInfo *LibcallsInfo,
1451 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1453 FunctionVarLocs const *VarLocs) {
1454 MF = &NewMF;
1455 SDAGISelPass = PassPtr;
1456 ORE = &NewORE;
1459 LibInfo = LibraryInfo;
1460 Libcalls = LibcallsInfo;
1461 Context = &MF->getFunction().getContext();
1462 UA = NewUA;
1463 PSI = PSIin;
1464 BFI = BFIin;
1465 MMI = &MMIin;
1466 FnVarLocs = VarLocs;
1467}
1468
1470 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1471 allnodes_clear();
1472 OperandRecycler.clear(OperandAllocator);
1473 delete DbgInfo;
1474}
1475
1477 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1478}
1479
1480void SelectionDAG::allnodes_clear() {
1481 assert(&*AllNodes.begin() == &EntryNode);
1482 AllNodes.remove(AllNodes.begin());
1483 while (!AllNodes.empty())
1484 DeallocateNode(&AllNodes.front());
1485#ifndef NDEBUG
1486 NextPersistentId = 0;
1487#endif
1488}
1489
1490SDNode *SelectionDAG::lookupNode(const FoldingSetNodeID &ID,
1491 FoldingSetInsertToken &InsertToken) {
1492 SDNode *N = CSEMap.lookup(ID, InsertToken);
1493 if (N) {
1494 switch (N->getOpcode()) {
1495 default: break;
1496 case ISD::Constant:
1497 case ISD::ConstantFP:
1498 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1499 "debug location. Use another overload.");
1500 }
1501 }
1502 return N;
1503}
1504
1505SDNode *SelectionDAG::lookupNode(const FoldingSetNodeID &ID, const SDLoc &DL,
1506 FoldingSetInsertToken &InsertToken) {
1507 SDNode *N = CSEMap.lookup(ID, InsertToken);
1508 if (N) {
1509 switch (N->getOpcode()) {
1510 case ISD::Constant:
1511 case ISD::ConstantFP:
1512 // Erase debug location from the node if the node is used at several
1513 // different places. Do not propagate one location to all uses as it
1514 // will cause a worse single stepping debugging experience.
1515 if (N->getDebugLoc() != DL.getDebugLoc())
1516 N->setDebugLoc(DebugLoc());
1517 break;
1518 default:
1519 // When the node's point of use is located earlier in the instruction
1520 // sequence than its prior point of use, update its debug info to the
1521 // earlier location.
1522 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1523 N->setDebugLoc(DL.getDebugLoc());
1524 break;
1525 }
1526 }
1527 return N;
1528}
1529
1531 allnodes_clear();
1532 OperandRecycler.clear(OperandAllocator);
1533 OperandAllocator.Reset();
1534 CSEMap.clear();
1535
1536 ExtendedValueTypeNodes.clear();
1537 ExternalSymbols.clear();
1538 TargetExternalSymbols.clear();
1539 MCSymbols.clear();
1540 SDEI.clear();
1541 llvm::fill(CondCodeNodes, nullptr);
1542 llvm::fill(ValueTypeNodes, nullptr);
1543
1544 EntryNode.UseList = nullptr;
1545 InsertNode(&EntryNode);
1546 Root = getEntryNode();
1547 DbgInfo->clear();
1548}
1549
1551 return VT.bitsGT(Op.getValueType())
1552 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1553 : getNode(ISD::FP_ROUND, DL, VT, Op,
1554 getIntPtrConstant(0, DL, /*isTarget=*/true));
1555}
1556
1557std::pair<SDValue, SDValue>
1559 const SDLoc &DL, EVT VT) {
1560 assert(!VT.bitsEq(Op.getValueType()) &&
1561 "Strict no-op FP extend/round not allowed.");
1562 SDValue Res =
1563 VT.bitsGT(Op.getValueType())
1564 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1565 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1566 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1567
1568 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1569}
1570
1572 return VT.bitsGT(Op.getValueType()) ?
1573 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1574 getNode(ISD::TRUNCATE, DL, VT, Op);
1575}
1576
1578 return VT.bitsGT(Op.getValueType()) ?
1579 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1580 getNode(ISD::TRUNCATE, DL, VT, Op);
1581}
1582
1584 return VT.bitsGT(Op.getValueType()) ?
1585 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1586 getNode(ISD::TRUNCATE, DL, VT, Op);
1587}
1588
1590 EVT VT) {
1591 assert(!VT.isVector());
1592 auto Type = Op.getValueType();
1593 SDValue DestOp;
1594 if (Type == VT)
1595 return Op;
1596 auto Size = Op.getValueSizeInBits();
1597 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1598 if (DestOp.getValueType() == VT)
1599 return DestOp;
1600
1601 return getAnyExtOrTrunc(DestOp, DL, VT);
1602}
1603
1605 EVT VT) {
1606 assert(!VT.isVector());
1607 auto Type = Op.getValueType();
1608 SDValue DestOp;
1609 if (Type == VT)
1610 return Op;
1611 auto Size = Op.getValueSizeInBits();
1612 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1613 if (DestOp.getValueType() == VT)
1614 return DestOp;
1615
1616 return getSExtOrTrunc(DestOp, DL, VT);
1617}
1618
1620 EVT VT) {
1621 assert(!VT.isVector());
1622 auto Type = Op.getValueType();
1623 SDValue DestOp;
1624 if (Type == VT)
1625 return Op;
1626 auto Size = Op.getValueSizeInBits();
1627 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1628 if (DestOp.getValueType() == VT)
1629 return DestOp;
1630
1631 return getZExtOrTrunc(DestOp, DL, VT);
1632}
1633
1635 EVT OpVT) {
1636 if (VT.bitsLE(Op.getValueType()))
1637 return getNode(ISD::TRUNCATE, SL, VT, Op);
1638
1639 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1640 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1641}
1642
1644 EVT OpVT = Op.getValueType();
1645 assert(VT.isInteger() && OpVT.isInteger() &&
1646 "Cannot getZeroExtendInReg FP types");
1647 assert(VT.isVector() == OpVT.isVector() &&
1648 "getZeroExtendInReg type should be vector iff the operand "
1649 "type is vector!");
1650 assert((!VT.isVector() ||
1652 "Vector element counts must match in getZeroExtendInReg");
1653 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1654 if (OpVT == VT)
1655 return Op;
1656 // TODO: Use computeKnownBits instead of AssertZext.
1657 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1658 ->getVT()
1659 .getScalarType()
1660 .bitsLE(VT.getScalarType()))
1661 return Op;
1663 VT.getScalarSizeInBits());
1664 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1665}
1666
1668 // Only unsigned pointer semantics are supported right now. In the future this
1669 // might delegate to TLI to check pointer signedness.
1670 return getZExtOrTrunc(Op, DL, VT);
1671}
1672
1674 // Only unsigned pointer semantics are supported right now. In the future this
1675 // might delegate to TLI to check pointer signedness.
1676 return getZeroExtendInReg(Op, DL, VT);
1677}
1678
1680 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1681}
1682
1683/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1685 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1686}
1687
1689 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1690 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1691}
1692
1694 EVT OpVT) {
1695 if (!V)
1696 return getConstant(0, DL, VT);
1697
1698 switch (TLI->getBooleanContents(OpVT)) {
1701 return getConstant(1, DL, VT);
1703 return getAllOnesConstant(DL, VT);
1704 }
1705 llvm_unreachable("Unexpected boolean content enum!");
1706}
1707
1709 bool isT, bool isO) {
1710 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1711 DL, VT, isT, isO);
1712}
1713
1715 bool isT, bool isO) {
1716 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1717}
1718
1720 EVT VT, bool isT, bool isO) {
1721 assert(VT.isInteger() && "Cannot create FP integer constant!");
1722
1723 EVT EltVT = VT.getScalarType();
1724 const ConstantInt *Elt = &Val;
1725
1726 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1727 // to-be-splatted scalar ConstantInt.
1728 if (isa<VectorType>(Elt->getType()))
1729 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1730
1731 // In some cases the vector type is legal but the element type is illegal and
1732 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1733 // inserted value (the type does not need to match the vector element type).
1734 // Any extra bits introduced will be truncated away.
1735 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1737 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1738 APInt NewVal;
1739 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1740 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1741 else
1742 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1743 Elt = ConstantInt::get(*getContext(), NewVal);
1744 }
1745 // In other cases the element type is illegal and needs to be expanded, for
1746 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1747 // the value into n parts and use a vector type with n-times the elements.
1748 // Then bitcast to the type requested.
1749 // Legalizing constants too early makes the DAGCombiner's job harder so we
1750 // only legalize if the DAG tells us we must produce legal types.
1751 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1752 TLI->getTypeAction(*getContext(), EltVT) ==
1754 const APInt &NewVal = Elt->getValue();
1755 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1756 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1757
1758 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1759 if (VT.isScalableVector() ||
1760 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1761 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1762 "Can only handle an even split!");
1763 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1764
1765 SmallVector<SDValue, 2> ScalarParts;
1766 for (unsigned i = 0; i != Parts; ++i)
1767 ScalarParts.push_back(getConstant(
1768 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1769 ViaEltVT, isT, isO));
1770
1771 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1772 }
1773
1774 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1775 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1776
1777 // Check the temporary vector is the correct size. If this fails then
1778 // getTypeToTransformTo() probably returned a type whose size (in bits)
1779 // isn't a power-of-2 factor of the requested type size.
1780 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1781
1782 SmallVector<SDValue, 2> EltParts;
1783 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1784 EltParts.push_back(getConstant(
1785 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1786 ViaEltVT, isT, isO));
1787
1788 // EltParts is currently in little endian order. If we actually want
1789 // big-endian order then reverse it now.
1790 if (getDataLayout().isBigEndian())
1791 std::reverse(EltParts.begin(), EltParts.end());
1792
1793 // The elements must be reversed when the element order is different
1794 // to the endianness of the elements (because the BITCAST is itself a
1795 // vector shuffle in this situation). However, we do not need any code to
1796 // perform this reversal because getConstant() is producing a vector
1797 // splat.
1798 // This situation occurs in MIPS MSA.
1799
1801 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1802 llvm::append_range(Ops, EltParts);
1803
1804 SDValue V =
1805 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1806 return V;
1807 }
1808
1809 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1810 "APInt size does not match type size!");
1811 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1812 SDVTList VTs = getVTList(EltVT);
1814 AddNodeIDNode(ID, Opc, VTs, {});
1815 ID.AddPointer(Elt);
1816 ID.AddBoolean(isO);
1817 FoldingSetInsertToken InsertToken;
1818 SDNode *N = nullptr;
1819 if ((N = lookupNode(ID, DL, InsertToken)))
1820 if (!VT.isVector())
1821 return SDValue(N, 0);
1822
1823 if (!N) {
1824 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1825 if (!isT)
1826 N->setDebugLoc(DL.getDebugLoc());
1827 CSEMap.insert(N, InsertToken);
1828 InsertNode(N);
1829 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1830 }
1831
1832 SDValue Result(N, 0);
1833 if (VT.isVector())
1834 Result = getSplat(VT, DL, Result);
1835 return Result;
1836}
1837
1839 bool isT, bool isO) {
1840 unsigned Size = VT.getScalarSizeInBits();
1841 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1842}
1843
1845 bool IsOpaque) {
1847 IsTarget, IsOpaque);
1848}
1849
1851 bool isTarget) {
1852 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1853}
1854
1856 const SDLoc &DL) {
1857 assert(VT.isInteger() && "Shift amount is not an integer type!");
1858 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1859 return getConstant(Val, DL, ShiftVT);
1860}
1861
1863 const SDLoc &DL) {
1864 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1865 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1866}
1867
1869 bool isTarget) {
1870 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1871}
1872
1874 bool isTarget) {
1875 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1876}
1877
1879 EVT VT, bool isTarget) {
1880 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1881
1882 EVT EltVT = VT.getScalarType();
1883 const ConstantFP *Elt = &V;
1884
1885 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1886 // the to-be-splatted scalar ConstantFP.
1887 if (isa<VectorType>(Elt->getType()))
1888 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1889
1890 // Do the map lookup using the actual bit pattern for the floating point
1891 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1892 // we don't have issues with SNANs.
1893 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1894 SDVTList VTs = getVTList(EltVT);
1896 AddNodeIDNode(ID, Opc, VTs, {});
1897 ID.AddPointer(Elt);
1898 FoldingSetInsertToken InsertToken;
1899 SDNode *N = nullptr;
1900 if ((N = lookupNode(ID, DL, InsertToken)))
1901 if (!VT.isVector())
1902 return SDValue(N, 0);
1903
1904 if (!N) {
1905 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1906 CSEMap.insert(N, InsertToken);
1907 InsertNode(N);
1908 }
1909
1910 SDValue Result(N, 0);
1911 if (VT.isVector())
1912 Result = getSplat(VT, DL, Result);
1913 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1914 return Result;
1915}
1916
1918 bool isTarget) {
1919 EVT EltVT = VT.getScalarType();
1920 if (EltVT == MVT::f32)
1921 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1922 if (EltVT == MVT::f64)
1923 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1924 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1925 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1926 bool Ignored;
1927 APFloat APF = APFloat(Val);
1929 &Ignored);
1930 return getConstantFP(APF, DL, VT, isTarget);
1931 }
1932 llvm_unreachable("Unsupported type in getConstantFP");
1933}
1934
1936 EVT VT, int64_t Offset, bool isTargetGA,
1937 unsigned TargetFlags) {
1938 assert((TargetFlags == 0 || isTargetGA) &&
1939 "Cannot set target flags on target-independent globals");
1940
1941 // Truncate (with sign-extension) the offset value to the pointer size.
1943 if (BitWidth < 64)
1945
1946 unsigned Opc;
1947 if (GV->isThreadLocal())
1949 else
1951
1952 SDVTList VTs = getVTList(VT);
1954 AddNodeIDNode(ID, Opc, VTs, {});
1955 ID.AddPointer(GV);
1956 ID.AddInteger(Offset);
1957 ID.AddInteger(TargetFlags);
1958 FoldingSetInsertToken InsertToken;
1959 if (SDNode *E = lookupNode(ID, DL, InsertToken))
1960 return SDValue(E, 0);
1961
1962 auto *N = newSDNode<GlobalAddressSDNode>(
1963 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1964 CSEMap.insert(N, InsertToken);
1965 InsertNode(N);
1966 return SDValue(N, 0);
1967}
1968
1970 SDVTList VTs = getVTList(MVT::Untyped);
1973 ID.AddPointer(GV);
1974 FoldingSetInsertToken InsertToken;
1975 if (SDNode *E = lookupNode(ID, SDLoc(), InsertToken))
1976 return SDValue(E, 0);
1977
1978 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1979 CSEMap.insert(N, InsertToken);
1980 InsertNode(N);
1981 return SDValue(N, 0);
1982}
1983
1984SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1985 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1986 SDVTList VTs = getVTList(VT);
1988 AddNodeIDNode(ID, Opc, VTs, {});
1989 ID.AddInteger(FI);
1990 FoldingSetInsertToken InsertToken;
1991 if (SDNode *E = lookupNode(ID, InsertToken))
1992 return SDValue(E, 0);
1993
1994 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1995 CSEMap.insert(N, InsertToken);
1996 InsertNode(N);
1997 return SDValue(N, 0);
1998}
1999
2000SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
2001 unsigned TargetFlags) {
2002 assert((TargetFlags == 0 || isTarget) &&
2003 "Cannot set target flags on target-independent jump tables");
2004 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
2005 SDVTList VTs = getVTList(VT);
2007 AddNodeIDNode(ID, Opc, VTs, {});
2008 ID.AddInteger(JTI);
2009 ID.AddInteger(TargetFlags);
2010 FoldingSetInsertToken InsertToken;
2011 if (SDNode *E = lookupNode(ID, InsertToken))
2012 return SDValue(E, 0);
2013
2014 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
2015 CSEMap.insert(N, InsertToken);
2016 InsertNode(N);
2017 return SDValue(N, 0);
2018}
2019
2021 const SDLoc &DL) {
2023 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2024 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2025}
2026
2028 MaybeAlign Alignment, int Offset,
2029 bool isTarget, unsigned TargetFlags) {
2030 assert((TargetFlags == 0 || isTarget) &&
2031 "Cannot set target flags on target-independent globals");
2032 if (!Alignment)
2033 Alignment = shouldOptForSize()
2034 ? getDataLayout().getABITypeAlign(C->getType())
2035 : getDataLayout().getPrefTypeAlign(C->getType());
2036 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2037 SDVTList VTs = getVTList(VT);
2039 AddNodeIDNode(ID, Opc, VTs, {});
2040 ID.AddInteger(Alignment->value());
2041 ID.AddInteger(Offset);
2042 ID.AddPointer(C);
2043 ID.AddInteger(TargetFlags);
2044 FoldingSetInsertToken InsertToken;
2045 if (SDNode *E = lookupNode(ID, InsertToken))
2046 return SDValue(E, 0);
2047
2048 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2049 TargetFlags);
2050 CSEMap.insert(N, InsertToken);
2051 InsertNode(N);
2052 SDValue V = SDValue(N, 0);
2053 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2054 return V;
2055}
2056
2058 MaybeAlign Alignment, int Offset,
2059 bool isTarget, unsigned TargetFlags) {
2060 assert((TargetFlags == 0 || isTarget) &&
2061 "Cannot set target flags on target-independent globals");
2062 if (!Alignment)
2063 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2064 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2065 SDVTList VTs = getVTList(VT);
2067 AddNodeIDNode(ID, Opc, VTs, {});
2068 ID.AddInteger(Alignment->value());
2069 ID.AddInteger(Offset);
2070 C->addSelectionDAGCSEId(ID);
2071 ID.AddInteger(TargetFlags);
2072 FoldingSetInsertToken InsertToken;
2073 if (SDNode *E = lookupNode(ID, InsertToken))
2074 return SDValue(E, 0);
2075
2076 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2077 TargetFlags);
2078 CSEMap.insert(N, InsertToken);
2079 InsertNode(N);
2080 return SDValue(N, 0);
2081}
2082
2085 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), {});
2086 ID.AddPointer(MBB);
2087 FoldingSetInsertToken InsertToken;
2088 if (SDNode *E = lookupNode(ID, InsertToken))
2089 return SDValue(E, 0);
2090
2091 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2092 CSEMap.insert(N, InsertToken);
2093 InsertNode(N);
2094 return SDValue(N, 0);
2095}
2096
2098 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2099 ValueTypeNodes.size())
2100 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2101
2102 SDNode *&N = VT.isExtended() ?
2103 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2104
2105 if (N) return SDValue(N, 0);
2106 N = newSDNode<VTSDNode>(VT);
2107 InsertNode(N);
2108 return SDValue(N, 0);
2109}
2110
2112 SDNode *&N = ExternalSymbols[Sym];
2113 if (N) return SDValue(N, 0);
2114 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2115 InsertNode(N);
2116 return SDValue(N, 0);
2117}
2118
2119SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2121 return getExternalSymbol(SymName.data(), VT);
2122}
2123
2125 SDNode *&N = MCSymbols[Sym];
2126 if (N)
2127 return SDValue(N, 0);
2128 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2129 InsertNode(N);
2130 return SDValue(N, 0);
2131}
2132
2134 unsigned TargetFlags) {
2135 SDNode *&N =
2136 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2137 if (N) return SDValue(N, 0);
2138 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2139 InsertNode(N);
2140 return SDValue(N, 0);
2141}
2142
2144 EVT VT, unsigned TargetFlags) {
2146 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2147}
2148
2150 if ((unsigned)Cond >= CondCodeNodes.size())
2151 CondCodeNodes.resize(Cond+1);
2152
2153 if (!CondCodeNodes[Cond]) {
2154 auto *N = newSDNode<CondCodeSDNode>(Cond);
2155 CondCodeNodes[Cond] = N;
2156 InsertNode(N);
2157 }
2158
2159 return SDValue(CondCodeNodes[Cond], 0);
2160}
2161
2163 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2164 "APInt size does not match type size!");
2165
2166 if (MulImm == 0)
2167 return getConstant(0, DL, VT);
2168
2169 const MachineFunction &MF = getMachineFunction();
2170 const Function &F = MF.getFunction();
2171 ConstantRange CR = getVScaleRange(&F, 64);
2172 if (const APInt *C = CR.getSingleElement())
2173 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2174
2175 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2176}
2177
2178/// \returns a value of type \p VT that represents the runtime value of \p
2179/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2180/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2181/// or TypeSize.
2182template <typename Ty>
2184 EVT VT, Ty Quantity) {
2185 if (Quantity.isScalable())
2186 return DAG.getVScale(
2187 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2188
2189 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2190}
2191
2193 ElementCount EC) {
2194 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2195}
2196
2198 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2199}
2200
2202 ElementCount EC) {
2203 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2204 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2205 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2206 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2207}
2208
2210 APInt One(ResVT.getScalarSizeInBits(), 1);
2211 return getStepVector(DL, ResVT, One);
2212}
2213
2215 const APInt &StepVal) {
2216 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2217 if (ResVT.isScalableVector())
2218 return getNode(
2219 ISD::STEP_VECTOR, DL, ResVT,
2220 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2221
2222 SmallVector<SDValue, 16> OpsStepConstants;
2223 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2224 OpsStepConstants.push_back(
2225 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2226 return getBuildVector(ResVT, DL, OpsStepConstants);
2227}
2228
2229/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2230/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2235
2237 SDValue N2, ArrayRef<int> Mask) {
2238 assert(VT.getVectorNumElements() == Mask.size() &&
2239 "Must have the same number of vector elements as mask elements!");
2240 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2241 "Invalid VECTOR_SHUFFLE");
2242
2243 // Canonicalize shuffle undef, undef -> undef
2244 if (N1.isUndef() && N2.isUndef()) {
2245 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2246 return getPOISON(VT);
2247 return getUNDEF(VT);
2248 }
2249
2250 // Validate that all indices in Mask are within the range of the elements
2251 // input to the shuffle.
2252 int NElts = Mask.size();
2253 assert(llvm::all_of(Mask,
2254 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2255 "Index out of range");
2256
2257 // Copy the mask so we can do any needed cleanup.
2258 SmallVector<int, 8> MaskVec(Mask);
2259
2260 // Canonicalize shuffle v, v -> v, poison
2261 if (N1 == N2) {
2262 N2 = getPOISON(VT);
2263 for (int i = 0; i != NElts; ++i)
2264 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2265 }
2266
2267 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2268 if (N1.isUndef())
2269 commuteShuffle(N1, N2, MaskVec);
2270
2271 if (TLI->hasVectorBlend()) {
2272 // If shuffling a splat, try to blend the splat instead. We do this here so
2273 // that even when this arises during lowering we don't have to re-handle it.
2274 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2275 BitVector UndefElements;
2276 SDValue Splat = BV->getSplatValue(&UndefElements);
2277 if (!Splat)
2278 return;
2279
2280 for (int i = 0; i < NElts; ++i) {
2281 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2282 continue;
2283
2284 // If this input comes from undef, mark it as such.
2285 if (UndefElements[MaskVec[i] - Offset]) {
2286 MaskVec[i] = -1;
2287 continue;
2288 }
2289
2290 // If we can blend a non-undef lane, use that instead.
2291 if (!UndefElements[i])
2292 MaskVec[i] = i + Offset;
2293 }
2294 };
2295 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2296 BlendSplat(N1BV, 0);
2297 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2298 BlendSplat(N2BV, NElts);
2299 }
2300
2301 // Canonicalize all index into lhs, -> shuffle lhs, poison
2302 // Canonicalize all index into rhs, -> shuffle rhs, poison
2303 bool AllLHS = true, AllRHS = true;
2304 bool N2Undef = N2.isUndef();
2305 for (int i = 0; i != NElts; ++i) {
2306 if (MaskVec[i] >= NElts) {
2307 if (N2Undef)
2308 MaskVec[i] = -1;
2309 else
2310 AllLHS = false;
2311 } else if (MaskVec[i] >= 0) {
2312 AllRHS = false;
2313 }
2314 }
2315 if (AllLHS && AllRHS)
2316 return getPOISON(VT);
2317 if (AllLHS && !N2Undef)
2318 N2 = getPOISON(VT);
2319 if (AllRHS) {
2320 N1 = getPOISON(VT);
2321 commuteShuffle(N1, N2, MaskVec);
2322 }
2323 // Reset our undef status after accounting for the mask.
2324 N2Undef = N2.isUndef();
2325 // Re-check whether both sides ended up undef.
2326 if (N1.isUndef() && N2Undef) {
2327 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2328 return getPOISON(VT);
2329 return getUNDEF(VT);
2330 }
2331
2332 // If Identity shuffle return that node.
2333 bool Identity = true, AllSame = true;
2334 for (int i = 0; i != NElts; ++i) {
2335 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2336 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2337 }
2338 if (Identity && NElts)
2339 return N1;
2340
2341 // Shuffling a constant splat doesn't change the result.
2342 if (N2Undef) {
2343 SDValue V = N1;
2344
2345 // Look through any bitcasts. We check that these don't change the number
2346 // (and size) of elements and just changes their types.
2347 while (V.getOpcode() == ISD::BITCAST)
2348 V = V->getOperand(0);
2349
2350 // A splat should always show up as a build vector node.
2351 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2352 BitVector UndefElements;
2353 SDValue Splat = BV->getSplatValue(&UndefElements);
2354 // If this is a splat of an undef, shuffling it is also undef.
2355 if (Splat && Splat.isUndef())
2356 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2357
2358 bool SameNumElts =
2359 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2360
2361 // We only have a splat which can skip shuffles if there is a splatted
2362 // value and no undef lanes rearranged by the shuffle.
2363 if (Splat && UndefElements.none()) {
2364 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2365 // number of elements match or the value splatted is a zero constant.
2366 if (SameNumElts || isNullConstant(Splat))
2367 return N1;
2368 }
2369
2370 // If the shuffle itself creates a splat, build the vector directly.
2371 if (AllSame && SameNumElts) {
2372 EVT BuildVT = BV->getValueType(0);
2373 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2374 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2375
2376 // We may have jumped through bitcasts, so the type of the
2377 // BUILD_VECTOR may not match the type of the shuffle.
2378 if (BuildVT != VT)
2379 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2380 return NewBV;
2381 }
2382 }
2383 }
2384
2385 SDVTList VTs = getVTList(VT);
2387 SDValue Ops[2] = { N1, N2 };
2389 for (int i = 0; i != NElts; ++i)
2390 ID.AddInteger(MaskVec[i]);
2391
2392 FoldingSetInsertToken InsertToken;
2393 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2394 return SDValue(E, 0);
2395
2396 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2397 // SDNode doesn't have access to it. This memory will be "leaked" when
2398 // the node is deallocated, but recovered when the NodeAllocator is released.
2399 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2400 llvm::copy(MaskVec, MaskAlloc);
2401
2402 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2403 dl.getDebugLoc(), MaskAlloc);
2404 createOperands(N, Ops);
2405
2406 CSEMap.insert(N, InsertToken);
2407 InsertNode(N);
2408 SDValue V = SDValue(N, 0);
2409 NewSDValueDbgMsg(V, "Creating new node: ", this);
2410 return V;
2411}
2412
2414 EVT VT = SV.getValueType(0);
2415 SmallVector<int, 8> MaskVec(SV.getMask());
2417
2418 SDValue Op0 = SV.getOperand(0);
2419 SDValue Op1 = SV.getOperand(1);
2420 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2421}
2422
2424 SDVTList VTs = getVTList(VT);
2426 AddNodeIDNode(ID, ISD::Register, VTs, {});
2427 ID.AddInteger(Reg.id());
2428 FoldingSetInsertToken InsertToken;
2429 if (SDNode *E = lookupNode(ID, InsertToken))
2430 return SDValue(E, 0);
2431
2432 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2433 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2434 CSEMap.insert(N, InsertToken);
2435 InsertNode(N);
2436 return SDValue(N, 0);
2437}
2438
2441 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), {});
2442 ID.AddPointer(RegMask);
2443 FoldingSetInsertToken InsertToken;
2444 if (SDNode *E = lookupNode(ID, InsertToken))
2445 return SDValue(E, 0);
2446
2447 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2448 CSEMap.insert(N, InsertToken);
2449 InsertNode(N);
2450 return SDValue(N, 0);
2451}
2452
2454 MCSymbol *Label) {
2455 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2456}
2457
2458SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2459 SDValue Root, MCSymbol *Label) {
2461 SDValue Ops[] = { Root };
2462 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2463 ID.AddPointer(Label);
2464 FoldingSetInsertToken InsertToken;
2465 if (SDNode *E = lookupNode(ID, InsertToken))
2466 return SDValue(E, 0);
2467
2468 auto *N =
2469 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2470 createOperands(N, Ops);
2471
2472 CSEMap.insert(N, InsertToken);
2473 InsertNode(N);
2474 return SDValue(N, 0);
2475}
2476
2478 int64_t Offset, bool isTarget,
2479 unsigned TargetFlags) {
2480 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2481 SDVTList VTs = getVTList(VT);
2482
2484 AddNodeIDNode(ID, Opc, VTs, {});
2485 ID.AddPointer(BA);
2486 ID.AddInteger(Offset);
2487 ID.AddInteger(TargetFlags);
2488 FoldingSetInsertToken InsertToken;
2489 if (SDNode *E = lookupNode(ID, InsertToken))
2490 return SDValue(E, 0);
2491
2492 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2493 CSEMap.insert(N, InsertToken);
2494 InsertNode(N);
2495 return SDValue(N, 0);
2496}
2497
2500 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), {});
2501 ID.AddPointer(V);
2502
2503 FoldingSetInsertToken InsertToken;
2504 if (SDNode *E = lookupNode(ID, InsertToken))
2505 return SDValue(E, 0);
2506
2507 auto *N = newSDNode<SrcValueSDNode>(V);
2508 CSEMap.insert(N, InsertToken);
2509 InsertNode(N);
2510 return SDValue(N, 0);
2511}
2512
2515 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2516 ID.AddPointer(MD);
2517
2518 FoldingSetInsertToken InsertToken;
2519 if (SDNode *E = lookupNode(ID, InsertToken))
2520 return SDValue(E, 0);
2521
2522 auto *N = newSDNode<MDNodeSDNode>(MD);
2523 CSEMap.insert(N, InsertToken);
2524 InsertNode(N);
2525 return SDValue(N, 0);
2526}
2527
2529 if (VT == V.getValueType())
2530 return V;
2531
2532 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2533}
2534
2536 unsigned SrcAS, unsigned DestAS) {
2537 SDVTList VTs = getVTList(VT);
2538 SDValue Ops[] = {Ptr};
2541 ID.AddInteger(SrcAS);
2542 ID.AddInteger(DestAS);
2543
2544 FoldingSetInsertToken InsertToken;
2545 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2546 return SDValue(E, 0);
2547
2548 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2549 VTs, SrcAS, DestAS);
2550 createOperands(N, Ops);
2551
2552 CSEMap.insert(N, InsertToken);
2553 InsertNode(N);
2554 return SDValue(N, 0);
2555}
2556
2558 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2559}
2560
2562 UndefPoisonKind Kind) {
2563 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2564 return V;
2565 return getFreeze(V);
2566}
2567
2568/// getShiftAmountOperand - Return the specified value casted to
2569/// the target's desired shift amount type.
2571 EVT OpTy = Op.getValueType();
2572 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2573 if (OpTy == ShTy || OpTy.isVector()) return Op;
2574
2575 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2576}
2577
2579 SDLoc dl(Node);
2581 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2582 EVT VT = Node->getValueType(0);
2583 SDValue Tmp1 = Node->getOperand(0);
2584 SDValue Tmp2 = Node->getOperand(1);
2585 const MaybeAlign MA(Node->getConstantOperandVal(3));
2586
2587 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2588 Tmp2, MachinePointerInfo(V));
2589 SDValue VAList = VAListLoad;
2590
2591 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2592 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2593 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2594
2595 VAList = getNode(
2596 ISD::AND, dl, VAList.getValueType(), VAList,
2597 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2598 }
2599
2600 // Increment the pointer, VAList, to the next vaarg
2601 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2602 getConstant(getDataLayout().getTypeAllocSize(
2603 VT.getTypeForEVT(*getContext())),
2604 dl, VAList.getValueType()));
2605 // Store the incremented VAList to the legalized pointer
2606 Tmp1 =
2607 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2608 // Load the actual argument out of the pointer VAList
2609 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2610}
2611
2613 SDLoc dl(Node);
2615 // This defaults to loading a pointer from the input and storing it to the
2616 // output, returning the chain.
2617 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2618 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2619 SDValue Tmp1 =
2620 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2621 Node->getOperand(2), MachinePointerInfo(VS));
2622 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2623 MachinePointerInfo(VD));
2624}
2625
2627 const DataLayout &DL = getDataLayout();
2628 Type *Ty = VT.getTypeForEVT(*getContext());
2629 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2630
2631 if (TLI->isTypeLegal(VT) || !VT.isVector())
2632 return RedAlign;
2633
2634 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2635 const Align StackAlign = TFI->getStackAlign();
2636
2637 // See if we can choose a smaller ABI alignment in cases where it's an
2638 // illegal vector type that will get broken down.
2639 if (RedAlign > StackAlign) {
2640 EVT IntermediateVT;
2641 MVT RegisterVT;
2642 unsigned NumIntermediates;
2643 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2644 NumIntermediates, RegisterVT);
2645 Ty = IntermediateVT.getTypeForEVT(*getContext());
2646 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2647 if (RedAlign2 < RedAlign)
2648 RedAlign = RedAlign2;
2649
2650 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2651 // If the stack is not realignable, the alignment should be limited to the
2652 // StackAlignment
2653 RedAlign = std::min(RedAlign, StackAlign);
2654 }
2655
2656 return RedAlign;
2657}
2658
2660 MachineFrameInfo &MFI = MF->getFrameInfo();
2661 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2662 int StackID = 0;
2663 if (Bytes.isScalable())
2664 StackID = TFI->getStackIDForScalableVectors();
2665 // The stack id gives an indication of whether the object is scalable or
2666 // not, so it's safe to pass in the minimum size here.
2667 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2668 false, nullptr, StackID);
2669 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2670}
2671
2673 Type *Ty = VT.getTypeForEVT(*getContext());
2674 Align StackAlign =
2675 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2676 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2677}
2678
2680 TypeSize VT1Size = VT1.getStoreSize();
2681 TypeSize VT2Size = VT2.getStoreSize();
2682 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2683 "Don't know how to choose the maximum size when creating a stack "
2684 "temporary");
2685 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2686 ? VT1Size
2687 : VT2Size;
2688
2689 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2690 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2691 const DataLayout &DL = getDataLayout();
2692 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2693 return CreateStackTemporary(Bytes, Align);
2694}
2695
2697 ISD::CondCode Cond, const SDLoc &dl,
2698 SDNodeFlags Flags) {
2699 EVT OpVT = N1.getValueType();
2700
2701 auto GetUndefBooleanConstant = [&]() {
2702 if (VT.getScalarType() == MVT::i1 ||
2703 TLI->getBooleanContents(OpVT) ==
2705 return getUNDEF(VT);
2706 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2707 // so we cannot use getUNDEF(). Return zero instead.
2708 return getConstant(0, dl, VT);
2709 };
2710
2711 // These setcc operations always fold.
2712 switch (Cond) {
2713 default: break;
2714 case ISD::SETFALSE:
2715 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2716 case ISD::SETTRUE:
2717 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2718
2719 case ISD::SETOEQ:
2720 case ISD::SETOGT:
2721 case ISD::SETOGE:
2722 case ISD::SETOLT:
2723 case ISD::SETOLE:
2724 case ISD::SETONE:
2725 case ISD::SETO:
2726 case ISD::SETUO:
2727 case ISD::SETUEQ:
2728 case ISD::SETUNE:
2729 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2730 break;
2731 }
2732
2733 if (OpVT.isInteger()) {
2734 // For EQ and NE, we can always pick a value for the undef to make the
2735 // predicate pass or fail, so we can return undef.
2736 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2737 // icmp eq/ne X, undef -> undef.
2738 if ((N1.isUndef() || N2.isUndef()) &&
2739 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2740 return GetUndefBooleanConstant();
2741
2742 // If both operands are undef, we can return undef for int comparison.
2743 // icmp undef, undef -> undef.
2744 if (N1.isUndef() && N2.isUndef())
2745 return GetUndefBooleanConstant();
2746
2747 // icmp X, X -> true/false
2748 // icmp X, undef -> true/false because undef could be X.
2749 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2750 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2751 }
2752
2754 const APInt &C2 = N2C->getAPIntValue();
2756 const APInt &C1 = N1C->getAPIntValue();
2757
2759 dl, VT, OpVT);
2760 }
2761 }
2762
2763 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2764 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2765
2766 if (N1CFP && N2CFP) {
2767 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2768 switch (Cond) {
2769 default: break;
2770 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2771 return GetUndefBooleanConstant();
2772 [[fallthrough]];
2773 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2774 OpVT);
2775 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2776 return GetUndefBooleanConstant();
2777 [[fallthrough]];
2779 R==APFloat::cmpLessThan, dl, VT,
2780 OpVT);
2781 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2782 return GetUndefBooleanConstant();
2783 [[fallthrough]];
2784 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2785 OpVT);
2786 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2787 return GetUndefBooleanConstant();
2788 [[fallthrough]];
2790 VT, OpVT);
2791 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2792 return GetUndefBooleanConstant();
2793 [[fallthrough]];
2795 R==APFloat::cmpEqual, dl, VT,
2796 OpVT);
2797 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2798 return GetUndefBooleanConstant();
2799 [[fallthrough]];
2801 R==APFloat::cmpEqual, dl, VT, OpVT);
2802 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2803 OpVT);
2804 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2805 OpVT);
2807 R==APFloat::cmpEqual, dl, VT,
2808 OpVT);
2809 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2810 OpVT);
2812 R==APFloat::cmpLessThan, dl, VT,
2813 OpVT);
2815 R==APFloat::cmpUnordered, dl, VT,
2816 OpVT);
2818 VT, OpVT);
2819 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2820 OpVT);
2821 }
2822 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2823 // Ensure that the constant occurs on the RHS.
2825 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2826 return SDValue();
2827 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2828 /*IsSignaling=*/false, Flags);
2829 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2830 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2831 // If an operand is known to be a nan (or undef that could be a nan), we can
2832 // fold it.
2833 // Choosing NaN for the undef will always make unordered comparison succeed
2834 // and ordered comparison fails.
2835 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2836 switch (ISD::getUnorderedFlavor(Cond)) {
2837 default:
2838 llvm_unreachable("Unknown flavor!");
2839 case 0: // Known false.
2840 return getBoolConstant(false, dl, VT, OpVT);
2841 case 1: // Known true.
2842 return getBoolConstant(true, dl, VT, OpVT);
2843 case 2: // Undefined.
2844 return GetUndefBooleanConstant();
2845 }
2846 }
2847
2848 // Could not fold it.
2849 return SDValue();
2850}
2851
2852/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2853/// use this predicate to simplify operations downstream.
2855 unsigned BitWidth = Op.getScalarValueSizeInBits();
2857}
2858
2859// TODO: Should have argument to specify if sign bit of nan is ignorable.
2861 if (Depth >= MaxRecursionDepth)
2862 return false; // Limit search depth.
2863
2864 unsigned Opc = Op.getOpcode();
2865 switch (Opc) {
2866 case ISD::FABS:
2867 return true;
2868 case ISD::AssertNoFPClass: {
2869 FPClassTest NoFPClass =
2870 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2871
2872 const FPClassTest TestMask = fcNan | fcNegative;
2873 return (NoFPClass & TestMask) == TestMask;
2874 }
2875 case ISD::ARITH_FENCE:
2876 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2877 case ISD::FEXP:
2878 case ISD::FEXP2:
2879 case ISD::FEXP10:
2880 return Op->getFlags().hasNoNaNs();
2881 case ISD::FMINNUM:
2882 case ISD::FMINNUM_IEEE:
2883 case ISD::FMINIMUM:
2884 case ISD::FMINIMUMNUM:
2885 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2886 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2887 case ISD::FMAXNUM:
2888 case ISD::FMAXNUM_IEEE:
2889 case ISD::FMAXIMUM:
2890 case ISD::FMAXIMUMNUM:
2891 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2892 // is sufficient.
2893 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2894 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2895 default:
2896 return false;
2897 }
2898
2899 llvm_unreachable("covered opcode switch");
2900}
2901
2902/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2903/// this predicate to simplify operations downstream. Mask is known to be zero
2904/// for bits that V cannot have.
2906 unsigned Depth) const {
2907 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2908}
2909
2910/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2911/// DemandedElts. We use this predicate to simplify operations downstream.
2912/// Mask is known to be zero for bits that V cannot have.
2914 const APInt &DemandedElts,
2915 unsigned Depth) const {
2916 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2917}
2918
2919/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2920/// DemandedElts. We use this predicate to simplify operations downstream.
2922 unsigned Depth /* = 0 */) const {
2923 return computeKnownBits(V, DemandedElts, Depth).isZero();
2924}
2925
2926/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2928 unsigned Depth) const {
2929 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2930}
2931
2933 const APInt &DemandedElts,
2934 unsigned Depth) const {
2935 EVT VT = Op.getValueType();
2936 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2937
2938 unsigned NumElts = VT.getVectorNumElements();
2939 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2940
2941 APInt KnownZeroElements = APInt::getZero(NumElts);
2942 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2943 if (!DemandedElts[EltIdx])
2944 continue; // Don't query elements that are not demanded.
2945 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2946 if (MaskedVectorIsZero(Op, Mask, Depth))
2947 KnownZeroElements.setBit(EltIdx);
2948 }
2949 return KnownZeroElements;
2950}
2951
2952/// isSplatValue - Return true if the vector V has the same value
2953/// across all DemandedElts. For scalable vectors, we don't know the
2954/// number of lanes at compile time. Instead, we use a 1 bit APInt
2955/// to represent a conservative value for all lanes; that is, that
2956/// one bit value is implicitly splatted across all lanes.
2957bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2958 APInt &UndefElts, unsigned Depth) const {
2959 unsigned Opcode = V.getOpcode();
2960 EVT VT = V.getValueType();
2961 assert(VT.isVector() && "Vector type expected");
2962 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2963 "scalable demanded bits are ignored");
2964
2965 if (!DemandedElts)
2966 return false; // No demanded elts, better to assume we don't know anything.
2967
2968 if (Depth >= MaxRecursionDepth)
2969 return false; // Limit search depth.
2970
2971 // Deal with some common cases here that work for both fixed and scalable
2972 // vector types.
2973 switch (Opcode) {
2974 case ISD::SPLAT_VECTOR:
2975 UndefElts = V.getOperand(0).isUndef()
2976 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2977 : APInt(DemandedElts.getBitWidth(), 0);
2978 return true;
2979 case ISD::ADD:
2980 case ISD::SUB:
2981 case ISD::AND:
2982 case ISD::XOR:
2983 case ISD::OR: {
2984 APInt UndefLHS, UndefRHS;
2985 SDValue LHS = V.getOperand(0);
2986 SDValue RHS = V.getOperand(1);
2987 // Only recognize splats with the same demanded undef elements for both
2988 // operands, otherwise we might fail to handle binop-specific undef
2989 // handling.
2990 // e.g. (and undef, 0) -> 0 etc.
2991 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2992 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2993 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2994 UndefElts = UndefLHS | UndefRHS;
2995 return true;
2996 }
2997 return false;
2998 }
2999 case ISD::ABS:
3001 case ISD::TRUNCATE:
3002 case ISD::SIGN_EXTEND:
3003 case ISD::ZERO_EXTEND:
3004 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3005 default:
3006 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3007 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3008 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3009 Depth);
3010 break;
3011 }
3012
3013 // We don't support other cases than those above for scalable vectors at
3014 // the moment.
3015 if (VT.isScalableVector())
3016 return false;
3017
3018 unsigned NumElts = VT.getVectorNumElements();
3019 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3020 UndefElts = APInt::getZero(NumElts);
3021
3022 switch (Opcode) {
3023 case ISD::BUILD_VECTOR: {
3024 SDValue Scl;
3025 for (unsigned i = 0; i != NumElts; ++i) {
3026 SDValue Op = V.getOperand(i);
3027 if (Op.isUndef()) {
3028 UndefElts.setBit(i);
3029 continue;
3030 }
3031 if (!DemandedElts[i])
3032 continue;
3033 if (Scl && Scl != Op)
3034 return false;
3035 Scl = Op;
3036 }
3037 return true;
3038 }
3039 case ISD::VECTOR_SHUFFLE: {
3040 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3041 APInt DemandedLHS = APInt::getZero(NumElts);
3042 APInt DemandedRHS = APInt::getZero(NumElts);
3043 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3044 for (int i = 0; i != (int)NumElts; ++i) {
3045 int M = Mask[i];
3046 if (M < 0) {
3047 UndefElts.setBit(i);
3048 continue;
3049 }
3050 if (!DemandedElts[i])
3051 continue;
3052 if (M < (int)NumElts)
3053 DemandedLHS.setBit(M);
3054 else
3055 DemandedRHS.setBit(M - NumElts);
3056 }
3057
3058 // If we aren't demanding either op, assume there's no splat.
3059 // If we are demanding both ops, assume there's no splat.
3060 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3061 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3062 return false;
3063
3064 // See if the demanded elts of the source op is a splat or we only demand
3065 // one element, which should always be a splat.
3066 // TODO: Handle source ops splats with undefs.
3067 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3068 APInt SrcUndefs;
3069 return (SrcElts.popcount() == 1) ||
3070 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3071 (SrcElts & SrcUndefs).isZero());
3072 };
3073 if (!DemandedLHS.isZero())
3074 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3075 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3076 }
3078 // Offset the demanded elts by the subvector index.
3079 SDValue Src = V.getOperand(0);
3080 // We don't support scalable vectors at the moment.
3081 if (Src.getValueType().isScalableVector())
3082 return false;
3083 uint64_t Idx = V.getConstantOperandVal(1);
3084 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3085 APInt UndefSrcElts;
3086 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3087 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3088 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3089 return true;
3090 }
3091 break;
3092 }
3096 // Widen the demanded elts by the src element count.
3097 SDValue Src = V.getOperand(0);
3098 // We don't support scalable vectors at the moment.
3099 if (Src.getValueType().isScalableVector())
3100 return false;
3101 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3102 APInt UndefSrcElts;
3103 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3104 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3105 UndefElts = UndefSrcElts.trunc(NumElts);
3106 return true;
3107 }
3108 break;
3109 }
3110 case ISD::BITCAST: {
3111 SDValue Src = V.getOperand(0);
3112 EVT SrcVT = Src.getValueType();
3113 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3114 unsigned BitWidth = VT.getScalarSizeInBits();
3115
3116 // Ignore bitcasts from unsupported types.
3117 // TODO: Add fp support?
3118 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3119 break;
3120
3121 // Bitcast 'small element' vector to 'large element' vector.
3122 if ((BitWidth % SrcBitWidth) == 0) {
3123 // See if each sub element is a splat.
3124 unsigned Scale = BitWidth / SrcBitWidth;
3125 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3126 APInt ScaledDemandedElts =
3127 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3128 for (unsigned I = 0; I != Scale; ++I) {
3129 APInt SubUndefElts;
3130 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3131 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3132 SubDemandedElts &= ScaledDemandedElts;
3133 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3134 return false;
3135 // TODO: Add support for merging sub undef elements.
3136 if (!SubUndefElts.isZero())
3137 return false;
3138 }
3139 return true;
3140 }
3141 break;
3142 }
3143 }
3144
3145 return false;
3146}
3147
3148/// Helper wrapper to main isSplatValue function.
3149bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3150 EVT VT = V.getValueType();
3151 assert(VT.isVector() && "Vector type expected");
3152
3153 APInt UndefElts;
3154 // Since the number of lanes in a scalable vector is unknown at compile time,
3155 // we track one bit which is implicitly broadcast to all lanes. This means
3156 // that all lanes in a scalable vector are considered demanded.
3157 APInt DemandedElts
3159 return isSplatValue(V, DemandedElts, UndefElts) &&
3160 (AllowUndefs || !UndefElts);
3161}
3162
3165
3166 EVT VT = V.getValueType();
3167 unsigned Opcode = V.getOpcode();
3168 switch (Opcode) {
3169 default: {
3170 APInt UndefElts;
3171 // Since the number of lanes in a scalable vector is unknown at compile time,
3172 // we track one bit which is implicitly broadcast to all lanes. This means
3173 // that all lanes in a scalable vector are considered demanded.
3174 APInt DemandedElts
3176
3177 if (isSplatValue(V, DemandedElts, UndefElts)) {
3178 if (VT.isScalableVector()) {
3179 // DemandedElts and UndefElts are ignored for scalable vectors, since
3180 // the only supported cases are SPLAT_VECTOR nodes.
3181 SplatIdx = 0;
3182 } else {
3183 // Handle case where all demanded elements are UNDEF.
3184 if (DemandedElts.isSubsetOf(UndefElts)) {
3185 SplatIdx = 0;
3186 return getUNDEF(VT);
3187 }
3188 SplatIdx = (UndefElts & DemandedElts).countr_one();
3189 }
3190 return V;
3191 }
3192 break;
3193 }
3194 case ISD::SPLAT_VECTOR:
3195 SplatIdx = 0;
3196 return V;
3197 case ISD::VECTOR_SHUFFLE: {
3198 assert(!VT.isScalableVector());
3199 // Check if this is a shuffle node doing a splat.
3200 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3201 // getTargetVShiftNode currently struggles without the splat source.
3202 auto *SVN = cast<ShuffleVectorSDNode>(V);
3203 if (!SVN->isSplat())
3204 break;
3205 int Idx = SVN->getSplatIndex();
3206 int NumElts = V.getValueType().getVectorNumElements();
3207 SplatIdx = Idx % NumElts;
3208 return V.getOperand(Idx / NumElts);
3209 }
3210 }
3211
3212 return SDValue();
3213}
3214
3216 int SplatIdx;
3217 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3218 EVT SVT = SrcVector.getValueType().getScalarType();
3219 EVT LegalSVT = SVT;
3220 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3221 if (!SVT.isInteger())
3222 return SDValue();
3223 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3224 if (LegalSVT.bitsLT(SVT))
3225 return SDValue();
3226 }
3227 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3228 }
3229 return SDValue();
3230}
3231
3232std::optional<ConstantRange>
3234 unsigned Depth) const {
3235 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3236 V.getOpcode() == ISD::SRA) &&
3237 "Unknown shift node");
3238 // Shifting more than the bitwidth is not valid.
3239 unsigned BitWidth = V.getScalarValueSizeInBits();
3240
3241 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3242 const APInt &ShAmt = Cst->getAPIntValue();
3243 if (ShAmt.uge(BitWidth))
3244 return std::nullopt;
3245 return ConstantRange(ShAmt);
3246 }
3247
3248 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3249 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3250 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3251 if (!DemandedElts[i])
3252 continue;
3253 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3254 if (!SA) {
3255 MinAmt = MaxAmt = nullptr;
3256 break;
3257 }
3258 const APInt &ShAmt = SA->getAPIntValue();
3259 if (ShAmt.uge(BitWidth))
3260 return std::nullopt;
3261 if (!MinAmt || MinAmt->ugt(ShAmt))
3262 MinAmt = &ShAmt;
3263 if (!MaxAmt || MaxAmt->ult(ShAmt))
3264 MaxAmt = &ShAmt;
3265 }
3266 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3267 "Failed to find matching min/max shift amounts");
3268 if (MinAmt && MaxAmt)
3269 return ConstantRange(*MinAmt, *MaxAmt + 1);
3270 }
3271
3272 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3273 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3274 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3275 if (KnownAmt.getMaxValue().ult(BitWidth))
3276 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3277
3278 return std::nullopt;
3279}
3280
3281std::optional<unsigned>
3283 unsigned Depth) const {
3284 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3285 V.getOpcode() == ISD::SRA) &&
3286 "Unknown shift node");
3287 if (std::optional<ConstantRange> AmtRange =
3288 getValidShiftAmountRange(V, DemandedElts, Depth))
3289 if (const APInt *ShAmt = AmtRange->getSingleElement())
3290 return ShAmt->getZExtValue();
3291 return std::nullopt;
3292}
3293
3294std::optional<unsigned>
3296 APInt DemandedElts = getDemandAllEltsMask(V);
3297 return getValidShiftAmount(V, DemandedElts, Depth);
3298}
3299
3300std::optional<unsigned>
3302 unsigned Depth) const {
3303 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3304 V.getOpcode() == ISD::SRA) &&
3305 "Unknown shift node");
3306 if (std::optional<ConstantRange> AmtRange =
3307 getValidShiftAmountRange(V, DemandedElts, Depth))
3308 return AmtRange->getUnsignedMin().getZExtValue();
3309 return std::nullopt;
3310}
3311
3312std::optional<unsigned>
3314 APInt DemandedElts = getDemandAllEltsMask(V);
3315 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3316}
3317
3318std::optional<unsigned>
3320 unsigned Depth) const {
3321 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3322 V.getOpcode() == ISD::SRA) &&
3323 "Unknown shift node");
3324 if (std::optional<ConstantRange> AmtRange =
3325 getValidShiftAmountRange(V, DemandedElts, Depth))
3326 return AmtRange->getUnsignedMax().getZExtValue();
3327 return std::nullopt;
3328}
3329
3330std::optional<unsigned>
3332 APInt DemandedElts = getDemandAllEltsMask(V);
3333 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3334}
3335
3336/// Determine which bits of Op are known to be either zero or one and return
3337/// them in Known. For vectors, the known bits are those that are shared by
3338/// every vector element.
3340 APInt DemandedElts = getDemandAllEltsMask(Op);
3341 return computeKnownBits(Op, DemandedElts, Depth);
3342}
3343
3344/// Determine which bits of Op are known to be either zero or one and return
3345/// them in Known. The DemandedElts argument allows us to only collect the known
3346/// bits that are shared by the requested vector elements.
3348 unsigned Depth) const {
3349 unsigned BitWidth = Op.getScalarValueSizeInBits();
3350
3351 KnownBits Known(BitWidth); // Don't know anything.
3352
3353 if (auto OptAPInt = Op->bitcastToAPInt()) {
3354 // We know all of the bits for a constant!
3355 return KnownBits::makeConstant(*std::move(OptAPInt));
3356 }
3357
3358 if (Depth >= MaxRecursionDepth)
3359 return Known; // Limit search depth.
3360
3361 KnownBits Known2;
3362 unsigned NumElts = DemandedElts.getBitWidth();
3363 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3364 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3365 assert((!Op.getValueType().isFixedLengthVector() ||
3366 NumElts == Op.getValueType().getVectorNumElements()) &&
3367 "Unexpected vector size");
3368
3369 if (!DemandedElts)
3370 return Known; // No demanded elts, better to assume we don't know anything.
3371
3372 unsigned Opcode = Op.getOpcode();
3373 switch (Opcode) {
3374 case ISD::FREEZE: {
3375 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3377 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3378 break;
3379 }
3380 case ISD::MERGE_VALUES:
3381 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3382 Depth + 1);
3383 case ISD::SPLAT_VECTOR: {
3384 SDValue SrcOp = Op.getOperand(0);
3385 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3386 "Expected SPLAT_VECTOR implicit truncation");
3387 // Implicitly truncate the bits to match the official semantics of
3388 // SPLAT_VECTOR.
3390 break;
3391 }
3393 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3394 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3395 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3396 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3397 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3398 }
3399 break;
3400 }
3401 case ISD::STEP_VECTOR: {
3402 const APInt &Step = Op.getConstantOperandAPInt(0);
3403
3404 if (Step.isPowerOf2())
3405 Known.Zero.setLowBits(Step.logBase2());
3406
3408
3409 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3410 break;
3411 const APInt MinNumElts =
3412 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3413
3414 bool Overflow;
3415 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3417 .umul_ov(MinNumElts, Overflow);
3418 if (Overflow)
3419 break;
3420
3421 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3422 if (Overflow)
3423 break;
3424
3425 Known.Zero.setHighBits(MaxValue.countl_zero());
3426 break;
3427 }
3428 case ISD::BUILD_VECTOR:
3429 assert(!Op.getValueType().isScalableVector());
3430 // Collect the known bits that are shared by every demanded vector element.
3431 Known.setAllConflict();
3432 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3433 if (!DemandedElts[i])
3434 continue;
3435
3436 SDValue SrcOp = Op.getOperand(i);
3437 if (SrcOp.getOpcode() == ISD::POISON)
3438 continue;
3439
3440 Known2 = computeKnownBits(SrcOp, Depth + 1);
3441
3442 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3443 if (SrcOp.getValueSizeInBits() != BitWidth) {
3444 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3445 "Expected BUILD_VECTOR implicit truncation");
3446 Known2 = Known2.trunc(BitWidth);
3447 }
3448
3449 // Known bits are the values that are shared by every demanded element.
3450 Known = Known.intersectWith(Known2);
3451
3452 // If we don't know any bits, early out.
3453 if (Known.isUnknown())
3454 break;
3455 }
3456
3457 // If every demanded element was poison, we know nothing.
3458 if (Known.hasConflict())
3459 Known.resetAll();
3460 break;
3461 case ISD::VECTOR_COMPRESS: {
3462 SDValue Vec = Op.getOperand(0);
3463 SDValue PassThru = Op.getOperand(2);
3464 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3465 // If we don't know any bits, early out.
3466 if (Known.isUnknown())
3467 break;
3468 Known2 = computeKnownBits(Vec, Depth + 1);
3469 Known = Known.intersectWith(Known2);
3470 break;
3471 }
3472 case ISD::VECTOR_SHUFFLE: {
3473 assert(!Op.getValueType().isScalableVector());
3474 // Collect the known bits that are shared by every vector element referenced
3475 // by the shuffle.
3476 APInt DemandedLHS, DemandedRHS;
3478 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3479 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3480 DemandedLHS, DemandedRHS))
3481 break;
3482
3483 // Known bits are the values that are shared by every demanded element.
3484 Known.setAllConflict();
3485 if (!!DemandedLHS) {
3486 SDValue LHS = Op.getOperand(0);
3487 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3488 Known = Known.intersectWith(Known2);
3489 }
3490 // If we don't know any bits, early out.
3491 if (Known.isUnknown())
3492 break;
3493 if (!!DemandedRHS) {
3494 SDValue RHS = Op.getOperand(1);
3495 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3496 Known = Known.intersectWith(Known2);
3497 }
3498 break;
3499 }
3500 case ISD::VSCALE: {
3502 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3504 break;
3505 }
3506 case ISD::CONCAT_VECTORS: {
3507 if (Op.getValueType().isScalableVector())
3508 break;
3509 // Split DemandedElts and test each of the demanded subvectors.
3510 Known.setAllConflict();
3511 EVT SubVectorVT = Op.getOperand(0).getValueType();
3512 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3513 unsigned NumSubVectors = Op.getNumOperands();
3514 for (unsigned i = 0; i != NumSubVectors; ++i) {
3515 APInt DemandedSub =
3516 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3517 if (!!DemandedSub) {
3518 SDValue Sub = Op.getOperand(i);
3519 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3520 Known = Known.intersectWith(Known2);
3521 }
3522 // If we don't know any bits, early out.
3523 if (Known.isUnknown())
3524 break;
3525 }
3526 break;
3527 }
3528 case ISD::INSERT_SUBVECTOR: {
3529 if (Op.getValueType().isScalableVector())
3530 break;
3531 // Demand any elements from the subvector and the remainder from the src its
3532 // inserted into.
3533 SDValue Src = Op.getOperand(0);
3534 SDValue Sub = Op.getOperand(1);
3535 uint64_t Idx = Op.getConstantOperandVal(2);
3536 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3537 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3538 APInt DemandedSrcElts = DemandedElts;
3539 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3540
3541 Known.setAllConflict();
3542 if (!!DemandedSubElts) {
3543 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3544 if (Known.isUnknown())
3545 break; // early-out.
3546 }
3547 if (!!DemandedSrcElts) {
3548 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3549 Known = Known.intersectWith(Known2);
3550 }
3551 break;
3552 }
3554 // Offset the demanded elts by the subvector index.
3555 SDValue Src = Op.getOperand(0);
3556
3557 APInt DemandedSrcElts;
3558 if (Src.getValueType().isScalableVector())
3559 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3560 else {
3561 uint64_t Idx = Op.getConstantOperandVal(1);
3562 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3563 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3564 }
3565 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3566 break;
3567 }
3568 case ISD::SCALAR_TO_VECTOR: {
3569 if (Op.getValueType().isScalableVector())
3570 break;
3571 // We know about scalar_to_vector as much as we know about it source,
3572 // which becomes the first element of otherwise unknown vector.
3573 if (DemandedElts != 1)
3574 break;
3575
3576 SDValue N0 = Op.getOperand(0);
3577 Known = computeKnownBits(N0, Depth + 1);
3578 if (N0.getValueSizeInBits() != BitWidth)
3579 Known = Known.trunc(BitWidth);
3580
3581 break;
3582 }
3583 case ISD::BITCAST: {
3584 if (Op.getValueType().isScalableVector())
3585 break;
3586
3587 SDValue N0 = Op.getOperand(0);
3588 EVT SubVT = N0.getValueType();
3589 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3590
3591 // Ignore bitcasts from unsupported types.
3592 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3593 break;
3594
3595 // Fast handling of 'identity' bitcasts.
3596 if (BitWidth == SubBitWidth) {
3597 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3598 break;
3599 }
3600
3601 bool IsLE = getDataLayout().isLittleEndian();
3602
3603 // Bitcast 'small element' vector to 'large element' scalar/vector.
3604 if ((BitWidth % SubBitWidth) == 0) {
3605 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3606
3607 // Collect known bits for the (larger) output by collecting the known
3608 // bits from each set of sub elements and shift these into place.
3609 // We need to separately call computeKnownBits for each set of
3610 // sub elements as the knownbits for each is likely to be different.
3611 unsigned SubScale = BitWidth / SubBitWidth;
3612 APInt SubDemandedElts(NumElts * SubScale, 0);
3613 for (unsigned i = 0; i != NumElts; ++i)
3614 if (DemandedElts[i])
3615 SubDemandedElts.setBit(i * SubScale);
3616
3617 for (unsigned i = 0; i != SubScale; ++i) {
3618 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3619 Depth + 1);
3620 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3621 Known.insertBits(Known2, SubBitWidth * Shifts);
3622 }
3623 }
3624
3625 // Bitcast 'large element' scalar/vector to 'small element' vector.
3626 if ((SubBitWidth % BitWidth) == 0) {
3627 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3628
3629 // Collect known bits for the (smaller) output by collecting the known
3630 // bits from the overlapping larger input elements and extracting the
3631 // sub sections we actually care about.
3632 unsigned SubScale = SubBitWidth / BitWidth;
3633 APInt SubDemandedElts =
3634 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3635 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3636
3637 Known.setAllConflict();
3638 for (unsigned i = 0; i != NumElts; ++i)
3639 if (DemandedElts[i]) {
3640 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3641 unsigned Offset = (Shifts % SubScale) * BitWidth;
3642 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3643 // If we don't know any bits, early out.
3644 if (Known.isUnknown())
3645 break;
3646 }
3647 }
3648 break;
3649 }
3650 case ISD::AND:
3651 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3652 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3653
3654 Known &= Known2;
3655 break;
3656 case ISD::OR:
3657 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3658 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3659
3660 Known |= Known2;
3661 break;
3662 case ISD::XOR:
3663 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3664 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3665
3666 Known ^= Known2;
3667 break;
3668 case ISD::MUL: {
3669 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3670 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3671 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3672 // TODO: SelfMultiply can be poison, but not undef.
3673 if (SelfMultiply)
3674 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3675 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3676 Depth + 1);
3677 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3678
3679 // If the multiplication is known not to overflow, the product of a number
3680 // with itself is non-negative. Only do this if we didn't already computed
3681 // the opposite value for the sign bit.
3682 if (Op->getFlags().hasNoSignedWrap() &&
3683 Op.getOperand(0) == Op.getOperand(1) &&
3684 !Known.isNegative())
3685 Known.makeNonNegative();
3686 break;
3687 }
3688 case ISD::MULHU: {
3689 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3690 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3691 Known = KnownBits::mulhu(Known, Known2);
3692 break;
3693 }
3694 case ISD::MULHS: {
3695 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3696 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3697 Known = KnownBits::mulhs(Known, Known2);
3698 break;
3699 }
3700 case ISD::ABDU: {
3701 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3702 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3703 Known = KnownBits::abdu(Known, Known2);
3704 break;
3705 }
3706 case ISD::ABDS: {
3707 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3708 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3709 Known = KnownBits::abds(Known, Known2);
3710 unsigned SignBits1 =
3711 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3712 if (SignBits1 == 1)
3713 break;
3714 unsigned SignBits0 =
3715 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3716 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3717 break;
3718 }
3719 case ISD::UMUL_LOHI: {
3720 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3721 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3722 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3723 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3724 if (Op.getResNo() == 0)
3725 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3726 else
3727 Known = KnownBits::mulhu(Known, Known2);
3728 break;
3729 }
3730 case ISD::SMUL_LOHI: {
3731 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3732 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3733 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3734 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3735 if (Op.getResNo() == 0)
3736 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3737 else
3738 Known = KnownBits::mulhs(Known, Known2);
3739 break;
3740 }
3741 case ISD::AVGFLOORU: {
3742 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3743 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3744 Known = KnownBits::avgFloorU(Known, Known2);
3745 break;
3746 }
3747 case ISD::AVGCEILU: {
3748 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3749 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3750 Known = KnownBits::avgCeilU(Known, Known2);
3751 break;
3752 }
3753 case ISD::AVGFLOORS: {
3754 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3755 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3756 Known = KnownBits::avgFloorS(Known, Known2);
3757 break;
3758 }
3759 case ISD::AVGCEILS: {
3760 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3761 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3762 Known = KnownBits::avgCeilS(Known, Known2);
3763 break;
3764 }
3765 case ISD::SELECT:
3766 case ISD::VSELECT:
3767 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3768 // If we don't know any bits, early out.
3769 if (Known.isUnknown())
3770 break;
3771 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3772
3773 // Only known if known in both the LHS and RHS.
3774 Known = Known.intersectWith(Known2);
3775 break;
3776 case ISD::SELECT_CC:
3777 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3778 // If we don't know any bits, early out.
3779 if (Known.isUnknown())
3780 break;
3781 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3782
3783 // Only known if known in both the LHS and RHS.
3784 Known = Known.intersectWith(Known2);
3785 break;
3786 case ISD::SMULO:
3787 case ISD::UMULO:
3788 if (Op.getResNo() != 1)
3789 break;
3790 // The boolean result conforms to getBooleanContents.
3791 // If we know the result of a setcc has the top bits zero, use this info.
3792 // We know that we have an integer-based boolean since these operations
3793 // are only available for integer.
3794 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3796 BitWidth > 1)
3797 Known.Zero.setBitsFrom(1);
3798 break;
3799 case ISD::SETCC:
3800 case ISD::SETCCCARRY:
3801 case ISD::STRICT_FSETCC:
3802 case ISD::STRICT_FSETCCS: {
3803 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3804 // If we know the result of a setcc has the top bits zero, use this info.
3805 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3807 BitWidth > 1)
3808 Known.Zero.setBitsFrom(1);
3809 break;
3810 }
3811 case ISD::SHL: {
3812 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3813 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3814
3815 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3816 bool NSW = Op->getFlags().hasNoSignedWrap();
3817
3818 bool ShAmtNonZero = Known2.isNonZero();
3819
3820 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3821
3822 // Minimum shift low bits are known zero.
3823 if (std::optional<unsigned> ShMinAmt =
3824 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3825 Known.Zero.setLowBits(*ShMinAmt);
3826 break;
3827 }
3828 case ISD::SRL:
3829 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3830 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3831 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3832 Op->getFlags().hasExact());
3833
3834 // Minimum shift high bits are known zero.
3835 if (std::optional<unsigned> ShMinAmt =
3836 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3837 Known.Zero.setHighBits(*ShMinAmt);
3838 break;
3839 case ISD::SRA:
3840 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3841 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3842 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3843 Op->getFlags().hasExact());
3844 break;
3845 case ISD::ROTL:
3846 case ISD::ROTR:
3847 if (ConstantSDNode *C =
3848 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3849 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3850
3851 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3852
3853 // Canonicalize to ROTR.
3854 if (Opcode == ISD::ROTL && Amt != 0)
3855 Amt = BitWidth - Amt;
3856
3857 Known.Zero = Known.Zero.rotr(Amt);
3858 Known.One = Known.One.rotr(Amt);
3859 }
3860 break;
3861 case ISD::FSHL:
3862 case ISD::FSHR:
3863 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3864 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3865
3866 // For fshl, 0-shift returns the 1st arg.
3867 // For fshr, 0-shift returns the 2nd arg.
3868 if (Amt == 0) {
3869 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3870 DemandedElts, Depth + 1);
3871 break;
3872 }
3873
3874 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3875 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3876 const APInt ShAmt(BitWidth, Amt);
3877 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3878 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3879 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3880 : KnownBits::fshr(Known, Known2, ShAmt);
3881 }
3882 break;
3883 case ISD::SHL_PARTS:
3884 case ISD::SRA_PARTS:
3885 case ISD::SRL_PARTS: {
3886 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3887
3888 // Collect lo/hi source values and concatenate.
3889 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3890 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3891 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3892 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3893 Known = Known2.concat(Known);
3894
3895 // Collect shift amount.
3896 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3897
3898 if (Opcode == ISD::SHL_PARTS)
3899 Known = KnownBits::shl(Known, Known2);
3900 else if (Opcode == ISD::SRA_PARTS)
3901 Known = KnownBits::ashr(Known, Known2);
3902 else // if (Opcode == ISD::SRL_PARTS)
3903 Known = KnownBits::lshr(Known, Known2);
3904
3905 // TODO: Minimum shift low/high bits are known zero.
3906
3907 if (Op.getResNo() == 0)
3908 Known = Known.extractBits(LoBits, 0);
3909 else
3910 Known = Known.extractBits(HiBits, LoBits);
3911 break;
3912 }
3914 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3915 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3916 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3917 break;
3918 }
3919 case ISD::CTTZ:
3920 case ISD::CTTZ_ZERO_POISON: {
3921 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3922 // If we have a known 1, its position is our upper bound.
3923 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3924 unsigned LowBits = llvm::bit_width(PossibleTZ);
3925 Known.Zero.setBitsFrom(LowBits);
3926 break;
3927 }
3928 case ISD::CTLZ:
3929 case ISD::CTLZ_ZERO_POISON: {
3930 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3931 // If we have a known 1, its position is our upper bound.
3932 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3933 unsigned LowBits = llvm::bit_width(PossibleLZ);
3934 Known.Zero.setBitsFrom(LowBits);
3935 break;
3936 }
3937 case ISD::CTLS: {
3938 unsigned MinRedundantSignBits =
3939 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3940 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3942 Known = Range.toKnownBits();
3943 break;
3944 }
3945 case ISD::CTPOP: {
3946 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3947 // If we know some of the bits are zero, they can't be one.
3948 unsigned PossibleOnes = Known2.countMaxPopulation();
3949 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3950 break;
3951 }
3952 case ISD::PARITY: {
3953 // Parity returns 0 everywhere but the LSB.
3954 Known.Zero.setBitsFrom(1);
3955 break;
3956 }
3957 case ISD::PDEP: {
3958 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3959 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3960 Known = KnownBits::pdep(Known2, Known);
3961 break;
3962 }
3963 case ISD::PEXT: {
3964 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3965 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3966 Known = KnownBits::pext(Known2, Known);
3967 break;
3968 }
3969 case ISD::CLMUL: {
3970 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3971 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3972 Known = KnownBits::clmul(Known, Known2);
3973 break;
3974 }
3975 case ISD::MGATHER:
3976 case ISD::MLOAD: {
3977 ISD::LoadExtType ETy =
3978 (Opcode == ISD::MGATHER)
3979 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3980 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3981 if (ETy == ISD::ZEXTLOAD) {
3982 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3983 KnownBits Known0(MemVT.getScalarSizeInBits());
3984 return Known0.zext(BitWidth);
3985 }
3986 break;
3987 }
3988 case ISD::LOAD: {
3990 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3991 if (ISD::isNON_EXTLoad(LD) && Cst) {
3992 // Determine any common known bits from the loaded constant pool value.
3993 Type *CstTy = Cst->getType();
3994 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3995 !Op.getValueType().isScalableVector()) {
3996 // If its a vector splat, then we can (quickly) reuse the scalar path.
3997 // NOTE: We assume all elements match and none are UNDEF.
3998 if (CstTy->isVectorTy()) {
3999 if (const Constant *Splat = Cst->getSplatValue()) {
4000 Cst = Splat;
4001 CstTy = Cst->getType();
4002 }
4003 }
4004 // TODO - do we need to handle different bitwidths?
4005 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4006 // Iterate across all vector elements finding common known bits.
4007 Known.setAllConflict();
4008 for (unsigned i = 0; i != NumElts; ++i) {
4009 if (!DemandedElts[i])
4010 continue;
4011 if (Constant *Elt = Cst->getAggregateElement(i)) {
4012 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4013 const APInt &Value = CInt->getValue();
4014 Known.One &= Value;
4015 Known.Zero &= ~Value;
4016 continue;
4017 }
4018 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4019 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4020 Known.One &= Value;
4021 Known.Zero &= ~Value;
4022 continue;
4023 }
4024 }
4025 Known.One.clearAllBits();
4026 Known.Zero.clearAllBits();
4027 break;
4028 }
4029 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4030 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4031 Known = KnownBits::makeConstant(CInt->getValue());
4032 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4033 Known =
4034 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4035 }
4036 }
4037 }
4038 } else if (Op.getResNo() == 0) {
4039 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4040 KnownBits KnownScalarMemory(ScalarMemorySize);
4041 if (const MDNode *MD = LD->getRanges())
4042 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4043
4044 // Extend the Known bits from memory to the size of the scalar result.
4045 if (ISD::isZEXTLoad(Op.getNode()))
4046 Known = KnownScalarMemory.zext(BitWidth);
4047 else if (ISD::isSEXTLoad(Op.getNode()))
4048 Known = KnownScalarMemory.sext(BitWidth);
4049 else if (ISD::isEXTLoad(Op.getNode()))
4050 Known = KnownScalarMemory.anyext(BitWidth);
4051 else
4052 Known = KnownScalarMemory;
4053 assert(Known.getBitWidth() == BitWidth);
4054 return Known;
4055 }
4056 break;
4057 }
4059 if (Op.getValueType().isScalableVector())
4060 break;
4061 EVT InVT = Op.getOperand(0).getValueType();
4062 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4063 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4064 Known = Known.zext(BitWidth);
4065 break;
4066 }
4067 case ISD::ZERO_EXTEND: {
4068 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4069 Known = Known.zext(BitWidth);
4070 break;
4071 }
4073 if (Op.getValueType().isScalableVector())
4074 break;
4075 EVT InVT = Op.getOperand(0).getValueType();
4076 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4077 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4078 // If the sign bit is known to be zero or one, then sext will extend
4079 // it to the top bits, else it will just zext.
4080 Known = Known.sext(BitWidth);
4081 break;
4082 }
4083 case ISD::SIGN_EXTEND: {
4084 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4085 // If the sign bit is known to be zero or one, then sext will extend
4086 // it to the top bits, else it will just zext.
4087 Known = Known.sext(BitWidth);
4088 break;
4089 }
4091 if (Op.getValueType().isScalableVector())
4092 break;
4093 EVT InVT = Op.getOperand(0).getValueType();
4094 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4095 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4096 Known = Known.anyext(BitWidth);
4097 break;
4098 }
4099 case ISD::ANY_EXTEND: {
4100 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4101 Known = Known.anyext(BitWidth);
4102 break;
4103 }
4104 case ISD::TRUNCATE: {
4105 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4106 Known = Known.trunc(BitWidth);
4107 break;
4108 }
4109 case ISD::TRUNCATE_SSAT_S: {
4110 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4111 Known = Known.truncSSat(BitWidth);
4112 break;
4113 }
4114 case ISD::TRUNCATE_SSAT_U: {
4115 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4116 Known = Known.truncSSatU(BitWidth);
4117 break;
4118 }
4119 case ISD::TRUNCATE_USAT_U: {
4120 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4121 Known = Known.truncUSat(BitWidth);
4122 break;
4123 }
4124 case ISD::AssertZext: {
4125 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4127 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4128 Known.Zero |= (~InMask);
4129 Known.One &= (~Known.Zero);
4130 break;
4131 }
4132 case ISD::AssertAlign: {
4133 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4134 assert(LogOfAlign != 0);
4135
4136 // TODO: Should use maximum with source
4137 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4138 // well as clearing one bits.
4139 Known.Zero.setLowBits(LogOfAlign);
4140 Known.One.clearLowBits(LogOfAlign);
4141 break;
4142 }
4143 case ISD::AssertNoFPClass: {
4144 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4145
4146 FPClassTest NoFPClass =
4147 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4148 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4149 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4150 // Cannot be negative.
4151 Known.makeNonNegative();
4152 }
4153
4154 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4155 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4156 // Cannot be positive.
4157 Known.makeNegative();
4158 }
4159
4160 break;
4161 }
4162 case ISD::FABS:
4163 // fabs clears the sign bit
4164 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4165 Known.makeNonNegative();
4166 break;
4167 case ISD::FGETSIGN:
4168 // All bits are zero except the low bit.
4169 Known.Zero.setBitsFrom(1);
4170 break;
4171 case ISD::ADD: {
4172 SDNodeFlags Flags = Op.getNode()->getFlags();
4173 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4174 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4175 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4177 Op.getOperand(0), DemandedElts,
4179 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4180 Flags.hasNoUnsignedWrap(), SelfAdd);
4181 break;
4182 }
4183 case ISD::SUB: {
4184 SDNodeFlags Flags = Op.getNode()->getFlags();
4185 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4186 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4187 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4188 Flags.hasNoUnsignedWrap());
4189 break;
4190 }
4191 case ISD::USUBO:
4192 case ISD::SSUBO:
4193 case ISD::USUBO_CARRY:
4194 case ISD::SSUBO_CARRY:
4195 if (Op.getResNo() == 1) {
4196 // If we know the result of a setcc has the top bits zero, use this info.
4197 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4199 BitWidth > 1)
4200 Known.Zero.setBitsFrom(1);
4201 break;
4202 }
4203 [[fallthrough]];
4204 case ISD::SUBC: {
4205 assert(Op.getResNo() == 0 &&
4206 "We only compute knownbits for the difference here.");
4207
4208 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4209 KnownBits Borrow(1);
4210 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4211 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4212 // Borrow has bit width 1
4213 Borrow = Borrow.trunc(1);
4214 } else {
4215 Borrow.setAllZero();
4216 }
4217
4218 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4219 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4220 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4221 break;
4222 }
4223 case ISD::UADDO:
4224 case ISD::SADDO:
4225 case ISD::UADDO_CARRY:
4226 case ISD::SADDO_CARRY:
4227 if (Op.getResNo() == 1) {
4228 // If we know the result of a setcc has the top bits zero, use this info.
4229 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4231 BitWidth > 1)
4232 Known.Zero.setBitsFrom(1);
4233 break;
4234 }
4235 [[fallthrough]];
4236 case ISD::ADDC:
4237 case ISD::ADDE: {
4238 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4239
4240 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4241 KnownBits Carry(1);
4242 if (Opcode == ISD::ADDE)
4243 // Can't track carry from glue, set carry to unknown.
4244 Carry.resetAll();
4245 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4246 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4247 // Carry has bit width 1
4248 Carry = Carry.trunc(1);
4249 } else {
4250 Carry.setAllZero();
4251 }
4252
4253 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4254 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4255 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4256 break;
4257 }
4258 case ISD::UDIV: {
4259 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4260 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4261 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4262 break;
4263 }
4264 case ISD::SDIV: {
4265 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4266 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4267 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4268 break;
4269 }
4270 case ISD::SREM: {
4271 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4272 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4273 Known = KnownBits::srem(Known, Known2);
4274 break;
4275 }
4276 case ISD::UREM: {
4277 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4278 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4279 Known = KnownBits::urem(Known, Known2);
4280 break;
4281 }
4282 case ISD::EXTRACT_ELEMENT: {
4283 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4284 const unsigned Index = Op.getConstantOperandVal(1);
4285 const unsigned EltBitWidth = Op.getValueSizeInBits();
4286
4287 // Remove low part of known bits mask
4288 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4289 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4290
4291 // Remove high part of known bit mask
4292 Known = Known.trunc(EltBitWidth);
4293 break;
4294 }
4296 SDValue InVec = Op.getOperand(0);
4297 SDValue EltNo = Op.getOperand(1);
4298 EVT VecVT = InVec.getValueType();
4299 // computeKnownBits not yet implemented for scalable vectors.
4300 if (VecVT.isScalableVector())
4301 break;
4302 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4303 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4304
4305 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4306 // anything about the extended bits.
4307 if (BitWidth > EltBitWidth)
4308 Known = Known.trunc(EltBitWidth);
4309
4310 // If we know the element index, just demand that vector element, else for
4311 // an unknown element index, ignore DemandedElts and demand them all.
4312 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4313 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4314 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4315 DemandedSrcElts =
4316 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4317
4318 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4319 if (BitWidth > EltBitWidth)
4320 Known = Known.anyext(BitWidth);
4321 break;
4322 }
4324 if (Op.getValueType().isScalableVector())
4325 break;
4326
4327 // If we know the element index, split the demand between the
4328 // source vector and the inserted element, otherwise assume we need
4329 // the original demanded vector elements and the value.
4330 SDValue InVec = Op.getOperand(0);
4331 SDValue InVal = Op.getOperand(1);
4332 SDValue EltNo = Op.getOperand(2);
4333 bool DemandedVal = true;
4334 APInt DemandedVecElts = DemandedElts;
4335 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4336 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4337 unsigned EltIdx = CEltNo->getZExtValue();
4338 DemandedVal = !!DemandedElts[EltIdx];
4339 DemandedVecElts.clearBit(EltIdx);
4340 }
4341 Known.setAllConflict();
4342 if (DemandedVal) {
4343 Known2 = computeKnownBits(InVal, Depth + 1);
4344 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4345 }
4346 if (!!DemandedVecElts) {
4347 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4348 Known = Known.intersectWith(Known2);
4349 }
4350 break;
4351 }
4352 case ISD::BITREVERSE: {
4353 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4354 Known = Known2.reverseBits();
4355 break;
4356 }
4357 case ISD::BSWAP: {
4358 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4359 Known = Known2.byteSwap();
4360 break;
4361 }
4362 case ISD::ABS:
4363 case ISD::ABS_MIN_POISON: {
4364 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4365 Known = Known2.abs();
4366 Known.Zero.setHighBits(
4367 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4368 break;
4369 }
4370 case ISD::USUBSAT: {
4371 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4372 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4373 Known = KnownBits::usub_sat(Known, Known2);
4374 break;
4375 }
4376 case ISD::UMIN: {
4377 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4378 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4379 Known = KnownBits::umin(Known, Known2);
4380 break;
4381 }
4382 case ISD::UMAX: {
4383 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4384 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4385 Known = KnownBits::umax(Known, Known2);
4386 break;
4387 }
4388 case ISD::SMIN:
4389 case ISD::SMAX: {
4390 // If we have a clamp pattern, we know that the number of sign bits will be
4391 // the minimum of the clamp min/max range.
4392 bool IsMax = (Opcode == ISD::SMAX);
4393 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4394 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4395 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4396 CstHigh =
4397 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4398 if (CstLow && CstHigh) {
4399 if (!IsMax)
4400 std::swap(CstLow, CstHigh);
4401
4402 const APInt &ValueLow = CstLow->getAPIntValue();
4403 const APInt &ValueHigh = CstHigh->getAPIntValue();
4404 if (ValueLow.sle(ValueHigh)) {
4405 unsigned LowSignBits = ValueLow.getNumSignBits();
4406 unsigned HighSignBits = ValueHigh.getNumSignBits();
4407 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4408 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4409 Known.One.setHighBits(MinSignBits);
4410 break;
4411 }
4412 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4413 Known.Zero.setHighBits(MinSignBits);
4414 break;
4415 }
4416 }
4417 }
4418
4419 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4420 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4421 if (IsMax)
4422 Known = KnownBits::smax(Known, Known2);
4423 else
4424 Known = KnownBits::smin(Known, Known2);
4425
4426 // For SMAX, if CstLow is non-negative we know the result will be
4427 // non-negative and thus all sign bits are 0.
4428 // TODO: There's an equivalent of this for smin with negative constant for
4429 // known ones.
4430 if (IsMax && CstLow) {
4431 const APInt &ValueLow = CstLow->getAPIntValue();
4432 if (ValueLow.isNonNegative()) {
4433 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4434 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4435 }
4436 }
4437
4438 break;
4439 }
4440 case ISD::UINT_TO_FP: {
4441 Known.makeNonNegative();
4442 break;
4443 }
4444 case ISD::SINT_TO_FP: {
4445 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4446 if (Known2.isNonNegative())
4447 Known.makeNonNegative();
4448 else if (Known2.isNegative())
4449 Known.makeNegative();
4450 break;
4451 }
4452 case ISD::FP_TO_UINT_SAT: {
4453 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4454 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4456 break;
4457 }
4458 case ISD::ATOMIC_LOAD: {
4459 // If we are looking at the loaded value.
4460 if (Op.getResNo() == 0) {
4461 auto *AT = cast<AtomicSDNode>(Op);
4462 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4463 KnownBits KnownScalarMemory(ScalarMemorySize);
4464 if (const MDNode *MD = AT->getRanges())
4465 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4466
4467 switch (AT->getExtensionType()) {
4468 case ISD::ZEXTLOAD:
4469 Known = KnownScalarMemory.zext(BitWidth);
4470 break;
4471 case ISD::SEXTLOAD:
4472 Known = KnownScalarMemory.sext(BitWidth);
4473 break;
4474 case ISD::EXTLOAD:
4475 switch (TLI->getExtendForAtomicOps()) {
4476 case ISD::ZERO_EXTEND:
4477 Known = KnownScalarMemory.zext(BitWidth);
4478 break;
4479 case ISD::SIGN_EXTEND:
4480 Known = KnownScalarMemory.sext(BitWidth);
4481 break;
4482 default:
4483 Known = KnownScalarMemory.anyext(BitWidth);
4484 break;
4485 }
4486 break;
4487 case ISD::NON_EXTLOAD:
4488 Known = KnownScalarMemory;
4489 break;
4490 }
4491 assert(Known.getBitWidth() == BitWidth);
4492 }
4493 break;
4494 }
4496 if (Op.getResNo() == 1) {
4497 // The boolean result conforms to getBooleanContents.
4498 // If we know the result of a setcc has the top bits zero, use this info.
4499 // We know that we have an integer-based boolean since these operations
4500 // are only available for integer.
4501 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4503 BitWidth > 1)
4504 Known.Zero.setBitsFrom(1);
4505 break;
4506 }
4507 [[fallthrough]];
4509 case ISD::ATOMIC_SWAP:
4520 case ISD::ATOMIC_LOAD_UMAX: {
4521 // If we are looking at the loaded value.
4522 if (Op.getResNo() == 0) {
4523 auto *AT = cast<AtomicSDNode>(Op);
4524 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4525
4526 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4527 Known.Zero.setBitsFrom(MemBits);
4528 }
4529 break;
4530 }
4531 case ISD::FrameIndex:
4532 case ISD::TargetFrameIndex: {
4533 const MachineFunction &MF = getMachineFunction();
4534 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4535 TLI->computeKnownBitsForStackObjectPointer(
4536 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4537 break;
4538 }
4539
4540 default:
4541 if (Opcode < ISD::BUILTIN_OP_END)
4542 break;
4543 [[fallthrough]];
4547 // Allow the target to implement this method for its nodes.
4548 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4549 break;
4550 }
4551
4552 return Known;
4553}
4554
4555/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4568
4571 // X + 0 never overflow
4572 if (isNullConstant(N1))
4573 return OFK_Never;
4574
4575 // If both operands each have at least two sign bits, the addition
4576 // cannot overflow.
4577 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4578 return OFK_Never;
4579
4580 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4581 return OFK_Sometime;
4582}
4583
4586 // X + 0 never overflow
4587 if (isNullConstant(N1))
4588 return OFK_Never;
4589
4590 // mulhi + 1 never overflow
4591 KnownBits N1Known = computeKnownBits(N1);
4592 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4593 N1Known.getMaxValue().ult(2))
4594 return OFK_Never;
4595
4596 KnownBits N0Known = computeKnownBits(N0);
4597 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4598 N0Known.getMaxValue().ult(2))
4599 return OFK_Never;
4600
4601 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4602 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4603 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4604 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4605}
4606
4609 // X - 0 never overflow
4610 if (isNullConstant(N1))
4611 return OFK_Never;
4612
4613 // If both operands each have at least two sign bits, the subtraction
4614 // cannot overflow.
4615 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4616 return OFK_Never;
4617
4618 KnownBits N0Known = computeKnownBits(N0);
4619 KnownBits N1Known = computeKnownBits(N1);
4620 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4621 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4622 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4623}
4624
4627 // X - 0 never overflow
4628 if (isNullConstant(N1))
4629 return OFK_Never;
4630
4631 ConstantRange N0Range =
4632 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4633 ConstantRange N1Range =
4634 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4635 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4636}
4637
4640 // X * 0 and X * 1 never overflow.
4641 if (isNullConstant(N1) || isOneConstant(N1))
4642 return OFK_Never;
4643
4646 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4647}
4648
4651 // X * 0 and X * 1 never overflow.
4652 if (isNullConstant(N1) || isOneConstant(N1))
4653 return OFK_Never;
4654
4655 // Get the size of the result.
4656 unsigned BitWidth = N0.getScalarValueSizeInBits();
4657
4658 // Sum of the sign bits.
4659 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4660
4661 // If we have enough sign bits, then there's no overflow.
4662 if (SignBits > BitWidth + 1)
4663 return OFK_Never;
4664
4665 if (SignBits == BitWidth + 1) {
4666 // The overflow occurs when the true multiplication of the
4667 // the operands is the minimum negative number.
4668 KnownBits N0Known = computeKnownBits(N0);
4669 KnownBits N1Known = computeKnownBits(N1);
4670 // If one of the operands is non-negative, then there's no
4671 // overflow.
4672 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4673 return OFK_Never;
4674 }
4675
4676 return OFK_Sometime;
4677}
4678
4680 unsigned Depth) const {
4681 APInt DemandedElts = getDemandAllEltsMask(Op);
4682 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4683}
4684
4686 const APInt &DemandedElts,
4687 bool ForSigned,
4688 unsigned Depth) const {
4689 EVT VT = Op.getValueType();
4690 unsigned BitWidth = VT.getScalarSizeInBits();
4691
4692 if (Depth >= MaxRecursionDepth)
4693 return ConstantRange::getFull(BitWidth);
4694
4695 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4696 return ConstantRange(C->getAPIntValue());
4697
4698 unsigned Opcode = Op.getOpcode();
4699 switch (Opcode) {
4700 case ISD::VSCALE: {
4702 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4703 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4704 }
4705 default:
4706 break;
4707 }
4708
4709 return ConstantRange::getFull(BitWidth);
4710}
4711
4714 unsigned Depth) const {
4715 APInt DemandedElts = getDemandAllEltsMask(Op);
4716 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4717 Depth);
4718}
4719
4721 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4722 unsigned Depth) const {
4723 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4725 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4728 return CR1.intersectWith(CR2, RangeType);
4729}
4730
4732 unsigned Depth) const {
4733 APInt DemandedElts = getDemandAllEltsMask(Val);
4734 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4735}
4736
4738 const APInt &DemandedElts,
4739 bool OrZero, unsigned Depth) const {
4740 if (Depth >= MaxRecursionDepth)
4741 return false; // Limit search depth.
4742
4743 EVT OpVT = Val.getValueType();
4744 unsigned BitWidth = OpVT.getScalarSizeInBits();
4745 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4746 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4747 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4748 assert(
4749 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4750 "Unexpected vector size");
4751
4752 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4753 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4754 return (OrZero && V.isZero()) || V.isPowerOf2();
4755 };
4756
4757 // Is the constant a known power of 2 or zero?
4758 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4759 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4760 return true;
4761
4762 switch (Val.getOpcode()) {
4764 SDValue InVec = Val.getOperand(0);
4765 SDValue EltNo = Val.getOperand(1);
4766 EVT VecVT = InVec.getValueType();
4767
4768 // Skip scalable vectors or implicit extensions.
4769 if (VecVT.isScalableVector() ||
4770 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4771 break;
4772
4773 // If we know the element index, just demand that vector element, else for
4774 // an unknown element index, ignore DemandedElts and demand them all.
4775 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4776 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4777 APInt DemandedSrcElts =
4778 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4779 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4780 : APInt::getAllOnes(NumSrcElts);
4781 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4782 }
4783
4784 case ISD::AND: {
4785 // Looking for `x & -x` pattern:
4786 // If x == 0:
4787 // x & -x -> 0
4788 // If x != 0:
4789 // x & -x -> non-zero pow2
4790 // so if we find the pattern return whether we know `x` is non-zero.
4791 SDValue X, Z;
4792 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4793 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4794 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4795 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4796 break;
4797 }
4798
4799 case ISD::SHL: {
4800 // A left-shift of a constant one will have exactly one bit set because
4801 // shifting the bit off the end is undefined.
4802 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4803 if (C && C->getAPIntValue() == 1)
4804 return true;
4805 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4806 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4807 Depth + 1);
4808 }
4809
4810 case ISD::SRL: {
4811 // A logical right-shift of a constant sign-bit will have exactly
4812 // one bit set.
4813 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4814 if (C && C->getAPIntValue().isSignMask())
4815 return true;
4816 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4817 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4818 Depth + 1);
4819 }
4820
4821 case ISD::TRUNCATE:
4822 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4823 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4824 Depth + 1);
4825
4826 case ISD::ROTL:
4827 case ISD::ROTR:
4828 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4829 Depth + 1);
4830 case ISD::BSWAP:
4831 case ISD::BITREVERSE:
4832 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4833 Depth + 1);
4834
4835 case ISD::SMIN:
4836 case ISD::SMAX:
4837 case ISD::UMIN:
4838 case ISD::UMAX:
4839 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4840 Depth + 1) &&
4841 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4842 Depth + 1);
4843
4844 case ISD::SELECT:
4845 case ISD::VSELECT:
4846 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4847 Depth + 1) &&
4848 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4849 Depth + 1);
4850
4851 case ISD::ZERO_EXTEND:
4852 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4853 Depth + 1);
4854
4855 case ISD::VSCALE:
4856 // vscale(power-of-two) is a power-of-two
4857 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4858 Depth + 1);
4859
4860 case ISD::VECTOR_SHUFFLE: {
4862 // Demanded elements with undef shuffle mask elements are unknown
4863 // - we cannot guarantee they are a power of two, so return false.
4864 APInt DemandedLHS, DemandedRHS;
4866 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4867 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4868 DemandedLHS, DemandedRHS))
4869 return false;
4870
4871 // All demanded elements from LHS must be known power of two.
4872 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4873 OrZero, Depth + 1))
4874 return false;
4875
4876 // All demanded elements from RHS must be known power of two.
4877 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4878 OrZero, Depth + 1))
4879 return false;
4880
4881 return true;
4882 }
4883 }
4884
4885 // More could be done here, though the above checks are enough
4886 // to handle some common cases.
4887 return false;
4888}
4889
4891 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4892 return C1->getValueAPF().getExactLog2Abs() >= 0;
4893
4894 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4895 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4896
4897 return false;
4898}
4899
4901 APInt DemandedElts = getDemandAllEltsMask(Op);
4902 return ComputeNumSignBits(Op, DemandedElts, Depth);
4903}
4904
4905unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4906 unsigned Depth) const {
4907 EVT VT = Op.getValueType();
4908 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4909 unsigned VTBits = VT.getScalarSizeInBits();
4910 unsigned NumElts = DemandedElts.getBitWidth();
4911 unsigned Tmp, Tmp2;
4912 unsigned FirstAnswer = 1;
4913
4914 assert((!VT.isScalableVector() || NumElts == 1) &&
4915 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4916
4917 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4918 const APInt &Val = C->getAPIntValue();
4919 return Val.getNumSignBits();
4920 }
4921
4922 if (Depth >= MaxRecursionDepth)
4923 return 1; // Limit search depth.
4924
4925 if (!DemandedElts)
4926 return 1; // No demanded elts, better to assume we don't know anything.
4927
4928 unsigned Opcode = Op.getOpcode();
4929 switch (Opcode) {
4930 default: break;
4931 case ISD::AssertSext:
4932 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4933 return VTBits-Tmp+1;
4934 case ISD::AssertZext:
4935 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4936 return VTBits-Tmp;
4937 case ISD::FREEZE:
4938 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4940 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4941 break;
4942 case ISD::MERGE_VALUES:
4943 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4944 Depth + 1);
4945 case ISD::SPLAT_VECTOR: {
4946 // Check if the sign bits of source go down as far as the truncated value.
4947 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4948 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4949 if (NumSrcSignBits > (NumSrcBits - VTBits))
4950 return NumSrcSignBits - (NumSrcBits - VTBits);
4951 break;
4952 }
4953 case ISD::BUILD_VECTOR:
4954 assert(!VT.isScalableVector());
4955 Tmp = VTBits;
4956 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4957 if (!DemandedElts[i])
4958 continue;
4959
4960 SDValue SrcOp = Op.getOperand(i);
4961 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4962 // for constant nodes to ensure we only look at the sign bits.
4964 APInt T = C->getAPIntValue().trunc(VTBits);
4965 Tmp2 = T.getNumSignBits();
4966 } else {
4967 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4968
4969 if (SrcOp.getValueSizeInBits() != VTBits) {
4970 assert(SrcOp.getValueSizeInBits() > VTBits &&
4971 "Expected BUILD_VECTOR implicit truncation");
4972 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4973 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4974 }
4975 }
4976 Tmp = std::min(Tmp, Tmp2);
4977 }
4978 return Tmp;
4979
4980 case ISD::VECTOR_COMPRESS: {
4981 SDValue Vec = Op.getOperand(0);
4982 SDValue PassThru = Op.getOperand(2);
4983 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
4984 if (Tmp == 1)
4985 return 1;
4986 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
4987 Tmp = std::min(Tmp, Tmp2);
4988 return Tmp;
4989 }
4990
4991 case ISD::VECTOR_SHUFFLE: {
4992 // Collect the minimum number of sign bits that are shared by every vector
4993 // element referenced by the shuffle.
4994 APInt DemandedLHS, DemandedRHS;
4996 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4997 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4998 DemandedLHS, DemandedRHS))
4999 return 1;
5000
5001 Tmp = std::numeric_limits<unsigned>::max();
5002 if (!!DemandedLHS)
5003 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5004 if (!!DemandedRHS) {
5005 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5006 Tmp = std::min(Tmp, Tmp2);
5007 }
5008 // If we don't know anything, early out and try computeKnownBits fall-back.
5009 if (Tmp == 1)
5010 break;
5011 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5012 return Tmp;
5013 }
5014
5015 case ISD::BITCAST: {
5016 if (VT.isScalableVector())
5017 break;
5018 SDValue N0 = Op.getOperand(0);
5019 EVT SrcVT = N0.getValueType();
5020 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5021
5022 // Ignore bitcasts from unsupported types..
5023 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5024 break;
5025
5026 // Fast handling of 'identity' bitcasts.
5027 if (VTBits == SrcBits)
5028 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5029
5030 bool IsLE = getDataLayout().isLittleEndian();
5031
5032 // Bitcast 'large element' scalar/vector to 'small element' vector.
5033 if ((SrcBits % VTBits) == 0) {
5034 assert(VT.isVector() && "Expected bitcast to vector");
5035
5036 unsigned Scale = SrcBits / VTBits;
5037 APInt SrcDemandedElts =
5038 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5039
5040 // Fast case - sign splat can be simply split across the small elements.
5041 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5042 if (Tmp == SrcBits)
5043 return VTBits;
5044
5045 // Slow case - determine how far the sign extends into each sub-element.
5046 Tmp2 = VTBits;
5047 for (unsigned i = 0; i != NumElts; ++i)
5048 if (DemandedElts[i]) {
5049 unsigned SubOffset = i % Scale;
5050 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5051 SubOffset = SubOffset * VTBits;
5052 if (Tmp <= SubOffset)
5053 return 1;
5054 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5055 }
5056 return Tmp2;
5057 }
5058 break;
5059 }
5060
5062 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5063 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5064 return VTBits - Tmp + 1;
5065 case ISD::SIGN_EXTEND:
5066 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5067 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5069 // Max of the input and what this extends.
5070 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5071 Tmp = VTBits-Tmp+1;
5072 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5073 return std::max(Tmp, Tmp2);
5075 if (VT.isScalableVector())
5076 break;
5077 SDValue Src = Op.getOperand(0);
5078 EVT SrcVT = Src.getValueType();
5079 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5080 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5081 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5082 }
5083 case ISD::SRA:
5084 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5085 // SRA X, C -> adds C sign bits.
5086 if (std::optional<unsigned> ShAmt =
5087 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5088 Tmp = std::min(Tmp + *ShAmt, VTBits);
5089 return Tmp;
5090 case ISD::SHL:
5091 if (std::optional<ConstantRange> ShAmtRange =
5092 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5093 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5094 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5095 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5096 // shifted out, then we can compute the number of sign bits for the
5097 // operand being extended. A future improvement could be to pass along the
5098 // "shifted left by" information in the recursive calls to
5099 // ComputeKnownSignBits. Allowing us to handle this more generically.
5100 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5101 SDValue Ext = Op.getOperand(0);
5102 EVT ExtVT = Ext.getValueType();
5103 SDValue Extendee = Ext.getOperand(0);
5104 EVT ExtendeeVT = Extendee.getValueType();
5105 unsigned SizeDifference =
5106 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5107 if (SizeDifference <= MinShAmt) {
5108 Tmp = SizeDifference +
5109 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5110 if (MaxShAmt < Tmp)
5111 return Tmp - MaxShAmt;
5112 }
5113 }
5114 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5115 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5116 if (MaxShAmt < Tmp)
5117 return Tmp - MaxShAmt;
5118 }
5119 break;
5120 case ISD::AND:
5121 case ISD::OR:
5122 case ISD::XOR: // NOT is handled here.
5123 // Logical binary ops preserve the number of sign bits at the worst.
5124 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5125 if (Tmp != 1) {
5126 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5127 FirstAnswer = std::min(Tmp, Tmp2);
5128 // We computed what we know about the sign bits as our first
5129 // answer. Now proceed to the generic code that uses
5130 // computeKnownBits, and pick whichever answer is better.
5131 }
5132 break;
5133
5134 case ISD::SELECT:
5135 case ISD::VSELECT:
5136 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5137 if (Tmp == 1) return 1; // Early out.
5138 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5139 return std::min(Tmp, Tmp2);
5140 case ISD::SELECT_CC:
5141 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5142 if (Tmp == 1) return 1; // Early out.
5143 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5144 return std::min(Tmp, Tmp2);
5145
5146 case ISD::SMIN:
5147 case ISD::SMAX: {
5148 // If we have a clamp pattern, we know that the number of sign bits will be
5149 // the minimum of the clamp min/max range.
5150 bool IsMax = (Opcode == ISD::SMAX);
5151 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5152 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5153 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5154 CstHigh =
5155 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5156 if (CstLow && CstHigh) {
5157 if (!IsMax)
5158 std::swap(CstLow, CstHigh);
5159 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5160 Tmp = CstLow->getAPIntValue().getNumSignBits();
5161 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5162 return std::min(Tmp, Tmp2);
5163 }
5164 }
5165
5166 // Fallback - just get the minimum number of sign bits of the operands.
5167 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5168 if (Tmp == 1)
5169 return 1; // Early out.
5170 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5171 return std::min(Tmp, Tmp2);
5172 }
5173 case ISD::UMIN:
5174 case ISD::UMAX:
5175 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5176 if (Tmp == 1)
5177 return 1; // Early out.
5178 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5179 return std::min(Tmp, Tmp2);
5180 case ISD::SSUBO_CARRY:
5181 case ISD::USUBO_CARRY:
5182 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5183 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5184 return VTBits;
5185 [[fallthrough]];
5186 case ISD::SADDO:
5187 case ISD::UADDO:
5188 case ISD::SADDO_CARRY:
5189 case ISD::UADDO_CARRY:
5190 case ISD::SSUBO:
5191 case ISD::USUBO:
5192 case ISD::SMULO:
5193 case ISD::UMULO:
5194 if (Op.getResNo() != 1)
5195 break;
5196 // The boolean result conforms to getBooleanContents. Fall through.
5197 // If setcc returns 0/-1, all bits are sign bits.
5198 // We know that we have an integer-based boolean since these operations
5199 // are only available for integer.
5200 if (TLI->getBooleanContents(VT.isVector(), false) ==
5202 return VTBits;
5203 break;
5204 case ISD::SETCC:
5205 case ISD::SETCCCARRY:
5206 case ISD::STRICT_FSETCC:
5207 case ISD::STRICT_FSETCCS: {
5208 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5209 // If setcc returns 0/-1, all bits are sign bits.
5210 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5212 return VTBits;
5213 break;
5214 }
5216 // Semantically similar to icmp ult.
5217 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5219 return VTBits;
5220 break;
5221 case ISD::ROTL:
5222 case ISD::ROTR: {
5223 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5224 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5225 FirstAnswer = SignBitsOps::rot(
5226 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5227 Opcode == ISD::ROTR);
5228 break;
5229 }
5230 case ISD::ADD:
5231 case ISD::ADDC:
5232 // TODO: Move Operand 1 check before Operand 0 check
5233 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5234 if (Tmp == 1) return 1; // Early out.
5235
5236 // Special case decrementing a value (ADD X, -1):
5237 if (ConstantSDNode *CRHS =
5238 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5239 if (CRHS->isAllOnes()) {
5241 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5242
5243 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5244 // sign bits set.
5245 if ((Known.Zero | 1).isAllOnes())
5246 return VTBits;
5247
5248 // If we are subtracting one from a positive number, there is no carry
5249 // out of the result.
5250 if (Known.isNonNegative())
5251 return Tmp;
5252 }
5253
5254 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5255 if (Tmp2 == 1) return 1; // Early out.
5256
5257 // Add can have at most one carry bit. Thus we know that the output
5258 // is, at worst, one more bit than the inputs.
5259 return std::min(Tmp, Tmp2) - 1;
5260 case ISD::SUB:
5261 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5262 if (Tmp2 == 1) return 1; // Early out.
5263
5264 // Handle NEG.
5265 if (ConstantSDNode *CLHS =
5266 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5267 if (CLHS->isZero()) {
5269 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5270 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5271 // sign bits set.
5272 if ((Known.Zero | 1).isAllOnes())
5273 return VTBits;
5274
5275 // If the input is known to be positive (the sign bit is known clear),
5276 // the output of the NEG has the same number of sign bits as the input.
5277 if (Known.isNonNegative())
5278 return Tmp2;
5279
5280 // Otherwise, we treat this like a SUB.
5281 }
5282
5283 // Sub can have at most one carry bit. Thus we know that the output
5284 // is, at worst, one more bit than the inputs.
5285 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5286 if (Tmp == 1) return 1; // Early out.
5287 return std::min(Tmp, Tmp2) - 1;
5288 case ISD::MUL: {
5289 // The output of the Mul can be at most twice the valid bits in the inputs.
5290 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5291 if (SignBitsOp0 == 1)
5292 break;
5293 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5294 if (SignBitsOp1 == 1)
5295 break;
5296 unsigned OutValidBits =
5297 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5298 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5299 }
5300 case ISD::AVGCEILS:
5301 case ISD::AVGFLOORS:
5302 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5303 if (Tmp == 1)
5304 return 1; // Early out.
5305 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5306 return std::min(Tmp, Tmp2);
5307 case ISD::SREM:
5308 // The sign bit is the LHS's sign bit, except when the result of the
5309 // remainder is zero. The magnitude of the result should be less than or
5310 // equal to the magnitude of the LHS. Therefore, the result should have
5311 // at least as many sign bits as the left hand side.
5312 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5313 case ISD::TRUNCATE: {
5314 // Check if the sign bits of source go down as far as the truncated value.
5315 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5316 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5317 if (NumSrcSignBits > (NumSrcBits - VTBits))
5318 return NumSrcSignBits - (NumSrcBits - VTBits);
5319 break;
5320 }
5321 case ISD::EXTRACT_ELEMENT: {
5322 if (VT.isScalableVector())
5323 break;
5324 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5325 const int BitWidth = Op.getValueSizeInBits();
5326 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5327
5328 // Get reverse index (starting from 1), Op1 value indexes elements from
5329 // little end. Sign starts at big end.
5330 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5331
5332 // If the sign portion ends in our element the subtraction gives correct
5333 // result. Otherwise it gives either negative or > bitwidth result
5334 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5335 }
5337 if (VT.isScalableVector())
5338 break;
5339 // If we know the element index, split the demand between the
5340 // source vector and the inserted element, otherwise assume we need
5341 // the original demanded vector elements and the value.
5342 SDValue InVec = Op.getOperand(0);
5343 SDValue InVal = Op.getOperand(1);
5344 SDValue EltNo = Op.getOperand(2);
5345 bool DemandedVal = true;
5346 APInt DemandedVecElts = DemandedElts;
5347 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5348 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5349 unsigned EltIdx = CEltNo->getZExtValue();
5350 DemandedVal = !!DemandedElts[EltIdx];
5351 DemandedVecElts.clearBit(EltIdx);
5352 }
5353 Tmp = std::numeric_limits<unsigned>::max();
5354 if (DemandedVal) {
5355 // TODO - handle implicit truncation of inserted elements.
5356 if (InVal.getScalarValueSizeInBits() != VTBits)
5357 break;
5358 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5359 Tmp = std::min(Tmp, Tmp2);
5360 }
5361 if (!!DemandedVecElts) {
5362 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5363 Tmp = std::min(Tmp, Tmp2);
5364 }
5365 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5366 return Tmp;
5367 }
5369 SDValue InVec = Op.getOperand(0);
5370 SDValue EltNo = Op.getOperand(1);
5371 EVT VecVT = InVec.getValueType();
5372 // ComputeNumSignBits not yet implemented for scalable vectors.
5373 if (VecVT.isScalableVector())
5374 break;
5375 const unsigned BitWidth = Op.getValueSizeInBits();
5376 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5377 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5378
5379 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5380 // anything about sign bits. But if the sizes match we can derive knowledge
5381 // about sign bits from the vector operand.
5382 if (BitWidth != EltBitWidth)
5383 break;
5384
5385 // If we know the element index, just demand that vector element, else for
5386 // an unknown element index, ignore DemandedElts and demand them all.
5387 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5388 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5389 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5390 DemandedSrcElts =
5391 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5392
5393 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5394 }
5396 // Offset the demanded elts by the subvector index.
5397 SDValue Src = Op.getOperand(0);
5398
5399 APInt DemandedSrcElts;
5400 if (Src.getValueType().isScalableVector())
5401 DemandedSrcElts = APInt(1, 1);
5402 else {
5403 uint64_t Idx = Op.getConstantOperandVal(1);
5404 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5405 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5406 }
5407 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5408 }
5409 case ISD::CONCAT_VECTORS: {
5410 if (VT.isScalableVector())
5411 break;
5412 // Determine the minimum number of sign bits across all demanded
5413 // elts of the input vectors. Early out if the result is already 1.
5414 Tmp = std::numeric_limits<unsigned>::max();
5415 EVT SubVectorVT = Op.getOperand(0).getValueType();
5416 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5417 unsigned NumSubVectors = Op.getNumOperands();
5418 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5419 APInt DemandedSub =
5420 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5421 if (!DemandedSub)
5422 continue;
5423 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5424 Tmp = std::min(Tmp, Tmp2);
5425 }
5426 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5427 return Tmp;
5428 }
5429 case ISD::INSERT_SUBVECTOR: {
5430 if (VT.isScalableVector())
5431 break;
5432 // Demand any elements from the subvector and the remainder from the src its
5433 // inserted into.
5434 SDValue Src = Op.getOperand(0);
5435 SDValue Sub = Op.getOperand(1);
5436 uint64_t Idx = Op.getConstantOperandVal(2);
5437 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5438 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5439 APInt DemandedSrcElts = DemandedElts;
5440 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5441
5442 Tmp = std::numeric_limits<unsigned>::max();
5443 if (!!DemandedSubElts) {
5444 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5445 if (Tmp == 1)
5446 return 1; // early-out
5447 }
5448 if (!!DemandedSrcElts) {
5449 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5450 Tmp = std::min(Tmp, Tmp2);
5451 }
5452 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5453 return Tmp;
5454 }
5455 case ISD::LOAD: {
5456 // If we are looking at the loaded value of the SDNode.
5457 if (Op.getResNo() != 0)
5458 break;
5459
5461 if (const MDNode *Ranges = LD->getRanges()) {
5462 if (DemandedElts != 1)
5463 break;
5464
5466 if (VTBits > CR.getBitWidth()) {
5467 switch (LD->getExtensionType()) {
5468 case ISD::SEXTLOAD:
5469 CR = CR.signExtend(VTBits);
5470 break;
5471 case ISD::ZEXTLOAD:
5472 CR = CR.zeroExtend(VTBits);
5473 break;
5474 default:
5475 break;
5476 }
5477 }
5478
5479 if (VTBits != CR.getBitWidth())
5480 break;
5481 return std::min(CR.getSignedMin().getNumSignBits(),
5483 }
5484
5485 unsigned ExtType = LD->getExtensionType();
5486 switch (ExtType) {
5487 default:
5488 break;
5489 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5490 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5491 return VTBits - Tmp + 1;
5492 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5493 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5494 return VTBits - Tmp;
5495 case ISD::NON_EXTLOAD:
5496 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5497 // We only need to handle vectors - computeKnownBits should handle
5498 // scalar cases.
5499 Type *CstTy = Cst->getType();
5500 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5501 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5502 VTBits == CstTy->getScalarSizeInBits()) {
5503 Tmp = VTBits;
5504 for (unsigned i = 0; i != NumElts; ++i) {
5505 if (!DemandedElts[i])
5506 continue;
5507 if (Constant *Elt = Cst->getAggregateElement(i)) {
5508 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5509 const APInt &Value = CInt->getValue();
5510 Tmp = std::min(Tmp, Value.getNumSignBits());
5511 continue;
5512 }
5513 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5514 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5515 Tmp = std::min(Tmp, Value.getNumSignBits());
5516 continue;
5517 }
5518 }
5519 // Unknown type. Conservatively assume no bits match sign bit.
5520 return 1;
5521 }
5522 return Tmp;
5523 }
5524 }
5525 break;
5526 }
5527
5528 break;
5529 }
5532 case ISD::ATOMIC_SWAP:
5544 case ISD::ATOMIC_LOAD: {
5545 auto *AT = cast<AtomicSDNode>(Op);
5546 // If we are looking at the loaded value.
5547 if (Op.getResNo() == 0) {
5548 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5549 if (Tmp == VTBits)
5550 return 1; // early-out
5551
5552 // For atomic_load, prefer to use the extension type.
5553 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5554 switch (AT->getExtensionType()) {
5555 default:
5556 break;
5557 case ISD::SEXTLOAD:
5558 return VTBits - Tmp + 1;
5559 case ISD::ZEXTLOAD:
5560 return VTBits - Tmp;
5561 }
5562 }
5563
5564 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5565 return VTBits - Tmp + 1;
5566 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5567 return VTBits - Tmp;
5568 }
5569 break;
5570 }
5571 }
5572
5573 // Allow the target to implement this method for its nodes.
5574 if (Opcode >= ISD::BUILTIN_OP_END ||
5575 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5576 Opcode == ISD::INTRINSIC_W_CHAIN ||
5577 Opcode == ISD::INTRINSIC_VOID) {
5578 // TODO: This can probably be removed once target code is audited. This
5579 // is here purely to reduce patch size and review complexity.
5580 if (!VT.isScalableVector()) {
5581 unsigned NumBits =
5582 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5583 if (NumBits > 1)
5584 FirstAnswer = std::max(FirstAnswer, NumBits);
5585 }
5586 }
5587
5588 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5589 // use this information.
5590 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5591 return std::max(FirstAnswer, Known.countMinSignBits());
5592}
5593
5595 unsigned Depth) const {
5596 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5597 return Op.getScalarValueSizeInBits() - SignBits + 1;
5598}
5599
5601 const APInt &DemandedElts,
5602 unsigned Depth) const {
5603 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5604 return Op.getScalarValueSizeInBits() - SignBits + 1;
5605}
5606
5608 UndefPoisonKind Kind,
5609 unsigned Depth) const {
5610 // Early out for FREEZE.
5611 if (Op.getOpcode() == ISD::FREEZE)
5612 return true;
5613
5614 APInt DemandedElts = getDemandAllEltsMask(Op);
5615 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5616}
5617
5619 const APInt &DemandedElts,
5620 UndefPoisonKind Kind,
5621 unsigned Depth) const {
5622 unsigned Opcode = Op.getOpcode();
5623
5624 // Early out for FREEZE.
5625 if (Opcode == ISD::FREEZE)
5626 return true;
5627
5628 if (Depth >= MaxRecursionDepth)
5629 return false; // Limit search depth.
5630
5631 if (isIntOrFPConstant(Op))
5632 return true;
5633
5634 switch (Opcode) {
5635 case ISD::CONDCODE:
5636 case ISD::VALUETYPE:
5637 case ISD::FrameIndex:
5639 case ISD::CopyFromReg:
5640 return true;
5641
5642 case ISD::POISON:
5643 return !includesPoison(Kind);
5644
5645 case ISD::UNDEF:
5646 return !includesUndef(Kind);
5647
5648 case ISD::BITCAST: {
5649 SDValue Src = Op.getOperand(0);
5650 EVT SrcVT = Src.getValueType();
5651 EVT DstVT = Op.getValueType();
5652
5653 if (!SrcVT.isVector() || !DstVT.isVector())
5654 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5655
5656 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5657 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5658 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5659 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5660
5661 if (SrcEltBits == DstEltBits)
5662 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5663 Depth + 1);
5664
5665 if (SrcEltBits < DstEltBits) {
5666 if (DstEltBits % SrcEltBits != 0)
5667 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5668
5669 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5670 "Unexpected vector bitcast");
5671 APInt DemandedSrcElts =
5672 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5673 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5674 Depth + 1);
5675 }
5676
5677 if (SrcEltBits % DstEltBits != 0)
5678 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5679
5680 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5681 "Unexpected vector bitcast");
5682 APInt DemandedSrcElts =
5683 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5684 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5685 Depth + 1);
5686 }
5687
5688 case ISD::BUILD_VECTOR:
5689 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5690 // this shouldn't affect the result.
5691 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5692 if (!DemandedElts[i])
5693 continue;
5694 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5695 return false;
5696 }
5697 return true;
5698
5699 case ISD::CONCAT_VECTORS: {
5700 EVT VT = Op.getValueType();
5701 if (!VT.isFixedLengthVector())
5702 break;
5703
5704 EVT SubVT = Op.getOperand(0).getValueType();
5705 unsigned NumSubElts = SubVT.getVectorNumElements();
5706 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5707 APInt DemandedSubElts =
5708 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5709 if (!!DemandedSubElts &&
5710 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5711 Kind, Depth + 1))
5712 return false;
5713 }
5714 return true;
5715 }
5716
5718 SDValue Src = Op.getOperand(0);
5719 if (Src.getValueType().isScalableVector())
5720 break;
5721 uint64_t Idx = Op.getConstantOperandVal(1);
5722 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5723 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5724 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5725 Depth + 1);
5726 }
5727
5728 case ISD::INSERT_SUBVECTOR: {
5729 if (Op.getValueType().isScalableVector())
5730 break;
5731 SDValue Src = Op.getOperand(0);
5732 SDValue Sub = Op.getOperand(1);
5733 uint64_t Idx = Op.getConstantOperandVal(2);
5734 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5735 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5736 APInt DemandedSrcElts = DemandedElts;
5737 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5738
5739 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5740 Sub, DemandedSubElts, Kind, Depth + 1))
5741 return false;
5742 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5743 Src, DemandedSrcElts, Kind, Depth + 1))
5744 return false;
5745 return true;
5746 }
5747
5749 SDValue Src = Op.getOperand(0);
5750 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5751 EVT SrcVT = Src.getValueType();
5752 if (SrcVT.isFixedLengthVector() && IndexC &&
5753 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5754 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5755 IndexC->getZExtValue());
5756 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5757 Depth + 1);
5758 }
5759 break;
5760 }
5761
5763 SDValue InVec = Op.getOperand(0);
5764 SDValue InVal = Op.getOperand(1);
5765 SDValue EltNo = Op.getOperand(2);
5766 EVT VT = InVec.getValueType();
5767 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5768 if (IndexC && VT.isFixedLengthVector() &&
5769 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5770 if (DemandedElts[IndexC->getZExtValue()] &&
5771 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5772 return false;
5773 APInt InVecDemandedElts = DemandedElts;
5774 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5775 if (!!InVecDemandedElts &&
5777 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5778 InVecDemandedElts, Kind, Depth + 1))
5779 return false;
5780 return true;
5781 }
5782 break;
5783 }
5784
5786 // Check upper (known undef) elements.
5787 if (DemandedElts.ugt(1) && includesUndef(Kind))
5788 return false;
5789 // Check element zero.
5790 if (DemandedElts[0] &&
5791 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5792 return false;
5793 return true;
5794
5795 case ISD::SPLAT_VECTOR:
5796 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5797
5798 case ISD::SELECT: {
5799 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5800 /*ConsiderFlags*/ true, Depth) &&
5801 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5802 Depth + 1) &&
5803 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5804 Kind, Depth + 1) &&
5805 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5806 Kind, Depth + 1);
5807 }
5808
5809 case ISD::VECTOR_SHUFFLE: {
5810 APInt DemandedLHS, DemandedRHS;
5811 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5812 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5813 DemandedElts, DemandedLHS, DemandedRHS,
5814 /*AllowUndefElts=*/false))
5815 return false;
5816 if (!DemandedLHS.isZero() &&
5817 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5818 Depth + 1))
5819 return false;
5820 if (!DemandedRHS.isZero() &&
5821 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5822 Depth + 1))
5823 return false;
5824 return true;
5825 }
5826
5827 case ISD::SHL:
5828 case ISD::SRL:
5829 case ISD::SRA:
5830 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5831 // enough to check operand 0 if Op can't create undef/poison.
5832 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5833 /*ConsiderFlags*/ true, Depth) &&
5834 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5835 Kind, Depth + 1);
5836
5837 case ISD::BSWAP:
5838 case ISD::CTPOP:
5839 case ISD::BITREVERSE:
5840 case ISD::AND:
5841 case ISD::OR:
5842 case ISD::XOR:
5843 case ISD::ADD:
5844 case ISD::SUB:
5845 case ISD::MUL:
5846 case ISD::SADDSAT:
5847 case ISD::UADDSAT:
5848 case ISD::SSUBSAT:
5849 case ISD::USUBSAT:
5850 case ISD::SSHLSAT:
5851 case ISD::USHLSAT:
5852 case ISD::SMIN:
5853 case ISD::SMAX:
5854 case ISD::UMIN:
5855 case ISD::UMAX:
5856 case ISD::ZERO_EXTEND:
5857 case ISD::SIGN_EXTEND:
5858 case ISD::ANY_EXTEND:
5859 case ISD::TRUNCATE:
5860 case ISD::VSELECT: {
5861 // If Op can't create undef/poison and none of its operands are undef/poison
5862 // then Op is never undef/poison. A difference from the more common check
5863 // below, outside the switch, is that we handle elementwise operations for
5864 // which the DemandedElts mask is valid for all operands here.
5865 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5866 /*ConsiderFlags*/ true, Depth) &&
5867 all_of(Op->ops(), [&](SDValue V) {
5868 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5869 Depth + 1);
5870 });
5871 }
5872
5873 // TODO: Search for noundef attributes from library functions.
5874
5875 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5876
5877 default:
5878 // Allow the target to implement this method for its nodes.
5879 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5880 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5881 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5882 Op, DemandedElts, *this, Kind, Depth);
5883 break;
5884 }
5885
5886 // If Op can't create undef/poison and none of its operands are undef/poison
5887 // then Op is never undef/poison.
5888 // NOTE: TargetNodes can handle this in themselves in
5889 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5890 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5891 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5892 all_of(Op->ops(), [&](SDValue V) {
5893 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5894 });
5895}
5896
5898 bool ConsiderFlags,
5899 unsigned Depth) const {
5900 APInt DemandedElts = getDemandAllEltsMask(Op);
5901 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5902}
5903
5905 UndefPoisonKind Kind,
5906 bool ConsiderFlags,
5907 unsigned Depth) const {
5908 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5909 return true;
5910
5911 unsigned Opcode = Op.getOpcode();
5912 switch (Opcode) {
5913 case ISD::AssertSext:
5914 case ISD::AssertZext:
5915 case ISD::AssertAlign:
5917 // Assertion nodes can create poison if the assertion fails.
5918 return includesPoison(Kind);
5919
5920 case ISD::FREEZE:
5924 case ISD::SADDSAT:
5925 case ISD::UADDSAT:
5926 case ISD::SSUBSAT:
5927 case ISD::USUBSAT:
5928 case ISD::MULHU:
5929 case ISD::MULHS:
5930 case ISD::AVGFLOORS:
5931 case ISD::AVGFLOORU:
5932 case ISD::AVGCEILS:
5933 case ISD::AVGCEILU:
5934 case ISD::ABDU:
5935 case ISD::ABDS:
5936 case ISD::SMIN:
5937 case ISD::SMAX:
5938 case ISD::SCMP:
5939 case ISD::UMIN:
5940 case ISD::UMAX:
5941 case ISD::UCMP:
5942 case ISD::AND:
5943 case ISD::XOR:
5944 case ISD::ROTL:
5945 case ISD::ROTR:
5946 case ISD::FSHL:
5947 case ISD::FSHR:
5948 case ISD::BSWAP:
5949 case ISD::CTTZ:
5950 case ISD::CTLZ:
5951 case ISD::CTLS:
5952 case ISD::CTPOP:
5953 case ISD::BITREVERSE:
5954 case ISD::PARITY:
5955 case ISD::SIGN_EXTEND:
5956 case ISD::TRUNCATE:
5960 case ISD::BITCAST:
5961 case ISD::BUILD_VECTOR:
5962 case ISD::BUILD_PAIR:
5963 case ISD::SPLAT_VECTOR:
5964 case ISD::FABS:
5965 case ISD::FCEIL:
5966 case ISD::FFLOOR:
5967 case ISD::FTRUNC:
5968 case ISD::FRINT:
5969 case ISD::FNEARBYINT:
5970 case ISD::FROUND:
5971 case ISD::FROUNDEVEN:
5972 return false;
5973
5974 case ISD::ABS:
5975 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
5976 // Different to Intrinsic::abs.
5977 return false;
5979 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
5980 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
5981
5982 case ISD::ADDC:
5983 case ISD::SUBC:
5984 case ISD::ADDE:
5985 case ISD::SUBE:
5986 case ISD::SADDO:
5987 case ISD::SSUBO:
5988 case ISD::SMULO:
5989 case ISD::SADDO_CARRY:
5990 case ISD::SSUBO_CARRY:
5991 case ISD::UADDO:
5992 case ISD::USUBO:
5993 case ISD::UMULO:
5994 case ISD::UADDO_CARRY:
5995 case ISD::USUBO_CARRY:
5996 // No poison on result or overflow flags.
5997 return false;
5998
5999 case ISD::SELECT_CC:
6000 case ISD::SETCC: {
6001 // Integer setcc cannot create undef or poison.
6002 if (Op.getOperand(0).getValueType().isInteger())
6003 return false;
6004
6005 // FP compares are more complicated. They can create poison for nan/infinity
6006 // based on options and flags. The options and flags also cause special
6007 // nonan condition codes to be used. Those condition codes may be preserved
6008 // even if the nonan flag is dropped somewhere.
6009 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6010 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6011 return (unsigned)CCCode & 0x10U;
6012 }
6013
6014 case ISD::OR:
6015 case ISD::ZERO_EXTEND:
6016 case ISD::SELECT:
6017 case ISD::VSELECT:
6018 case ISD::ADD:
6019 case ISD::SUB:
6020 case ISD::MUL:
6021 case ISD::FNEG:
6022 case ISD::FADD:
6023 case ISD::FSUB:
6024 case ISD::FMUL:
6025 case ISD::FDIV:
6026 case ISD::FREM:
6027 case ISD::FCOPYSIGN:
6028 case ISD::FMA:
6029 case ISD::FMAD:
6030 case ISD::FMULADD:
6031 case ISD::FP_EXTEND:
6032 case ISD::FMINNUM:
6033 case ISD::FMAXNUM:
6034 case ISD::FMINNUM_IEEE:
6035 case ISD::FMAXNUM_IEEE:
6036 case ISD::FMINIMUM:
6037 case ISD::FMAXIMUM:
6038 case ISD::FMINIMUMNUM:
6039 case ISD::FMAXIMUMNUM:
6045 // No poison except from flags (which is handled above)
6046 return false;
6047
6048 case ISD::SHL:
6049 case ISD::SRL:
6050 case ISD::SRA:
6051 // If the max shift amount isn't in range, then the shift can
6052 // create poison.
6053 return includesPoison(Kind) &&
6054 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6055
6058 // If the amount is zero then the result will be poison.
6059 // TODO: Add isKnownNeverZero DemandedElts handling.
6060 return includesPoison(Kind) &&
6061 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6062
6064 // Check if we demand any upper (undef) elements.
6065 return includesUndef(Kind) && DemandedElts.ugt(1);
6066
6069 // Ensure that the element index is in bounds.
6070 if (includesPoison(Kind)) {
6071 EVT VecVT = Op.getOperand(0).getValueType();
6072 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6073 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6074 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6075 }
6076 return false;
6077 }
6078
6079 case ISD::VECTOR_SHUFFLE: {
6080 // Check for any demanded shuffle element that is undef.
6081 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6082 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6083 if (Elt < 0 && DemandedElts[Idx])
6084 return true;
6085 return false;
6086 }
6087
6089 return false;
6090
6091 default:
6092 // Allow the target to implement this method for its nodes.
6093 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6094 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6095 return TLI->canCreateUndefOrPoisonForTargetNode(
6096 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6097 break;
6098 }
6099
6100 // Be conservative and return true.
6101 return true;
6102}
6103
6104bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6105 unsigned Opcode = Op.getOpcode();
6106 if (Opcode == ISD::OR)
6107 return Op->getFlags().hasDisjoint() ||
6108 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6109 if (Opcode == ISD::XOR)
6110 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6111 return false;
6112}
6113
6115 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6116 (Op.isAnyAdd() || isADDLike(Op));
6117}
6118
6120 FPClassTest InterestedClasses,
6121 unsigned Depth) const {
6122 APInt DemandedElts = getDemandAllEltsMask(Op);
6123 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6124}
6125
6127 const APInt &DemandedElts,
6128 FPClassTest InterestedClasses,
6129 unsigned Depth) const {
6131
6132 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6133 return KnownFPClass(CFP->getValueAPF());
6134
6135 if (Depth >= MaxRecursionDepth)
6136 return Known;
6137
6138 if (Op.getOpcode() == ISD::UNDEF)
6139 return Known;
6140
6141 EVT VT = Op.getValueType();
6142 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6143 assert((!VT.isFixedLengthVector() ||
6144 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6145 "Unexpected vector size");
6146
6147 if (!DemandedElts)
6148 return Known;
6149
6150 unsigned Opcode = Op.getOpcode();
6151 switch (Opcode) {
6152 case ISD::POISON: {
6153 Known.KnownFPClasses = fcNone;
6154 Known.SignBit = false;
6155 break;
6156 }
6157 case ISD::FNEG: {
6158 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6159 InterestedClasses, Depth + 1);
6160 Known.fneg();
6161 break;
6162 }
6163 case ISD::BUILD_VECTOR: {
6164 assert(!VT.isScalableVector());
6165 bool First = true;
6166 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6167 if (!DemandedElts[I])
6168 continue;
6169
6170 if (First) {
6171 Known =
6172 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6173 First = false;
6174 } else {
6175 Known |=
6176 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6177 }
6178
6179 if (Known.isUnknown())
6180 break;
6181 }
6182 break;
6183 }
6185 SDValue Src = Op.getOperand(0);
6186 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6187 EVT SrcVT = Src.getValueType();
6188 if (SrcVT.isFixedLengthVector() && CIdx) {
6189 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6190 APInt DemandedSrcElts = APInt::getOneBitSet(
6191 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6192 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6193 Depth + 1);
6194 } else {
6195 // Out of bounds index is poison.
6196 Known.KnownFPClasses = fcNone;
6197 }
6198 } else {
6199 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6200 }
6201 break;
6202 }
6203 case ISD::SPLAT_VECTOR: {
6204 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6205 break;
6206 }
6207 case ISD::BITCAST: {
6208 // FIXME: It should not be necessary to check for an elementwise bitcast.
6209 // If a bitcast is not elementwise between vector / scalar types,
6210 // computeKnownBits already splices the known bits of the source elements
6211 // appropriately so as to line up with the bits of the result's demanded
6212 // elements.
6213 EVT SrcVT = Op.getOperand(0).getValueType();
6214 if (VT.isScalableVector() || SrcVT.isScalableVector())
6215 break;
6216 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6217 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6218 if (VTNumElts != SrcVTNumElts)
6219 break;
6220
6221 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6223 break;
6224 }
6225 case ISD::FABS: {
6226 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6227 InterestedClasses, Depth + 1);
6228 Known.fabs();
6229 break;
6230 }
6231 case ISD::FCOPYSIGN: {
6232 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6233 InterestedClasses, Depth + 1);
6234 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6235 InterestedClasses, Depth + 1);
6236 Known.copysign(KnownSign);
6237 break;
6238 }
6239 case ISD::AssertNoFPClass: {
6240 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6241 InterestedClasses, Depth + 1);
6242 FPClassTest AssertedClasses =
6243 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6244 Known.KnownFPClasses &= ~AssertedClasses;
6245 break;
6246 }
6248 SDValue Src = Op.getOperand(0);
6249 EVT SrcVT = Src.getValueType();
6250 if (SrcVT.isFixedLengthVector()) {
6251 unsigned Idx = Op.getConstantOperandVal(1);
6252 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6253
6254 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6255 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6256 Depth + 1);
6257 } else {
6258 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6259 }
6260 break;
6261 }
6262 case ISD::INSERT_SUBVECTOR: {
6263 SDValue BaseVector = Op.getOperand(0);
6264 SDValue SubVector = Op.getOperand(1);
6265 EVT BaseVT = BaseVector.getValueType();
6266 if (BaseVT.isFixedLengthVector()) {
6267 unsigned Idx = Op.getConstantOperandVal(2);
6268 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6269 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6270
6271 APInt DemandedMask =
6272 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6273 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6274 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6275
6276 if (!DemandedSrcElts.isZero())
6277 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6278 InterestedClasses, Depth + 1);
6279 if (!DemandedSubElts.isZero()) {
6281 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6282 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6283 }
6284 } else {
6285 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6286 if (!Known.isUnknown())
6287 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6288 }
6289 break;
6290 }
6291 case ISD::SELECT:
6292 case ISD::VSELECT: {
6293 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6294 // IR-level ValueTracking.
6295 KnownFPClass KnownFalseClass = computeKnownFPClass(
6296 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6297 if (KnownFalseClass.isUnknown())
6298 break;
6299 KnownFPClass KnownTrueClass = computeKnownFPClass(
6300 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6301 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6302 break;
6303 }
6304 default:
6305 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6306 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6307 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6308 Depth);
6309 }
6310 break;
6311 }
6312
6313 return Known;
6314}
6315
6317 unsigned Depth) const {
6318 APInt DemandedElts = getDemandAllEltsMask(Op);
6319 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6320}
6321
6323 bool SNaN, unsigned Depth) const {
6324 assert(!DemandedElts.isZero() && "No demanded elements");
6325
6326 // If we're told that NaNs won't happen, assume they won't.
6327 if (Op->getFlags().hasNoNaNs())
6328 return true;
6329
6330 if (Depth >= MaxRecursionDepth)
6331 return false; // Limit search depth.
6332
6333 unsigned Opcode = Op.getOpcode();
6334 switch (Opcode) {
6335 case ISD::FADD:
6336 case ISD::FSUB:
6337 case ISD::FMUL:
6338 case ISD::FDIV:
6339 case ISD::FREM:
6340 case ISD::FSIN:
6341 case ISD::FCOS:
6342 case ISD::FTAN:
6343 case ISD::FASIN:
6344 case ISD::FACOS:
6345 case ISD::FATAN:
6346 case ISD::FATAN2:
6347 case ISD::FSINH:
6348 case ISD::FCOSH:
6349 case ISD::FTANH:
6350 case ISD::FMA:
6351 case ISD::FMULADD:
6352 case ISD::FMAD: {
6353 if (SNaN)
6354 return true;
6355 // TODO: Need isKnownNeverInfinity
6356 return false;
6357 }
6358 case ISD::FCANONICALIZE:
6359 case ISD::FEXP:
6360 case ISD::FEXP2:
6361 case ISD::FEXP10:
6362 case ISD::FTRUNC:
6363 case ISD::FFLOOR:
6364 case ISD::FCEIL:
6365 case ISD::FROUND:
6366 case ISD::FROUNDEVEN:
6367 case ISD::LROUND:
6368 case ISD::LLROUND:
6369 case ISD::FRINT:
6370 case ISD::LRINT:
6371 case ISD::LLRINT:
6372 case ISD::FNEARBYINT:
6373 case ISD::FLDEXP: {
6374 if (SNaN)
6375 return true;
6376 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6377 }
6378 case ISD::FABS:
6379 case ISD::FNEG:
6380 case ISD::FCOPYSIGN: {
6381 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6382 }
6383 case ISD::SELECT:
6384 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6385 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6386 case ISD::FP_EXTEND:
6387 case ISD::FP_ROUND: {
6388 if (SNaN)
6389 return true;
6390 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6391 }
6392 case ISD::SINT_TO_FP:
6393 case ISD::UINT_TO_FP:
6394 return true;
6395 case ISD::FSQRT: // Need is known positive
6396 case ISD::FLOG:
6397 case ISD::FLOG2:
6398 case ISD::FLOG10:
6399 case ISD::FPOWI:
6400 case ISD::FPOW: {
6401 if (SNaN)
6402 return true;
6403 // TODO: Refine on operand
6404 return false;
6405 }
6406 case ISD::FMINNUM:
6407 case ISD::FMAXNUM:
6408 case ISD::FMINIMUMNUM:
6409 case ISD::FMAXIMUMNUM: {
6410 // Only one needs to be known not-nan, since it will be returned if the
6411 // other ends up being one.
6412 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6413 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6414 }
6415 case ISD::FMINNUM_IEEE:
6416 case ISD::FMAXNUM_IEEE: {
6417 if (SNaN)
6418 return true;
6419 // This can return a NaN if either operand is an sNaN, or if both operands
6420 // are NaN.
6421 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6422 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6423 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6424 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6425 }
6426 case ISD::FMINIMUM:
6427 case ISD::FMAXIMUM: {
6428 // TODO: Does this quiet or return the origina NaN as-is?
6429 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6430 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6431 }
6433 SDValue Src = Op.getOperand(0);
6434 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6435 EVT SrcVT = Src.getValueType();
6436 if (SrcVT.isFixedLengthVector() && Idx &&
6437 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6438 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6439 Idx->getZExtValue());
6440 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6441 }
6442 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6443 }
6445 SDValue Src = Op.getOperand(0);
6446 if (Src.getValueType().isFixedLengthVector()) {
6447 unsigned Idx = Op.getConstantOperandVal(1);
6448 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6449 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6450 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6451 }
6452 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6453 }
6454 case ISD::INSERT_SUBVECTOR: {
6455 SDValue BaseVector = Op.getOperand(0);
6456 SDValue SubVector = Op.getOperand(1);
6457 EVT BaseVectorVT = BaseVector.getValueType();
6458 if (BaseVectorVT.isFixedLengthVector()) {
6459 unsigned Idx = Op.getConstantOperandVal(2);
6460 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6461 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6462
6463 // Clear/Extract the bits at the position where the subvector will be
6464 // inserted.
6465 APInt DemandedMask =
6466 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6467 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6468 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6469
6470 bool NeverNaN = true;
6471 if (!DemandedSrcElts.isZero())
6472 NeverNaN &=
6473 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6474 if (NeverNaN && !DemandedSubElts.isZero())
6475 NeverNaN &=
6476 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6477 return NeverNaN;
6478 }
6479 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6480 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6481 }
6482 case ISD::BUILD_VECTOR: {
6483 unsigned NumElts = Op.getNumOperands();
6484 for (unsigned I = 0; I != NumElts; ++I)
6485 if (DemandedElts[I] &&
6486 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6487 return false;
6488 return true;
6489 }
6490 case ISD::SPLAT_VECTOR:
6491 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6492 case ISD::AssertNoFPClass: {
6493 FPClassTest NoFPClass =
6494 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6495 if ((NoFPClass & fcNan) == fcNan)
6496 return true;
6497 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6498 return true;
6499 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6500 }
6501 default:
6502 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6503 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6504 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6505 Depth);
6506 }
6507 break;
6508 }
6509
6510 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6511 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6512 return Known.isKnownNever(NanMask);
6513}
6514
6516 APInt DemandedElts = getDemandAllEltsMask(Op);
6517 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6518}
6519
6521 const APInt &DemandedElts,
6522 unsigned Depth) const {
6523 assert(!DemandedElts.isZero() && "No demanded elements");
6524 EVT VT = Op.getValueType();
6526 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6527 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6528}
6529
6531 APInt DemandedElts = getDemandAllEltsMask(Op);
6532 return isKnownNeverZero(Op, DemandedElts, Depth);
6533}
6534
6536 unsigned Depth) const {
6537 if (Depth >= MaxRecursionDepth)
6538 return false; // Limit search depth.
6539
6540 EVT OpVT = Op.getValueType();
6541 unsigned BitWidth = OpVT.getScalarSizeInBits();
6542
6543 assert(!Op.getValueType().isFloatingPoint() &&
6544 "Floating point types unsupported - use isKnownNeverLogicalZero");
6545
6546 // If the value is a constant, we can obviously see if it is a zero or not.
6547 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6548 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6549 return !V.isZero();
6550 };
6551
6552 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6553 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6554 return true;
6555
6556 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6557 // some degree.
6558 switch (Op.getOpcode()) {
6559 default:
6560 break;
6561
6563 SDValue InVec = Op.getOperand(0);
6564 SDValue EltNo = Op.getOperand(1);
6565 EVT VecVT = InVec.getValueType();
6566
6567 // Skip scalable vectors or implicit extensions.
6568 if (VecVT.isScalableVector() ||
6569 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6570 break;
6571
6572 // If we know the element index, just demand that vector element, else for
6573 // an unknown element index, ignore DemandedElts and demand them all.
6574 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6575 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6576 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6577 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6578 DemandedSrcElts =
6579 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6580
6581 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6582 }
6583
6584 case ISD::OR:
6585 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6586 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6587
6588 case ISD::VSELECT:
6589 case ISD::SELECT:
6590 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6591 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6592
6593 case ISD::SHL: {
6594 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6595 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6596 KnownBits ValKnown =
6597 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6598 // 1 << X is never zero.
6599 if (ValKnown.One[0])
6600 return true;
6601 // If max shift cnt of known ones is non-zero, result is non-zero.
6602 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6603 .getMaxValue();
6604 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6605 !ValKnown.One.shl(MaxCnt).isZero())
6606 return true;
6607 break;
6608 }
6609
6610 case ISD::VECTOR_SHUFFLE: {
6611 if (Op.getValueType().isScalableVector())
6612 return false;
6613
6614 unsigned NumElts = DemandedElts.getBitWidth();
6615
6616 // All demanded elements from LHS and RHS must be known non-zero.
6617 // Demanded elements with undef shuffle mask elements are unknown.
6618
6619 APInt DemandedLHS, DemandedRHS;
6620 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6621 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6622 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6623 DemandedLHS, DemandedRHS))
6624 return false;
6625
6626 return (!DemandedLHS ||
6627 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6628 (!DemandedRHS ||
6629 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6630 }
6631
6632 case ISD::UADDSAT:
6633 case ISD::UMAX:
6634 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6635 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6636
6637 case ISD::UMIN:
6638 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6639 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6640
6641 // For smin/smax: If either operand is known negative/positive
6642 // respectively we don't need the other to be known at all.
6643 case ISD::SMAX: {
6644 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6645 if (Op1.isStrictlyPositive())
6646 return true;
6647
6648 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6649 if (Op0.isStrictlyPositive())
6650 return true;
6651
6652 if (Op1.isNonZero() && Op0.isNonZero())
6653 return true;
6654
6655 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6656 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6657 }
6658 case ISD::SMIN: {
6659 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6660 if (Op1.isNegative())
6661 return true;
6662
6663 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6664 if (Op0.isNegative())
6665 return true;
6666
6667 if (Op1.isNonZero() && Op0.isNonZero())
6668 return true;
6669
6670 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6671 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6672 }
6673
6674 case ISD::ROTL:
6675 case ISD::ROTR:
6676 case ISD::BITREVERSE:
6677 case ISD::BSWAP:
6678 case ISD::CTPOP:
6679 case ISD::ABS:
6681 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6682
6683 case ISD::SRA:
6684 case ISD::SRL: {
6685 if (Op->getFlags().hasExact())
6686 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6687 KnownBits ValKnown =
6688 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6689 if (ValKnown.isNegative())
6690 return true;
6691 // If max shift cnt of known ones is non-zero, result is non-zero.
6692 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6693 .getMaxValue();
6694 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6695 !ValKnown.One.lshr(MaxCnt).isZero())
6696 return true;
6697 break;
6698 }
6699 case ISD::UDIV:
6700 case ISD::SDIV:
6701 // div exact can only produce a zero if the dividend is zero.
6702 // TODO: For udiv this is also true if Op1 u<= Op0
6703 if (Op->getFlags().hasExact())
6704 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6705 break;
6706
6707 case ISD::ADD:
6708 if (Op->getFlags().hasNoUnsignedWrap())
6709 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6710 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6711 return true;
6712 // TODO: There are a lot more cases we can prove for add.
6713 break;
6714
6715 case ISD::SUB: {
6716 if (isNullConstant(Op.getOperand(0)))
6717 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6718
6719 std::optional<bool> ne = KnownBits::ne(
6720 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6721 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6722 return ne && *ne;
6723 }
6724
6725 case ISD::MUL:
6726 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6727 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6728 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6729 return true;
6730 break;
6731
6732 case ISD::ZERO_EXTEND:
6733 case ISD::SIGN_EXTEND:
6734 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6735 case ISD::VSCALE: {
6737 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6738 ConstantRange CR =
6739 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6740 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6741 return true;
6742 break;
6743 }
6744 }
6745
6746 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6747}
6748
6750 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6751 return !C1->isNegative();
6752
6753 switch (Op.getOpcode()) {
6754 case ISD::FABS:
6755 case ISD::FEXP:
6756 case ISD::FEXP2:
6757 case ISD::FEXP10:
6758 return true;
6759 default:
6760 return false;
6761 }
6762
6763 llvm_unreachable("covered opcode switch");
6764}
6765
6767 assert(Use.getValueType().isFloatingPoint());
6768 const SDNode *User = Use.getUser();
6769 if (User->getFlags().hasNoSignedZeros())
6770 return true;
6771
6772 unsigned OperandNo = Use.getOperandNo();
6773 // Check if this use is insensitive to the sign of zero
6774 switch (User->getOpcode()) {
6775 case ISD::SETCC:
6776 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6777 case ISD::FABS:
6778 // fabs always produces +0.0.
6779 return true;
6780 case ISD::FCOPYSIGN:
6781 // copysign overwrites the sign bit of the first operand.
6782 return OperandNo == 0;
6783 case ISD::FADD:
6784 case ISD::FSUB: {
6785 // Arithmetic with non-zero constants fixes the uncertainty around the
6786 // sign bit.
6787 SDValue Other = User->getOperand(1 - OperandNo);
6789 }
6790 case ISD::FP_TO_SINT:
6791 case ISD::FP_TO_UINT:
6792 // fp-to-int conversions normalize signed zeros.
6793 return true;
6794 default:
6795 return false;
6796 }
6797}
6798
6800 if (Op->getFlags().hasNoSignedZeros())
6801 return true;
6802 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6803 // regression. Ideally, this should be implemented as a demanded-bits
6804 // optimization that stems from the users.
6805 if (Op->use_size() > 2)
6806 return false;
6807 return all_of(Op->uses(),
6808 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6809}
6810
6812 // Check the obvious case.
6813 if (A == B) return true;
6814
6815 // For negative and positive zero.
6818 if (CA->isZero() && CB->isZero()) return true;
6819
6820 // Otherwise they may not be equal.
6821 return false;
6822}
6823
6824// Only bits set in Mask must be negated, other bits may be arbitrary.
6826 if (isBitwiseNot(V, AllowUndefs))
6827 return V.getOperand(0);
6828
6829 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6830 // bits in the non-extended part.
6831 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6832 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6833 return SDValue();
6834 SDValue ExtArg = V.getOperand(0);
6835 if (ExtArg.getScalarValueSizeInBits() >=
6836 MaskC->getAPIntValue().getActiveBits() &&
6837 isBitwiseNot(ExtArg, AllowUndefs) &&
6838 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6839 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6840 return ExtArg.getOperand(0).getOperand(0);
6841 return SDValue();
6842}
6843
6845 // Match masked merge pattern (X & ~M) op (Y & M)
6846 // Including degenerate case (X & ~M) op M
6847 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6848 SDValue Other) {
6849 if (SDValue NotOperand =
6850 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6851 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6852 NotOperand->getOpcode() == ISD::TRUNCATE)
6853 NotOperand = NotOperand->getOperand(0);
6854
6855 if (Other == NotOperand)
6856 return true;
6857 if (Other->getOpcode() == ISD::AND)
6858 return NotOperand == Other->getOperand(0) ||
6859 NotOperand == Other->getOperand(1);
6860 }
6861 return false;
6862 };
6863
6864 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6865 A = A->getOperand(0);
6866
6867 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6868 B = B->getOperand(0);
6869
6870 if (A->getOpcode() == ISD::AND)
6871 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6872 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6873 return false;
6874}
6875
6876// FIXME: unify with llvm::haveNoCommonBitsSet.
6878 assert(A.getValueType() == B.getValueType() &&
6879 "Values must have the same type");
6882 return true;
6885}
6886
6887static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6888 SelectionDAG &DAG) {
6889 if (cast<ConstantSDNode>(Step)->isZero())
6890 return DAG.getConstant(0, DL, VT);
6891
6892 return SDValue();
6893}
6894
6897 SelectionDAG &DAG) {
6898 int NumOps = Ops.size();
6899 assert(NumOps != 0 && "Can't build an empty vector!");
6900 assert(!VT.isScalableVector() &&
6901 "BUILD_VECTOR cannot be used with scalable types");
6902 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6903 "Incorrect element count in BUILD_VECTOR!");
6904
6905 // BUILD_VECTOR of UNDEFs is UNDEF.
6906 bool AllPoison = true;
6907 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6908 AllPoison &= Op.getOpcode() == ISD::POISON;
6909 return Op.isUndef();
6910 }))
6911 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6912
6913 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6914 SDValue IdentitySrc;
6915 bool IsIdentity = true;
6916 for (int i = 0; i != NumOps; ++i) {
6917 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6918 Ops[i].getOperand(0).getValueType() != VT ||
6919 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6920 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6921 Ops[i].getConstantOperandAPInt(1) != i) {
6922 IsIdentity = false;
6923 break;
6924 }
6925 IdentitySrc = Ops[i].getOperand(0);
6926 }
6927 if (IsIdentity)
6928 return IdentitySrc;
6929
6930 return SDValue();
6931}
6932
6933/// Try to simplify vector concatenation to an input value, undef, or build
6934/// vector.
6937 SelectionDAG &DAG) {
6938 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6940 [Ops](SDValue Op) {
6941 return Ops[0].getValueType() == Op.getValueType();
6942 }) &&
6943 "Concatenation of vectors with inconsistent value types!");
6944 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6945 VT.getVectorElementCount() &&
6946 "Incorrect element count in vector concatenation!");
6947
6948 if (Ops.size() == 1)
6949 return Ops[0];
6950
6951 // Concat of UNDEFs is UNDEF.
6952 bool AllPoison = true;
6953 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6954 AllPoison &= Op.getOpcode() == ISD::POISON;
6955 return Op.isUndef();
6956 }))
6957 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6958
6959 // Scan the operands and look for extract operations from a single source
6960 // that correspond to insertion at the same location via this concatenation:
6961 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
6962 SDValue IdentitySrc;
6963 bool IsIdentity = true;
6964 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
6965 SDValue Op = Ops[i];
6966 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
6967 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6968 Op.getOperand(0).getValueType() != VT ||
6969 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
6970 Op.getConstantOperandVal(1) != IdentityIndex) {
6971 IsIdentity = false;
6972 break;
6973 }
6974 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
6975 "Unexpected identity source vector for concat of extracts");
6976 IdentitySrc = Op.getOperand(0);
6977 }
6978 if (IsIdentity) {
6979 assert(IdentitySrc && "Failed to set source vector of extracts");
6980 return IdentitySrc;
6981 }
6982
6983 // The code below this point is only designed to work for fixed width
6984 // vectors, so we bail out for now.
6985 if (VT.isScalableVector())
6986 return SDValue();
6987
6988 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
6989 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
6990 // BUILD_VECTOR.
6991 // FIXME: Add support for SCALAR_TO_VECTOR as well.
6992 EVT SVT = VT.getScalarType();
6994 for (SDValue Op : Ops) {
6995 EVT OpVT = Op.getValueType();
6996 if (Op.getOpcode() == ISD::POISON)
6997 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
6998 else if (Op.getOpcode() == ISD::UNDEF)
6999 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7000 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7001 Elts.append(Op->op_begin(), Op->op_end());
7002 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7003 OpVT.getVectorNumElements() == 1 &&
7004 isNullConstant(Op.getOperand(2)))
7005 Elts.push_back(Op.getOperand(1));
7006 else
7007 return SDValue();
7008 }
7009
7010 // BUILD_VECTOR requires all inputs to be of the same type, find the
7011 // maximum type and extend them all.
7012 for (SDValue Op : Elts)
7013 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7014
7015 if (SVT.bitsGT(VT.getScalarType())) {
7016 for (SDValue &Op : Elts) {
7017 if (Op.getOpcode() == ISD::POISON)
7018 Op = DAG.getPOISON(SVT);
7019 else if (Op.getOpcode() == ISD::UNDEF)
7020 Op = DAG.getUNDEF(SVT);
7021 else
7022 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7023 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7024 : DAG.getSExtOrTrunc(Op, DL, SVT);
7025 }
7026 }
7027
7028 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7029 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7030 return V;
7031}
7032
7033/// Gets or creates the specified node.
7034SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7035 SDVTList VTs = getVTList(VT);
7037 AddNodeIDNode(ID, Opcode, VTs, {});
7038 FoldingSetInsertToken InsertToken;
7039 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7040 return SDValue(E, 0);
7041
7042 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7043 CSEMap.insert(N, InsertToken);
7044
7045 InsertNode(N);
7046 SDValue V = SDValue(N, 0);
7047 NewSDValueDbgMsg(V, "Creating new node: ", this);
7048 return V;
7049}
7050
7051SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7052 SDValue N1) {
7053 SDNodeFlags Flags;
7054 if (Inserter)
7055 Flags = Inserter->getFlags();
7056 return getNode(Opcode, DL, VT, N1, Flags);
7057}
7058
7059SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7060 SDValue N1, const SDNodeFlags Flags) {
7061 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7062
7063 // Constant fold unary operations with a vector integer or float operand.
7064 switch (Opcode) {
7065 default:
7066 // FIXME: Entirely reasonable to perform folding of other unary
7067 // operations here as the need arises.
7068 break;
7069 case ISD::FNEG:
7070 case ISD::FABS:
7071 case ISD::FCEIL:
7072 case ISD::FTRUNC:
7073 case ISD::FFLOOR:
7074 case ISD::FP_EXTEND:
7075 case ISD::FP_TO_SINT:
7076 case ISD::FP_TO_UINT:
7077 case ISD::FP_TO_FP16:
7078 case ISD::FP_TO_BF16:
7079 case ISD::TRUNCATE:
7080 case ISD::ANY_EXTEND:
7081 case ISD::ZERO_EXTEND:
7082 case ISD::SIGN_EXTEND:
7083 case ISD::UINT_TO_FP:
7084 case ISD::SINT_TO_FP:
7085 case ISD::FP16_TO_FP:
7086 case ISD::BF16_TO_FP:
7087 case ISD::BITCAST:
7088 case ISD::ABS:
7090 case ISD::BITREVERSE:
7091 case ISD::BSWAP:
7092 case ISD::CTLZ:
7094 case ISD::CTTZ:
7096 case ISD::CTPOP:
7097 case ISD::CTLS:
7098 case ISD::VECREDUCE_ADD:
7103 case ISD::VECREDUCE_MUL:
7104 case ISD::VECREDUCE_AND:
7105 case ISD::VECREDUCE_OR:
7106 case ISD::VECREDUCE_XOR:
7107 case ISD::STEP_VECTOR: {
7108 SDValue Ops = {N1};
7109 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7110 return Fold;
7111 }
7112 }
7113
7114 unsigned OpOpcode = N1.getNode()->getOpcode();
7115 switch (Opcode) {
7116 case ISD::STEP_VECTOR:
7117 assert(VT.isScalableVector() &&
7118 "STEP_VECTOR can only be used with scalable types");
7119 assert(OpOpcode == ISD::TargetConstant &&
7120 VT.getVectorElementType() == N1.getValueType() &&
7121 "Unexpected step operand");
7122 break;
7123 case ISD::FREEZE:
7124 assert(VT == N1.getValueType() && "Unexpected VT!");
7126 return N1;
7127 break;
7128 case ISD::TokenFactor:
7129 case ISD::MERGE_VALUES:
7131 return N1; // Factor, merge or concat of one node? No need.
7132 case ISD::BUILD_VECTOR: {
7133 // Attempt to simplify BUILD_VECTOR.
7134 SDValue Ops[] = {N1};
7135 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7136 return V;
7137 break;
7138 }
7139 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7140 case ISD::FP_EXTEND:
7142 "Invalid FP cast!");
7143 if (N1.getValueType() == VT) return N1; // noop conversion.
7144 assert((!VT.isVector() || VT.getVectorElementCount() ==
7146 "Vector element count mismatch!");
7147 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7148 if (N1.isUndef())
7149 return getUNDEF(VT);
7150 break;
7151 case ISD::FP_TO_SINT:
7152 case ISD::FP_TO_UINT:
7153 if (N1.isUndef())
7154 return getUNDEF(VT);
7155 break;
7156 case ISD::SINT_TO_FP:
7157 case ISD::UINT_TO_FP:
7158 // [us]itofp(undef) = 0, because the result value is bounded.
7159 if (N1.isUndef())
7160 return getConstantFP(0.0, DL, VT);
7161 break;
7162 case ISD::SIGN_EXTEND:
7163 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7164 "Invalid SIGN_EXTEND!");
7165 assert(VT.isVector() == N1.getValueType().isVector() &&
7166 "SIGN_EXTEND result type type should be vector iff the operand "
7167 "type is vector!");
7168 if (N1.getValueType() == VT) return N1; // noop extension
7169 assert((!VT.isVector() || VT.getVectorElementCount() ==
7171 "Vector element count mismatch!");
7172 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7173 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7174 SDNodeFlags Flags;
7175 if (OpOpcode == ISD::ZERO_EXTEND)
7176 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7177 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7178 transferDbgValues(N1, NewVal);
7179 return NewVal;
7180 }
7181
7182 if (OpOpcode == ISD::POISON)
7183 return getPOISON(VT);
7184
7185 if (N1.isUndef())
7186 // sext(undef) = 0, because the top bits will all be the same.
7187 return getConstant(0, DL, VT);
7188
7189 // Skip unnecessary sext_inreg pattern:
7190 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7191 if (OpOpcode == ISD::TRUNCATE) {
7192 SDValue OpOp = N1.getOperand(0);
7193 if (OpOp.getValueType() == VT) {
7194 unsigned NumSignExtBits =
7196 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7197 transferDbgValues(N1, OpOp);
7198 return OpOp;
7199 }
7200 }
7201 }
7202 break;
7203 case ISD::ZERO_EXTEND:
7204 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7205 "Invalid ZERO_EXTEND!");
7206 assert(VT.isVector() == N1.getValueType().isVector() &&
7207 "ZERO_EXTEND result type type should be vector iff the operand "
7208 "type is vector!");
7209 if (N1.getValueType() == VT) return N1; // noop extension
7210 assert((!VT.isVector() || VT.getVectorElementCount() ==
7212 "Vector element count mismatch!");
7213 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7214 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7215 SDNodeFlags Flags;
7216 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7217 SDValue NewVal =
7218 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7219 transferDbgValues(N1, NewVal);
7220 return NewVal;
7221 }
7222
7223 if (OpOpcode == ISD::POISON)
7224 return getPOISON(VT);
7225
7226 if (N1.isUndef())
7227 // zext(undef) = 0, because the top bits will be zero.
7228 return getConstant(0, DL, VT);
7229
7230 // Skip unnecessary zext_inreg pattern:
7231 // (zext (trunc x)) -> x iff the upper bits are known zero.
7232 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7233 // use to recognise zext_inreg patterns.
7234 if (OpOpcode == ISD::TRUNCATE) {
7235 SDValue OpOp = N1.getOperand(0);
7236 if (OpOp.getValueType() == VT) {
7237 if (OpOp.getOpcode() != ISD::AND) {
7240 if (MaskedValueIsZero(OpOp, HiBits)) {
7241 transferDbgValues(N1, OpOp);
7242 return OpOp;
7243 }
7244 }
7245 }
7246 }
7247 break;
7248 case ISD::ANY_EXTEND:
7249 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7250 "Invalid ANY_EXTEND!");
7251 assert(VT.isVector() == N1.getValueType().isVector() &&
7252 "ANY_EXTEND result type type should be vector iff the operand "
7253 "type is vector!");
7254 if (N1.getValueType() == VT) return N1; // noop extension
7255 assert((!VT.isVector() || VT.getVectorElementCount() ==
7257 "Vector element count mismatch!");
7258 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7259
7260 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7261 OpOpcode == ISD::ANY_EXTEND) {
7262 SDNodeFlags Flags;
7263 if (OpOpcode == ISD::ZERO_EXTEND)
7264 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7265 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7266 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7267 }
7268 if (N1.isUndef())
7269 return getUNDEF(VT);
7270
7271 // (ext (trunc x)) -> x
7272 if (OpOpcode == ISD::TRUNCATE) {
7273 SDValue OpOp = N1.getOperand(0);
7274 if (OpOp.getValueType() == VT) {
7275 transferDbgValues(N1, OpOp);
7276 return OpOp;
7277 }
7278 }
7279 break;
7280 case ISD::TRUNCATE:
7281 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7282 "Invalid TRUNCATE!");
7283 assert(VT.isVector() == N1.getValueType().isVector() &&
7284 "TRUNCATE result type type should be vector iff the operand "
7285 "type is vector!");
7286 if (N1.getValueType() == VT) return N1; // noop truncate
7287 assert((!VT.isVector() || VT.getVectorElementCount() ==
7289 "Vector element count mismatch!");
7290 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7291 if (OpOpcode == ISD::TRUNCATE)
7292 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7293 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7294 OpOpcode == ISD::ANY_EXTEND) {
7295 // If the source is smaller than the dest, we still need an extend.
7297 VT.getScalarType())) {
7298 SDNodeFlags Flags;
7299 if (OpOpcode == ISD::ZERO_EXTEND)
7300 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7301 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7302 }
7303 if (N1.getOperand(0).getValueType().bitsGT(VT))
7304 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7305 return N1.getOperand(0);
7306 }
7307 if (N1.isUndef())
7308 return getUNDEF(VT);
7309 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7310 return getVScale(DL, VT,
7312 break;
7316 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7317 assert(N1.getValueType().bitsLE(VT) &&
7318 "The input must be the same size or smaller than the result.");
7321 "The destination vector type must have fewer lanes than the input.");
7322 break;
7323 case ISD::ABS:
7324 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7325 if (N1.isUndef())
7326 return getConstant(0, DL, VT);
7327 break;
7329 assert(VT.isInteger() && VT == N1.getValueType() &&
7330 "Invalid ABS_MIN_POISON!");
7331 if (N1.isUndef())
7332 return getConstant(0, DL, VT);
7333 break;
7334 case ISD::BSWAP:
7335 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7336 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7337 "BSWAP types must be a multiple of 16 bits!");
7338 if (N1.isUndef())
7339 return getUNDEF(VT);
7340 // bswap(bswap(X)) -> X.
7341 if (OpOpcode == ISD::BSWAP)
7342 return N1.getOperand(0);
7343 break;
7344 case ISD::BITREVERSE:
7345 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7346 if (N1.isUndef())
7347 return getUNDEF(VT);
7348 break;
7349 case ISD::BITCAST:
7351 "Cannot BITCAST between types of different sizes!");
7352 if (VT == N1.getValueType()) return N1; // noop conversion.
7353 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7354 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7355 if (N1.isUndef())
7356 return getUNDEF(VT);
7357 break;
7359 assert(VT.isVector() && !N1.getValueType().isVector() &&
7360 (VT.getVectorElementType() == N1.getValueType() ||
7362 N1.getValueType().isInteger() &&
7364 "Illegal SCALAR_TO_VECTOR node!");
7365 if (N1.isUndef())
7366 return getUNDEF(VT);
7367 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7368 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7370 N1.getConstantOperandVal(1) == 0 &&
7371 N1.getOperand(0).getValueType() == VT)
7372 return N1.getOperand(0);
7373 break;
7374 case ISD::FNEG:
7375 // Negation of an unknown bag of bits is still completely undefined.
7376 if (N1.isUndef())
7377 return getUNDEF(VT);
7378
7379 if (OpOpcode == ISD::FNEG) // --X -> X
7380 return N1.getOperand(0);
7381 break;
7382 case ISD::FABS:
7383 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7384 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7385 break;
7386 case ISD::VSCALE:
7387 assert(VT == N1.getValueType() && "Unexpected VT!");
7388 break;
7389 case ISD::CTPOP:
7390 if (N1.getValueType().getScalarType() == MVT::i1)
7391 return N1;
7392 break;
7393 case ISD::CTLZ:
7394 case ISD::CTTZ:
7395 if (N1.getValueType().getScalarType() == MVT::i1)
7396 return getNOT(DL, N1, N1.getValueType());
7397 break;
7398 case ISD::CTLS:
7399 if (N1.getValueType().getScalarType() == MVT::i1)
7400 return getConstant(0, DL, VT);
7401 break;
7402 case ISD::VECREDUCE_ADD:
7403 if (N1.getValueType().getScalarType() == MVT::i1)
7404 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7405 break;
7408 if (N1.getValueType().getScalarType() == MVT::i1)
7409 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7410 break;
7413 if (N1.getValueType().getScalarType() == MVT::i1)
7414 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7415 break;
7416 case ISD::SPLAT_VECTOR:
7417 assert(VT.isVector() && "Wrong return type!");
7418 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7419 // that for now.
7421 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7423 N1.getValueType().isInteger() &&
7425 "Wrong operand type!");
7426 break;
7427 }
7428
7429 SDNode *N;
7430 SDVTList VTs = getVTList(VT);
7431 SDValue Ops[] = {N1};
7432 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7434 AddNodeIDNode(ID, Opcode, VTs, Ops);
7435 FoldingSetInsertToken InsertToken;
7436 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7437 E->intersectFlagsWith(Flags);
7438 return SDValue(E, 0);
7439 }
7440
7441 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7442 N->setFlags(Flags);
7443 createOperands(N, Ops);
7444 CSEMap.insert(N, InsertToken);
7445 } else {
7446 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7447 createOperands(N, Ops);
7448 }
7449
7450 InsertNode(N);
7451 SDValue V = SDValue(N, 0);
7452 NewSDValueDbgMsg(V, "Creating new node: ", this);
7453 return V;
7454}
7455
7456static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7457 switch (Opcode) {
7458 default:
7459 llvm_unreachable("Unexpected integer identity opcode");
7460 case ISD::ADD:
7461 case ISD::OR:
7462 case ISD::XOR:
7463 case ISD::UMAX:
7464 return APInt::getZero(BitWidth);
7465 case ISD::MUL:
7466 return APInt(BitWidth, 1);
7467 case ISD::AND:
7468 case ISD::UMIN:
7470 case ISD::SMAX:
7472 case ISD::SMIN:
7474 }
7475}
7476
7477static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7478 const APInt &C2) {
7479 switch (Opcode) {
7480 case ISD::ADD: return C1 + C2;
7481 case ISD::SUB: return C1 - C2;
7482 case ISD::MUL: return C1 * C2;
7483 case ISD::AND: return C1 & C2;
7484 case ISD::OR: return C1 | C2;
7485 case ISD::XOR: return C1 ^ C2;
7486 case ISD::SHL: return C1 << C2;
7487 case ISD::SRL: return C1.lshr(C2);
7488 case ISD::SRA: return C1.ashr(C2);
7489 case ISD::ROTL: return C1.rotl(C2);
7490 case ISD::ROTR: return C1.rotr(C2);
7491 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7492 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7493 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7494 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7495 case ISD::SADDSAT: return C1.sadd_sat(C2);
7496 case ISD::UADDSAT: return C1.uadd_sat(C2);
7497 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7498 case ISD::USUBSAT: return C1.usub_sat(C2);
7499 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7500 case ISD::USHLSAT: return C1.ushl_sat(C2);
7501 case ISD::UDIV:
7502 if (!C2.getBoolValue())
7503 break;
7504 return C1.udiv(C2);
7505 case ISD::UREM:
7506 if (!C2.getBoolValue())
7507 break;
7508 return C1.urem(C2);
7509 case ISD::SDIV:
7510 if (!C2.getBoolValue())
7511 break;
7512 return C1.sdiv(C2);
7513 case ISD::SREM:
7514 if (!C2.getBoolValue())
7515 break;
7516 return C1.srem(C2);
7517 case ISD::AVGFLOORS:
7518 return APIntOps::avgFloorS(C1, C2);
7519 case ISD::AVGFLOORU:
7520 return APIntOps::avgFloorU(C1, C2);
7521 case ISD::AVGCEILS:
7522 return APIntOps::avgCeilS(C1, C2);
7523 case ISD::AVGCEILU:
7524 return APIntOps::avgCeilU(C1, C2);
7525 case ISD::ABDS:
7526 return APIntOps::abds(C1, C2);
7527 case ISD::ABDU:
7528 return APIntOps::abdu(C1, C2);
7529 case ISD::MULHS:
7530 return APIntOps::mulhs(C1, C2);
7531 case ISD::MULHU:
7532 return APIntOps::mulhu(C1, C2);
7533 case ISD::CLMUL:
7534 return APIntOps::clmul(C1, C2);
7535 case ISD::CLMULR:
7536 return APIntOps::clmulr(C1, C2);
7537 case ISD::CLMULH:
7538 return APIntOps::clmulh(C1, C2);
7539 case ISD::PEXT:
7540 return APIntOps::pext(C1, C2);
7541 case ISD::PDEP:
7542 return APIntOps::pdep(C1, C2);
7543 }
7544 return std::nullopt;
7545}
7546// Handle constant folding with UNDEF.
7547// TODO: Handle more cases.
7548static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7549 bool IsUndef1, const APInt &C2,
7550 bool IsUndef2) {
7551 if (!(IsUndef1 || IsUndef2))
7552 return FoldValue(Opcode, C1, C2);
7553
7554 // Fold and(x, undef) -> 0
7555 // Fold mul(x, undef) -> 0
7556 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7557 return APInt::getZero(C1.getBitWidth());
7558
7559 return std::nullopt;
7560}
7561
7563 const GlobalAddressSDNode *GA,
7564 const SDNode *N2) {
7565 if (GA->getOpcode() != ISD::GlobalAddress)
7566 return SDValue();
7567 if (!TLI->isOffsetFoldingLegal(GA))
7568 return SDValue();
7569 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7570 if (!C2)
7571 return SDValue();
7572 int64_t Offset = C2->getSExtValue();
7573 switch (Opcode) {
7574 case ISD::ADD:
7575 case ISD::PTRADD:
7576 break;
7577 case ISD::SUB: Offset = -uint64_t(Offset); break;
7578 default: return SDValue();
7579 }
7580 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7581 GA->getOffset() + uint64_t(Offset));
7582}
7583
7585 switch (Opcode) {
7586 case ISD::SDIV:
7587 case ISD::UDIV:
7588 case ISD::SREM:
7589 case ISD::UREM: {
7590 // If a divisor is zero/undef or any element of a divisor vector is
7591 // zero/undef, the whole op is undef.
7592 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7593 SDValue Divisor = Ops[1];
7594 if (Divisor.isUndef() || isNullConstant(Divisor))
7595 return true;
7596
7597 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7598 llvm::any_of(Divisor->op_values(),
7599 [](SDValue V) { return V.isUndef() ||
7600 isNullConstant(V); });
7601 // TODO: Handle signed overflow.
7602 }
7603 // TODO: Handle oversized shifts.
7604 default:
7605 return false;
7606 }
7607}
7608
7611 SDNodeFlags Flags) {
7612 // If the opcode is a target-specific ISD node, there's nothing we can
7613 // do here and the operand rules may not line up with the below, so
7614 // bail early.
7615 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7616 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7617 // foldCONCAT_VECTORS in getNode before this is called.
7618 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7619 return SDValue();
7620
7621 unsigned NumOps = Ops.size();
7622 if (NumOps == 0)
7623 return SDValue();
7624
7625 if (isUndef(Opcode, Ops))
7626 return getUNDEF(VT);
7627
7628 // Handle unary special cases.
7629 if (NumOps == 1) {
7630 SDValue N1 = Ops[0];
7631
7632 // Constant fold unary operations with an integer constant operand. Even
7633 // opaque constant will be folded, because the folding of unary operations
7634 // doesn't create new constants with different values. Nevertheless, the
7635 // opaque flag is preserved during folding to prevent future folding with
7636 // other constants.
7637 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7638 const APInt &Val = C->getAPIntValue();
7639 switch (Opcode) {
7640 case ISD::SIGN_EXTEND:
7641 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7642 C->isTargetOpcode(), C->isOpaque());
7643 case ISD::TRUNCATE:
7644 if (C->isOpaque())
7645 break;
7646 [[fallthrough]];
7647 case ISD::ZERO_EXTEND:
7648 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7649 C->isTargetOpcode(), C->isOpaque());
7650 case ISD::ANY_EXTEND:
7651 // Some targets like RISCV prefer to sign extend some types.
7652 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7653 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7654 C->isTargetOpcode(), C->isOpaque());
7655 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7656 C->isTargetOpcode(), C->isOpaque());
7657 case ISD::ABS:
7658 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7659 C->isOpaque());
7661 if (Val.isMinSignedValue())
7662 return getPOISON(VT);
7663 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7664 C->isOpaque());
7665 case ISD::BITREVERSE:
7666 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7667 C->isOpaque());
7668 case ISD::BSWAP:
7669 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7670 C->isOpaque());
7671 case ISD::CTPOP:
7672 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7673 C->isOpaque());
7674 case ISD::CTLZ:
7676 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7677 C->isOpaque());
7678 case ISD::CTTZ:
7680 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7681 C->isOpaque());
7682 case ISD::CTLS:
7683 // CTLS returns the number of extra sign bits so subtract one.
7684 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7685 C->isTargetOpcode(), C->isOpaque());
7686 case ISD::UINT_TO_FP:
7687 case ISD::SINT_TO_FP: {
7689 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7691 return getConstantFP(FPV, DL, VT);
7692 }
7693 case ISD::FP16_TO_FP:
7694 case ISD::BF16_TO_FP: {
7695 bool Ignored;
7696 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7697 : APFloat::BFloat(),
7698 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7699
7700 // This can return overflow, underflow, or inexact; we don't care.
7701 // FIXME need to be more flexible about rounding mode.
7703 &Ignored);
7704 return getConstantFP(FPV, DL, VT);
7705 }
7706 case ISD::STEP_VECTOR:
7707 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7708 return V;
7709 break;
7710 case ISD::BITCAST:
7711 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7712 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7713 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7714 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7715 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7716 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7717 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7718 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7719 break;
7720 }
7721 }
7722
7723 // Constant fold unary operations with a floating point constant operand.
7724 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7725 APFloat V = C->getValueAPF(); // make copy
7726 switch (Opcode) {
7727 case ISD::FNEG:
7728 V.changeSign();
7729 return getConstantFP(V, DL, VT);
7730 case ISD::FABS:
7731 V.clearSign();
7732 return getConstantFP(V, DL, VT);
7733 case ISD::FCEIL: {
7734 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7736 return getConstantFP(V, DL, VT);
7737 return SDValue();
7738 }
7739 case ISD::FTRUNC: {
7740 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7742 return getConstantFP(V, DL, VT);
7743 return SDValue();
7744 }
7745 case ISD::FFLOOR: {
7746 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7748 return getConstantFP(V, DL, VT);
7749 return SDValue();
7750 }
7751 case ISD::FP_EXTEND: {
7752 bool ignored;
7753 // This can return overflow, underflow, or inexact; we don't care.
7754 // FIXME need to be more flexible about rounding mode.
7755 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7756 &ignored);
7757 return getConstantFP(V, DL, VT);
7758 }
7759 case ISD::FP_TO_SINT:
7760 case ISD::FP_TO_UINT: {
7761 bool ignored;
7762 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7763 // FIXME need to be more flexible about rounding mode.
7765 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7766 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7767 break;
7768 return getConstant(IntVal, DL, VT);
7769 }
7770 case ISD::FP_TO_FP16:
7771 case ISD::FP_TO_BF16: {
7772 bool Ignored;
7773 // This can return overflow, underflow, or inexact; we don't care.
7774 // FIXME need to be more flexible about rounding mode.
7775 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7776 : APFloat::BFloat(),
7778 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7779 }
7780 case ISD::BITCAST:
7781 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7782 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7783 VT);
7784 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7785 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7786 VT);
7787 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7788 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7789 VT);
7790 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7791 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7792 break;
7793 }
7794 }
7795
7796 // Early-out if we failed to constant fold a bitcast.
7797 if (Opcode == ISD::BITCAST)
7798 return SDValue();
7799
7800 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7801 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7802 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7803 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7804 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7805 Opcode == ISD::VECREDUCE_AND) &&
7807 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7808 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7809 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7810 for (SDValue Elt : N1->op_values()) {
7811 if (Elt.getOpcode() == ISD::POISON)
7812 return getPOISON(VT);
7813 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7814 return SDValue();
7815 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7816 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7817 assert(Folded &&
7818 "Expected vector reduction base opcode to be foldable");
7819 Acc = *Folded;
7820 }
7821 EVT EltVT = N1.getValueType().getScalarType();
7822 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7823 }
7824 }
7825
7826 // Handle binops special cases.
7827 if (NumOps == 2) {
7828 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7829 return CFP;
7830
7831 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7832 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7833 if (C1->isOpaque() || C2->isOpaque())
7834 return SDValue();
7835
7836 std::optional<APInt> FoldAttempt =
7837 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7838 if (!FoldAttempt)
7839 return SDValue();
7840
7841 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7842 assert((!Folded || !VT.isVector()) &&
7843 "Can't fold vectors ops with scalar operands");
7844 return Folded;
7845 }
7846 }
7847
7848 // fold (add Sym, c) -> Sym+c
7850 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7851 if (TLI->isCommutativeBinOp(Opcode))
7853 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7854
7855 // fold (sext_in_reg c1) -> c2
7856 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7857 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7858
7859 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7860 unsigned FromBits = EVT.getScalarSizeInBits();
7861 Val <<= Val.getBitWidth() - FromBits;
7862 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7863 return getConstant(Val, DL, ConstantVT);
7864 };
7865
7866 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7867 const APInt &Val = C1->getAPIntValue();
7868 return SignExtendInReg(Val, VT);
7869 }
7870
7872 SmallVector<SDValue, 8> ScalarOps;
7873 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7874 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7875 SDValue Op = Ops[0].getOperand(I);
7876 if (Op.isUndef()) {
7877 ScalarOps.push_back(getUNDEF(OpVT));
7878 continue;
7879 }
7880 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7881 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7882 }
7883 return getBuildVector(VT, DL, ScalarOps);
7884 }
7885
7886 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7887 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7888 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7889 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7890 Ops[0].getOperand(0).getValueType()));
7891 }
7892 }
7893
7894 // Handle fshl/fshr special cases.
7895 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7896 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7897 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7898 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7899
7900 if (C1 && C2 && C3) {
7901 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7902 return SDValue();
7903 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7904 &V3 = C3->getAPIntValue();
7905
7906 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7907 : APIntOps::fshr(V1, V2, V3);
7908 return getConstant(FoldedVal, DL, VT);
7909 }
7910 }
7911
7912 // Handle fma/fmad special cases.
7913 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7914 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7915 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7916 Ops[2].getValueType() == VT && "FMA types must match!");
7920 if (C1 && C2 && C3) {
7921 APFloat V1 = C1->getValueAPF();
7922 const APFloat &V2 = C2->getValueAPF();
7923 const APFloat &V3 = C3->getValueAPF();
7924 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7925 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7927 } else
7928 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7929 return getConstantFP(V1, DL, VT);
7930 }
7931 }
7932
7933 // This is for vector folding only from here on.
7934 if (!VT.isVector())
7935 return SDValue();
7936
7937 // Constant fold integer partial reductions with constant BUILD_VECTOR
7938 // operands. The reduction order is deliberately unspecified. Use the same
7939 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
7940 // lane I contributes to accumulator lane I % NumAccElts.
7941 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
7942 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
7943 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
7944 // These nodes have no scalar form, so unsupported cases must not fall
7945 // through to generic per-lane vector folding.
7946 if (!llvm::all_of(Ops, [](SDValue Op) {
7947 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
7948 }))
7949 return SDValue();
7950
7951 unsigned AccEltBits = VT.getScalarSizeInBits();
7952 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
7953 unsigned NumAccElts = VT.getVectorNumElements();
7954 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
7955 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
7956 BitVector PoisonElts(NumAccElts);
7957
7958 for (unsigned I = 0; I != NumAccElts; ++I) {
7959 SDValue Elt = Ops[0].getOperand(I);
7960 if (Elt.getOpcode() == ISD::POISON) {
7961 PoisonElts.set(I);
7962 continue;
7963 }
7964 auto *C = dyn_cast<ConstantSDNode>(Elt);
7965 if (!C || C->isOpaque())
7966 return SDValue();
7967 Results[I] = C->getAPIntValue().trunc(AccEltBits);
7968 }
7969
7970 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
7971 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
7972 for (unsigned I = 0; I != NumInputElts; ++I) {
7973 const unsigned AccIdx = I % NumAccElts;
7974 SDValue LHSElt = Ops[1].getOperand(I);
7975 SDValue RHSElt = Ops[2].getOperand(I);
7976 if (LHSElt.getOpcode() == ISD::POISON ||
7977 RHSElt.getOpcode() == ISD::POISON) {
7978 PoisonElts.set(AccIdx);
7979 continue;
7980 }
7981
7982 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
7983 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
7984 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
7985 return SDValue();
7986
7987 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
7988 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
7989 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
7990 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
7991 Results[AccIdx] += LHSVal * RHSVal;
7992 }
7993
7994 // After type legalization the vector element type may not be a legal
7995 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
7996 // promoted legal scalar type instead, matching the generic per-lane path
7997 // below. Bail out if legalization would narrow the type, since the lane
7998 // value would not fit.
7999 EVT AccEltVT = VT.getVectorElementType();
8000 EVT LegalSVT = AccEltVT;
8001 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8002 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8003 if (LegalSVT.bitsLT(AccEltVT))
8004 return SDValue();
8005 }
8006
8007 SmallVector<SDValue, 8> ResultOps;
8008 for (unsigned I = 0; I != NumAccElts; ++I)
8009 ResultOps.push_back(
8010 PoisonElts[I] ? getPOISON(LegalSVT)
8011 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8012 DL, LegalSVT));
8013 return getBuildVector(VT, DL, ResultOps);
8014 }
8015
8016 ElementCount NumElts = VT.getVectorElementCount();
8017
8018 // See if we can fold through any bitcasted integer ops.
8019 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8020 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8021 (Ops[0].getOpcode() == ISD::BITCAST ||
8022 Ops[1].getOpcode() == ISD::BITCAST)) {
8025 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8026 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8027 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8028 N2.getValueType().isInteger()) {
8029 bool IsLE = getDataLayout().isLittleEndian();
8030 unsigned EltBits = VT.getScalarSizeInBits();
8031 SmallVector<APInt> RawBits1, RawBits2;
8032 BitVector UndefElts1, UndefElts2;
8033 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8034 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8035 SmallVector<APInt> RawBits;
8036 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8037 std::optional<APInt> Fold = FoldValueWithUndef(
8038 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8039 if (!Fold)
8040 break;
8041 RawBits.push_back(*Fold);
8042 }
8043 if (RawBits.size() == NumElts.getFixedValue()) {
8044 // We have constant folded, but we might need to cast this again back
8045 // to the original (possibly legalized) type.
8046 EVT BVVT, BVEltVT;
8047 if (N1.getValueType() == VT) {
8048 BVVT = N1.getValueType();
8049 BVEltVT = BV1->getOperand(0).getValueType();
8050 } else {
8051 BVVT = N2.getValueType();
8052 BVEltVT = BV2->getOperand(0).getValueType();
8053 }
8054 unsigned BVEltBits = BVEltVT.getSizeInBits();
8055 SmallVector<APInt> DstBits;
8056 BitVector DstUndefs;
8058 DstBits, RawBits, DstUndefs,
8059 BitVector(RawBits.size(), false));
8060 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8061 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8062 if (DstUndefs[I])
8063 continue;
8064 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8065 }
8066 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8067 }
8068 }
8069 }
8070 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8071 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8072 isa<ConstantSDNode>(N2)) {
8073 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8074 {N1, N2}, Flags))
8075 return getBitcast(VT, Res);
8076 }
8077 }
8078
8079 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8080 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8081 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8082 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8083 APInt RHSVal;
8084 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8085 APInt NewStep = Opcode == ISD::MUL
8086 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8087 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8088 return getStepVector(DL, VT, NewStep);
8089 }
8090 }
8091
8092 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8093 return !Op.getValueType().isVector() ||
8094 Op.getValueType().getVectorElementCount() == NumElts;
8095 };
8096
8097 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8098 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8099 Op.getOpcode() == ISD::BUILD_VECTOR ||
8100 Op.getOpcode() == ISD::SPLAT_VECTOR;
8101 };
8102
8103 // All operands must be vector types with the same number of elements as
8104 // the result type and must be either UNDEF or a build/splat vector
8105 // or UNDEF scalars.
8106 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8107 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8108 return SDValue();
8109
8110 // If we are comparing vectors, then the result needs to be a i1 boolean that
8111 // is then extended back to the legal result type depending on how booleans
8112 // are represented.
8113 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8114 ISD::NodeType ExtendCode =
8115 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8116 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8118
8119 // Find legal integer scalar type for constant promotion and
8120 // ensure that its scalar size is at least as large as source.
8121 EVT LegalSVT = VT.getScalarType();
8122 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8123 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8124 if (LegalSVT.bitsLT(VT.getScalarType()))
8125 return SDValue();
8126 }
8127
8128 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8129 // only have one operand to check. For fixed-length vector types we may have
8130 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8131 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8132
8133 // Constant fold each scalar lane separately.
8134 SmallVector<SDValue, 4> ScalarResults;
8135 for (unsigned I = 0; I != NumVectorElts; I++) {
8136 SmallVector<SDValue, 4> ScalarOps;
8137 for (SDValue Op : Ops) {
8138 EVT InSVT = Op.getValueType().getScalarType();
8139 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8140 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8141 if (Op.isUndef())
8142 ScalarOps.push_back(getUNDEF(InSVT));
8143 else
8144 ScalarOps.push_back(Op);
8145 continue;
8146 }
8147
8148 SDValue ScalarOp =
8149 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8150 EVT ScalarVT = ScalarOp.getValueType();
8151
8152 // Build vector (integer) scalar operands may need implicit
8153 // truncation - do this before constant folding.
8154 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8155 // Don't create illegally-typed nodes unless they're constants or undef
8156 // - if we fail to constant fold we can't guarantee the (dead) nodes
8157 // we're creating will be cleaned up before being visited for
8158 // legalization.
8159 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8160 !isa<ConstantSDNode>(ScalarOp) &&
8161 TLI->getTypeAction(*getContext(), InSVT) !=
8163 return SDValue();
8164 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8165 }
8166
8167 ScalarOps.push_back(ScalarOp);
8168 }
8169
8170 // Constant fold the scalar operands.
8171 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8172
8173 // Scalar folding only succeeded if the result is a constant or UNDEF.
8174 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8175 ScalarResult.getOpcode() != ISD::ConstantFP)
8176 return SDValue();
8177
8178 // Legalize the (integer) scalar constant if necessary. We only do
8179 // this once we know the folding succeeded, since otherwise we would
8180 // get a node with illegal type which has a user.
8181 if (LegalSVT != SVT)
8182 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8183
8184 ScalarResults.push_back(ScalarResult);
8185 }
8186
8187 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8188 : getBuildVector(VT, DL, ScalarResults);
8189 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8190 return V;
8191}
8192
8195 // TODO: Add support for unary/ternary fp opcodes.
8196 if (Ops.size() != 2)
8197 return SDValue();
8198
8199 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8200 // should. That will require dealing with a potentially non-default
8201 // rounding mode, checking the "opStatus" return value from the APFloat
8202 // math calculations, and possibly other variations.
8203 SDValue N1 = Ops[0];
8204 SDValue N2 = Ops[1];
8205 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8206 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8207 if (N1CFP && N2CFP) {
8208 APFloat C1 = N1CFP->getValueAPF(); // make copy
8209 const APFloat &C2 = N2CFP->getValueAPF();
8210 switch (Opcode) {
8211 case ISD::FADD:
8213 return getConstantFP(C1, DL, VT);
8214 case ISD::FSUB:
8216 return getConstantFP(C1, DL, VT);
8217 case ISD::FMUL:
8219 return getConstantFP(C1, DL, VT);
8220 case ISD::FDIV:
8222 return getConstantFP(C1, DL, VT);
8223 case ISD::FREM:
8224 C1.mod(C2);
8225 return getConstantFP(C1, DL, VT);
8226 case ISD::FCOPYSIGN:
8227 C1.copySign(C2);
8228 return getConstantFP(C1, DL, VT);
8229 case ISD::FMINNUM:
8230 return getConstantFP(minnum(C1, C2), DL, VT);
8231 case ISD::FMAXNUM:
8232 return getConstantFP(maxnum(C1, C2), DL, VT);
8233 case ISD::FMINIMUM:
8234 return getConstantFP(minimum(C1, C2), DL, VT);
8235 case ISD::FMAXIMUM:
8236 return getConstantFP(maximum(C1, C2), DL, VT);
8237 case ISD::FMINIMUMNUM:
8238 return getConstantFP(minimumnum(C1, C2), DL, VT);
8239 case ISD::FMAXIMUMNUM:
8240 return getConstantFP(maximumnum(C1, C2), DL, VT);
8241 default: break;
8242 }
8243 }
8244 if (N1CFP && Opcode == ISD::FP_ROUND) {
8245 APFloat C1 = N1CFP->getValueAPF(); // make copy
8246 bool Unused;
8247 // This can return overflow, underflow, or inexact; we don't care.
8248 // FIXME need to be more flexible about rounding mode.
8250 &Unused);
8251 return getConstantFP(C1, DL, VT);
8252 }
8253
8254 switch (Opcode) {
8255 case ISD::FSUB:
8256 // -0.0 - undef --> undef (consistent with "fneg undef")
8257 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8258 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8259 return getUNDEF(VT);
8260 [[fallthrough]];
8261
8262 case ISD::FADD:
8263 case ISD::FMUL:
8264 case ISD::FDIV:
8265 case ISD::FREM:
8266 // If both operands are undef, the result is undef. If 1 operand is undef,
8267 // the result is NaN. This should match the behavior of the IR optimizer.
8268 if (N1.isUndef() && N2.isUndef())
8269 return getUNDEF(VT);
8270 if (N1.isUndef() || N2.isUndef())
8272 }
8273 return SDValue();
8274}
8275
8277 const SDLoc &DL, EVT DstEltVT) {
8278 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8279
8280 // If this is already the right type, we're done.
8281 if (SrcEltVT == DstEltVT)
8282 return SDValue(BV, 0);
8283
8284 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8285 unsigned DstBitSize = DstEltVT.getSizeInBits();
8286
8287 // If this is a conversion of N elements of one type to N elements of another
8288 // type, convert each element. This handles FP<->INT cases.
8289 if (SrcBitSize == DstBitSize) {
8291 for (SDValue Op : BV->op_values()) {
8292 // If the vector element type is not legal, the BUILD_VECTOR operands
8293 // are promoted and implicitly truncated. Make that explicit here.
8294 if (Op.getValueType() != SrcEltVT)
8295 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8296 Ops.push_back(getBitcast(DstEltVT, Op));
8297 }
8298 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8300 return getBuildVector(VT, DL, Ops);
8301 }
8302
8303 // Otherwise, we're growing or shrinking the elements. To avoid having to
8304 // handle annoying details of growing/shrinking FP values, we convert them to
8305 // int first.
8306 if (SrcEltVT.isFloatingPoint()) {
8307 // Convert the input float vector to a int vector where the elements are the
8308 // same sizes.
8309 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());