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 "vscale-unroll-limit",
120 cl::desc("Maximum vscale for which vector unrolling is allowed."),
121 cl::Hidden, cl::init(64));
122
124 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
125}
126
128
129//===----------------------------------------------------------------------===//
130// ConstantFPSDNode Class
131//===----------------------------------------------------------------------===//
132
133/// isExactlyValue - We don't rely on operator== working on double values, as
134/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
135/// As such, this method can be used to do an exact bit-for-bit comparison of
136/// two floating point values.
138 return getValueAPF().bitwiseIsEqual(V);
139}
140
142 const APFloat& Val) {
143 assert(VT.isFloatingPoint() && "Can only convert between FP types");
144
145 // convert modifies in place, so make a copy.
146 APFloat Val2 = APFloat(Val);
147 bool losesInfo;
149 &losesInfo);
150 return !losesInfo;
151}
152
153//===----------------------------------------------------------------------===//
154// ISD Namespace
155//===----------------------------------------------------------------------===//
156
157bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
158 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
159 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
160 unsigned EltSize =
161 N->getValueType(0).getVectorElementType().getSizeInBits();
162 SplatVal = OptAPInt->trunc(EltSize);
163 return true;
164 }
165 }
166
167 auto *BV = dyn_cast<BuildVectorSDNode>(N);
168 if (!BV)
169 return false;
170
171 APInt SplatUndef;
172 unsigned SplatBitSize;
173 bool HasUndefs;
174 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
175 // Endianness does not matter here. We are checking for a splat given the
176 // element size of the vector, and if we find such a splat for little endian
177 // layout, then that should be valid also for big endian (as the full vector
178 // size is known to be a multiple of the element size).
179 const bool IsBigEndian = false;
180 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
181 EltSize, IsBigEndian) &&
182 EltSize == SplatBitSize;
183}
184
185// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
186// specializations of the more general isConstantSplatVector()?
187
188bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
189 // Look through a bit convert.
190 while (N->getOpcode() == ISD::BITCAST)
191 N = N->getOperand(0).getNode();
192
193 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
194 APInt SplatVal;
195 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
196 }
197
198 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
199
200 unsigned i = 0, e = N->getNumOperands();
201
202 // Skip over all of the undef values.
203 while (i != e && N->getOperand(i).isUndef())
204 ++i;
205
206 // Do not accept an all-undef vector.
207 if (i == e) return false;
208
209 // Do not accept build_vectors that aren't all constants or which have non-~0
210 // elements. We have to be a bit careful here, as the type of the constant
211 // may not be the same as the type of the vector elements due to type
212 // legalization (the elements are promoted to a legal type for the target and
213 // a vector of a type may be legal when the base element type is not).
214 // We only want to check enough bits to cover the vector elements, because
215 // we care if the resultant vector is all ones, not whether the individual
216 // constants are.
217 SDValue NotZero = N->getOperand(i);
218 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
219 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
220 if (OptAPInt->countr_one() < EltSize)
221 return false;
222 } else
223 return false;
224
225 // Okay, we have at least one ~0 value, check to see if the rest match or are
226 // undefs. Even with the above element type twiddling, this should be OK, as
227 // the same type legalization should have applied to all the elements.
228 for (++i; i != e; ++i)
229 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
230 return false;
231 return true;
232}
233
234bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
235 // Look through a bit convert.
236 while (N->getOpcode() == ISD::BITCAST)
237 N = N->getOperand(0).getNode();
238
239 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
240 APInt SplatVal;
241 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
242 }
243
244 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
245
246 bool IsAllUndef = true;
247 for (const SDValue &Op : N->op_values()) {
248 if (Op.isUndef())
249 continue;
250 IsAllUndef = false;
251 // Do not accept build_vectors that aren't all constants or which have non-0
252 // elements. We have to be a bit careful here, as the type of the constant
253 // may not be the same as the type of the vector elements due to type
254 // legalization (the elements are promoted to a legal type for the target
255 // and a vector of a type may be legal when the base element type is not).
256 // We only want to check enough bits to cover the vector elements, because
257 // we care if the resultant vector is all zeros, not whether the individual
258 // constants are.
259 if (auto OptAPInt = Op->bitcastToAPInt()) {
260 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
261 if (OptAPInt->countr_zero() < EltSize)
262 return false;
263 } else
264 return false;
265 }
266
267 // Do not accept an all-undef vector.
268 if (IsAllUndef)
269 return false;
270 return true;
271}
272
274 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
275}
276
278 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
279}
280
282 if (N->getOpcode() != ISD::BUILD_VECTOR)
283 return false;
284
285 for (const SDValue &Op : N->op_values()) {
286 if (Op.isUndef())
287 continue;
289 return false;
290 }
291 return true;
292}
293
295 if (N->getOpcode() != ISD::BUILD_VECTOR)
296 return false;
297
298 for (const SDValue &Op : N->op_values()) {
299 if (Op.isUndef())
300 continue;
302 return false;
303 }
304 return true;
305}
306
307bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
308 bool Signed) {
309 assert(N->getValueType(0).isVector() && "Expected a vector!");
310
311 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
312 if (EltSize <= NewEltSize)
313 return false;
314
315 if (N->getOpcode() == ISD::ZERO_EXTEND) {
316 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
317 NewEltSize) &&
318 !Signed;
319 }
320 if (N->getOpcode() == ISD::SIGN_EXTEND) {
321 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
322 NewEltSize) &&
323 Signed;
324 }
325 if (N->getOpcode() != ISD::BUILD_VECTOR)
326 return false;
327
328 for (const SDValue &Op : N->op_values()) {
329 if (Op.isUndef())
330 continue;
332 return false;
333
334 APInt C = Op->getAsAPIntVal().trunc(EltSize);
335 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
336 return false;
337 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
338 return false;
339 }
340
341 return true;
342}
343
345 // Return false if the node has no operands.
346 // This is "logically inconsistent" with the definition of "all" but
347 // is probably the desired behavior.
348 if (N->getNumOperands() == 0)
349 return false;
350 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
351}
352
354 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
355}
356
357template <typename ConstNodeType>
359 std::function<bool(ConstNodeType *)> Match,
360 bool AllowUndefs, bool AllowTruncation) {
361 // FIXME: Add support for scalar UNDEF cases?
362 if (auto *C = dyn_cast<ConstNodeType>(Op))
363 return Match(C);
364
365 // FIXME: Add support for vector UNDEF cases?
366 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
367 ISD::SPLAT_VECTOR != Op.getOpcode())
368 return false;
369
370 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
371 return true;
372
373 EVT SVT = Op.getValueType().getScalarType();
374 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
375 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
376 continue;
377
378 if (AllowUndefs && Op.getOperand(i).isUndef()) {
379 if (!Match(nullptr))
380 return false;
381 continue;
382 }
383
384 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
385 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
386 !Match(Cst))
387 return false;
388 }
389 return true;
390}
391// Build used template types.
393 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
395 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
396 bool);
397
399 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
400 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
401 bool AllowUndefs, bool AllowTypeMismatch) {
402 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
403 return false;
404
405 // TODO: Add support for scalar UNDEF cases?
406 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
407 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
408 return Match(LHSCst, RHSCst);
409
410 // TODO: Add support for vector UNDEF cases?
411 if (LHS.getOpcode() != RHS.getOpcode() ||
412 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
413 LHS.getOpcode() != ISD::SPLAT_VECTOR))
414 return false;
415
416 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
417 return true;
418
419 EVT SVT = LHS.getValueType().getScalarType();
420 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
421 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
422 continue;
423 SDValue LHSOp = LHS.getOperand(i);
424 SDValue RHSOp = RHS.getOperand(i);
425 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
426 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
427 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
428 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
429 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
430 return false;
431 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
432 LHSOp.getValueType() != RHSOp.getValueType()))
433 return false;
434 if (!Match(LHSCst, RHSCst))
435 return false;
436 }
437 return true;
438}
439
441 switch (MinMaxOpc) {
442 default:
443 llvm_unreachable("unrecognized opcode");
444 case ISD::UMIN:
445 return ISD::UMAX;
446 case ISD::UMAX:
447 return ISD::UMIN;
448 case ISD::SMIN:
449 return ISD::SMAX;
450 case ISD::SMAX:
451 return ISD::SMIN;
452 }
453}
454
456 switch (MinMaxOpc) {
457 default:
458 llvm_unreachable("unrecognized min/max opcode");
459 case ISD::SMIN:
460 return ISD::UMIN;
461 case ISD::SMAX:
462 return ISD::UMAX;
463 case ISD::UMIN:
464 return ISD::SMIN;
465 case ISD::UMAX:
466 return ISD::SMAX;
467 }
468}
469
471 switch (VecReduceOpcode) {
472 default:
473 llvm_unreachable("Expected VECREDUCE opcode");
476 case ISD::VP_REDUCE_FADD:
477 case ISD::VP_REDUCE_SEQ_FADD:
478 return ISD::FADD;
481 case ISD::VP_REDUCE_FMUL:
482 case ISD::VP_REDUCE_SEQ_FMUL:
483 return ISD::FMUL;
485 case ISD::VP_REDUCE_ADD:
486 return ISD::ADD;
488 case ISD::VP_REDUCE_MUL:
489 return ISD::MUL;
491 case ISD::VP_REDUCE_AND:
492 return ISD::AND;
494 case ISD::VP_REDUCE_OR:
495 return ISD::OR;
497 case ISD::VP_REDUCE_XOR:
498 return ISD::XOR;
500 case ISD::VP_REDUCE_SMAX:
501 return ISD::SMAX;
503 case ISD::VP_REDUCE_SMIN:
504 return ISD::SMIN;
506 case ISD::VP_REDUCE_UMAX:
507 return ISD::UMAX;
509 case ISD::VP_REDUCE_UMIN:
510 return ISD::UMIN;
512 case ISD::VP_REDUCE_FMAX:
513 return ISD::FMAXNUM;
515 case ISD::VP_REDUCE_FMIN:
516 return ISD::FMINNUM;
518 case ISD::VP_REDUCE_FMAXIMUM:
519 return ISD::FMAXIMUM;
521 case ISD::VP_REDUCE_FMINIMUM:
522 return ISD::FMINIMUM;
524 return ISD::FMAXIMUMNUM;
526 return ISD::FMINIMUMNUM;
527 }
528}
529
531 switch (MaskedOpc) {
532 case ISD::MASKED_UDIV:
533 return ISD::UDIV;
534 case ISD::MASKED_SDIV:
535 return ISD::SDIV;
536 case ISD::MASKED_UREM:
537 return ISD::UREM;
538 case ISD::MASKED_SREM:
539 return ISD::SREM;
540 default:
541 llvm_unreachable("Expected masked binop opcode");
542 }
543}
544
545bool ISD::isVPOpcode(unsigned Opcode) {
546 switch (Opcode) {
547 default:
548 return false;
549#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
550 case ISD::VPSD: \
551 return true;
552#include "llvm/IR/VPIntrinsics.def"
553 }
554}
555
556bool ISD::isVPBinaryOp(unsigned Opcode) {
557 switch (Opcode) {
558 default:
559 break;
560#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
561#define VP_PROPERTY_BINARYOP return true;
562#define END_REGISTER_VP_SDNODE(VPSD) break;
563#include "llvm/IR/VPIntrinsics.def"
564 }
565 return false;
566}
567
568bool ISD::isVPReduction(unsigned Opcode) {
569 switch (Opcode) {
570 default:
571 return false;
572 case ISD::VP_REDUCE_ADD:
573 case ISD::VP_REDUCE_MUL:
574 case ISD::VP_REDUCE_AND:
575 case ISD::VP_REDUCE_OR:
576 case ISD::VP_REDUCE_XOR:
577 case ISD::VP_REDUCE_SMAX:
578 case ISD::VP_REDUCE_SMIN:
579 case ISD::VP_REDUCE_UMAX:
580 case ISD::VP_REDUCE_UMIN:
581 case ISD::VP_REDUCE_FMAX:
582 case ISD::VP_REDUCE_FMIN:
583 case ISD::VP_REDUCE_FMAXIMUM:
584 case ISD::VP_REDUCE_FMINIMUM:
585 case ISD::VP_REDUCE_FADD:
586 case ISD::VP_REDUCE_FMUL:
587 case ISD::VP_REDUCE_SEQ_FADD:
588 case ISD::VP_REDUCE_SEQ_FMUL:
589 return true;
590 }
591}
592
593/// The operand position of the vector mask.
594std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
595 switch (Opcode) {
596 default:
597 return std::nullopt;
598#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
599 case ISD::VPSD: \
600 return MASKPOS;
601#include "llvm/IR/VPIntrinsics.def"
602 }
603}
604
605/// The operand position of the explicit vector length parameter.
606std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
607 switch (Opcode) {
608 default:
609 return std::nullopt;
610#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
611 case ISD::VPSD: \
612 return EVLPOS;
613#include "llvm/IR/VPIntrinsics.def"
614 }
615}
616
617std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
618 bool hasFPExcept) {
619 // FIXME: Return strict opcodes in case of fp exceptions.
620 switch (VPOpcode) {
621 default:
622 return std::nullopt;
623#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
624#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
625#define END_REGISTER_VP_SDNODE(VPOPC) break;
626#include "llvm/IR/VPIntrinsics.def"
627 }
628 return std::nullopt;
629}
630
631std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
632 switch (Opcode) {
633 default:
634 return std::nullopt;
635#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
636#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
637#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
638#include "llvm/IR/VPIntrinsics.def"
639 }
640}
641
643 switch (ExtType) {
644 case ISD::EXTLOAD:
645 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
646 case ISD::SEXTLOAD:
647 return ISD::SIGN_EXTEND;
648 case ISD::ZEXTLOAD:
649 return ISD::ZERO_EXTEND;
650 default:
651 break;
652 }
653
654 llvm_unreachable("Invalid LoadExtType");
655}
656
658 // To perform this operation, we just need to swap the L and G bits of the
659 // operation.
660 unsigned OldL = (Operation >> 2) & 1;
661 unsigned OldG = (Operation >> 1) & 1;
662 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
663 (OldL << 1) | // New G bit
664 (OldG << 2)); // New L bit.
665}
666
668 unsigned Operation = Op;
669 if (isIntegerLike)
670 Operation ^= 7; // Flip L, G, E bits, but not U.
671 else
672 Operation ^= 15; // Flip all of the condition bits.
673
675 Operation &= ~8; // Don't let N and U bits get set.
676
677 return ISD::CondCode(Operation);
678}
679
683
685 bool isIntegerLike) {
686 return getSetCCInverseImpl(Op, isIntegerLike);
687}
688
689/// For an integer comparison, return 1 if the comparison is a signed operation
690/// and 2 if the result is an unsigned comparison. Return zero if the operation
691/// does not depend on the sign of the input (setne and seteq).
692static int isSignedOp(ISD::CondCode Opcode) {
693 switch (Opcode) {
694 default: llvm_unreachable("Illegal integer setcc operation!");
695 case ISD::SETEQ:
696 case ISD::SETNE: return 0;
697 case ISD::SETLT:
698 case ISD::SETLE:
699 case ISD::SETGT:
700 case ISD::SETGE: return 1;
701 case ISD::SETULT:
702 case ISD::SETULE:
703 case ISD::SETUGT:
704 case ISD::SETUGE: return 2;
705 }
706}
707
709 EVT Type) {
710 bool IsInteger = Type.isInteger();
711 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
712 // Cannot fold a signed integer setcc with an unsigned integer setcc.
713 return ISD::SETCC_INVALID;
714
715 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
716
717 // If the N and U bits get set, then the resultant comparison DOES suddenly
718 // care about orderedness, and it is true when ordered.
719 if (Op > ISD::SETTRUE2)
720 Op &= ~16; // Clear the U bit if the N bit is set.
721
722 // Canonicalize illegal integer setcc's.
723 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
724 Op = ISD::SETNE;
725
726 return ISD::CondCode(Op);
727}
728
730 EVT Type) {
731 bool IsInteger = Type.isInteger();
732 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
733 // Cannot fold a signed setcc with an unsigned setcc.
734 return ISD::SETCC_INVALID;
735
736 // Combine all of the condition bits.
737 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
738
739 // Canonicalize illegal integer setcc's.
740 if (IsInteger) {
741 switch (Result) {
742 default: break;
743 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
744 case ISD::SETOEQ: // SETEQ & SETU[LG]E
745 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
746 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
747 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
748 }
749 }
750
751 return Result;
752}
753
754//===----------------------------------------------------------------------===//
755// SDNode Key Support
756//===----------------------------------------------------------------------===//
757
758/// If this is an SDNode with special info, add this info to the NodeID data.
759/// MorphNodeTo passes the opcode \p N is becoming, so \p Opc may differ from
760/// N->getOpcode() and a case may only cast to a class \p N already is.
761static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N,
762 unsigned Opc) {
763 // Machine nodes are uniqued by opcode, value types and operands alone, as in
764 // getMachineNode; MorphNodeTo's clearMemRefs overwrites the fields below.
766 return;
767
768 switch (Opc) {
771 case ISD::MCSymbol:
772 llvm_unreachable("Should only be used on nodes with operands");
773 default: break; // Normal nodes don't need extra info.
775 case ISD::Constant: {
777 ID.AddPointer(C->getConstantIntValue());
778 ID.AddBoolean(C->isOpaque());
779 break;
780 }
782 case ISD::ConstantFP:
783 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
784 break;
790 ID.AddPointer(GA->getGlobal());
791 ID.AddInteger(GA->getOffset());
792 ID.AddInteger(GA->getTargetFlags());
793 break;
794 }
795 case ISD::BasicBlock:
796 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
797 break;
798 case ISD::EH_LABEL:
800 ID.AddPointer(cast<LabelSDNode>(N)->getLabel());
801 break;
803 ID.AddPointer(cast<DeactivationSymbolSDNode>(N)->getGlobal());
804 break;
805 case ISD::Register:
806 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
807 break;
809 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
810 break;
811 case ISD::SRCVALUE:
812 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
813 break;
814 case ISD::FrameIndex:
816 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
817 break;
819 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
820 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
821 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
822 break;
823 case ISD::JumpTable:
825 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
826 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
827 break;
831 ID.AddInteger(CP->getAlign().value());
832 ID.AddInteger(CP->getOffset());
835 else
836 ID.AddPointer(CP->getConstVal());
837 ID.AddInteger(CP->getTargetFlags());
838 break;
839 }
840 case ISD::TargetIndex: {
842 ID.AddInteger(TI->getIndex());
843 ID.AddInteger(TI->getOffset());
844 ID.AddInteger(TI->getTargetFlags());
845 break;
846 }
847 case ISD::LOAD: {
848 const LoadSDNode *LD = cast<LoadSDNode>(N);
849 ID.AddInteger(LD->getMemoryVT().getRawBits());
850 ID.AddInteger(LD->getRawSubclassData());
851 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
852 ID.AddInteger(LD->getMemOperand()->getFlags());
853 break;
854 }
855 case ISD::STORE: {
856 const StoreSDNode *ST = cast<StoreSDNode>(N);
857 ID.AddInteger(ST->getMemoryVT().getRawBits());
858 ID.AddInteger(ST->getRawSubclassData());
859 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
860 ID.AddInteger(ST->getMemOperand()->getFlags());
861 break;
862 }
863 case ISD::VP_LOAD: {
864 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
865 ID.AddInteger(ELD->getMemoryVT().getRawBits());
866 ID.AddInteger(ELD->getRawSubclassData());
867 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
868 ID.AddInteger(ELD->getMemOperand()->getFlags());
869 break;
870 }
871 case ISD::VP_LOAD_FF: {
872 const auto *LD = cast<VPLoadFFSDNode>(N);
873 ID.AddInteger(LD->getMemoryVT().getRawBits());
874 ID.AddInteger(LD->getRawSubclassData());
875 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
876 ID.AddInteger(LD->getMemOperand()->getFlags());
877 break;
878 }
879 case ISD::VP_STORE: {
880 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
881 ID.AddInteger(EST->getMemoryVT().getRawBits());
882 ID.AddInteger(EST->getRawSubclassData());
883 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
884 ID.AddInteger(EST->getMemOperand()->getFlags());
885 break;
886 }
887 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
889 ID.AddInteger(SLD->getMemoryVT().getRawBits());
890 ID.AddInteger(SLD->getRawSubclassData());
891 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
892 break;
893 }
894 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
896 ID.AddInteger(SST->getMemoryVT().getRawBits());
897 ID.AddInteger(SST->getRawSubclassData());
898 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
899 break;
900 }
901 case ISD::VP_GATHER: {
903 ID.AddInteger(EG->getMemoryVT().getRawBits());
904 ID.AddInteger(EG->getRawSubclassData());
905 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
906 ID.AddInteger(EG->getMemOperand()->getFlags());
907 break;
908 }
909 case ISD::VP_SCATTER: {
911 ID.AddInteger(ES->getMemoryVT().getRawBits());
912 ID.AddInteger(ES->getRawSubclassData());
913 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
914 ID.AddInteger(ES->getMemOperand()->getFlags());
915 break;
916 }
917 case ISD::MLOAD: {
919 ID.AddInteger(MLD->getMemoryVT().getRawBits());
920 ID.AddInteger(MLD->getRawSubclassData());
921 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
922 ID.AddInteger(MLD->getMemOperand()->getFlags());
923 break;
924 }
925 case ISD::MSTORE: {
927 ID.AddInteger(MST->getMemoryVT().getRawBits());
928 ID.AddInteger(MST->getRawSubclassData());
929 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
930 ID.AddInteger(MST->getMemOperand()->getFlags());
931 break;
932 }
933 case ISD::MGATHER: {
935 ID.AddInteger(MG->getMemoryVT().getRawBits());
936 ID.AddInteger(MG->getRawSubclassData());
937 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
938 ID.AddInteger(MG->getMemOperand()->getFlags());
939 break;
940 }
941 case ISD::MSCATTER:
945 const MemSDNode *M = cast<MemSDNode>(N);
946 ID.AddInteger(M->getMemoryVT().getRawBits());
947 ID.AddInteger(M->getRawSubclassData());
948 ID.AddInteger(M->getPointerInfo().getAddrSpace());
949 ID.AddInteger(M->getMemOperand()->getFlags());
950 break;
951 }
952 case ISD::VECTOR_SHUFFLE: {
953 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
954 for (int M : Mask)
955 ID.AddInteger(M);
956 break;
957 }
958 case ISD::ADDRSPACECAST: {
960 ID.AddInteger(ASC->getSrcAddressSpace());
961 ID.AddInteger(ASC->getDestAddressSpace());
962 break;
963 }
965 case ISD::BlockAddress: {
967 ID.AddPointer(BA->getBlockAddress());
968 ID.AddInteger(BA->getOffset());
969 ID.AddInteger(BA->getTargetFlags());
970 break;
971 }
972 case ISD::AssertAlign:
973 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
974 break;
975 case ISD::PREFETCH:
978 // Handled by MemIntrinsicSDNode check after the switch.
979 break;
981 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
982 break;
983 } // end switch (Opc)
984
985 if (auto *AT = dyn_cast<AtomicSDNode>(N)) {
986 ID.AddInteger(AT->getMemoryVT().getRawBits());
987 ID.AddInteger(AT->getRawSubclassData());
988 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
989 ID.AddInteger(AT->getMemOperand()->getFlags());
990 }
991
992 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
993 // to check.
994 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
995 ID.AddInteger(MN->getRawSubclassData());
996 ID.AddInteger(MN->getMemoryVT().getRawBits());
997 for (const MachineMemOperand *MMO : MN->memoperands()) {
998 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
999 ID.AddInteger(MMO->getFlags());
1000 }
1001 }
1002}
1003
1005 : Opcode(N.getOpcode()), VTs(N.getVTList().VTs),
1006 OpStorage(N.op_begin(), N.op_end()) {
1007 Ops = OpStorage;
1008 AddNodeIDCustom(Tail, &N, N.getOpcode());
1009}
1010
1011#ifndef NDEBUG
1012/// Serialize a node the way SDNodes were uniqued before SDNodeKey, to
1013/// cross-check the typed comparison against. Deliberately reads the node
1014/// rather than going through SDNodeKey, so the key constructor is checked too
1015/// and not used as its own oracle.
1016static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1017 ID.AddInteger(N->getOpcode());
1018 ID.AddPointer(N->getVTList().VTs);
1019 for (const SDUse &Op : N->ops()) {
1020 ID.AddPointer(Op.getNode());
1021 ID.AddInteger(Op.getResNo());
1022 }
1023 AddNodeIDCustom(ID, N, N->getOpcode());
1024}
1025
1027 ID.AddInteger(Key.Opcode);
1028 ID.AddPointer(Key.VTs);
1029 for (const SDValue &Op : Key.Ops) {
1030 ID.AddPointer(Op.getNode());
1031 ID.AddInteger(Op.getResNo());
1032 }
1033 ID.AddNodeID(Key.Tail);
1034}
1035#endif
1036
1037static bool keyMatches(const SDNodeKey &Key, const SDNode &N) {
1038 if (N.getOpcode() != Key.Opcode || N.getVTList().VTs != Key.VTs)
1039 return false;
1040 if (!llvm::equal(N.ops(), Key.Ops))
1041 return false;
1042 // Build only what AddNodeIDCustom would have added, which is nothing for
1043 // most opcodes, rather than the whole profile.
1044 FoldingSetNodeID Tail;
1045 AddNodeIDCustom(Tail, &N, N.getOpcode());
1046 return Tail == Key.Tail;
1047}
1048
1050 bool Result = keyMatches(Key, N);
1051
1052#ifndef NDEBUG
1053 FoldingSetNodeID NodeProfile, KeyProfile;
1054 AddNodeIDNode(NodeProfile, &N);
1055 AddNodeIDNode(KeyProfile, Key);
1056 assert((NodeProfile == KeyProfile) == Result &&
1057 "SDNodeKey equality disagrees with profile");
1058#endif
1059 return Result;
1060}
1061
1062//===----------------------------------------------------------------------===//
1063// SelectionDAG Class
1064//===----------------------------------------------------------------------===//
1065
1066/// doNotCSE - Return true if CSE should not be performed for this node.
1067static bool doNotCSE(SDNode *N) {
1068 if (N->getValueType(0) == MVT::Glue)
1069 return true; // Never CSE anything that produces a glue result.
1070
1071 switch (N->getOpcode()) {
1072 default: break;
1073 case ISD::HANDLENODE:
1074 case ISD::EH_LABEL:
1075 return true; // Never CSE these nodes.
1076 }
1077
1078 // Check that remaining values produced are not flags.
1079 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1080 if (N->getValueType(i) == MVT::Glue)
1081 return true; // Never CSE anything that produces a glue result.
1082
1083 return false;
1084}
1085
1086/// Construct a DemandedElts mask which demands all elements of \p V.
1087/// If \p V is not a fixed-length vector, then this will return a single bit.
1089 EVT VT = V.getValueType();
1090 // Since the number of lanes in a scalable vector is unknown at compile time,
1091 // we track one bit which is implicitly broadcast to all lanes. This means
1092 // that all lanes in a scalable vector are considered demanded.
1094 : APInt(1, 1);
1095}
1096
1097/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1098/// SelectionDAG.
1100 // Create a dummy node (which is not added to allnodes), that adds a reference
1101 // to the root node, preventing it from being deleted.
1102 HandleSDNode Dummy(getRoot());
1103
1104 SmallVector<SDNode*, 128> DeadNodes;
1105
1106 // Add all obviously-dead nodes to the DeadNodes worklist.
1107 for (SDNode &Node : allnodes())
1108 if (Node.use_empty())
1109 DeadNodes.push_back(&Node);
1110
1111 RemoveDeadNodes(DeadNodes);
1112
1113 // If the root changed (e.g. it was a dead load, update the root).
1114 setRoot(Dummy.getValue());
1115}
1116
1117/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1118/// given list, and any nodes that become unreachable as a result.
1120
1121 // Process the worklist, deleting the nodes and adding their uses to the
1122 // worklist.
1123 while (!DeadNodes.empty()) {
1124 SDNode *N = DeadNodes.pop_back_val();
1125 // Skip to next node if we've already managed to delete the node. This could
1126 // happen if replacing a node causes a node previously added to the node to
1127 // be deleted.
1128 if (N->getOpcode() == ISD::DELETED_NODE)
1129 continue;
1130
1131 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1132 DUL->NodeDeleted(N, nullptr);
1133
1134 // Take the node out of the appropriate CSE map.
1135 RemoveNodeFromCSEMaps(N);
1136
1137 // Next, brutally remove the operand list. This is safe to do, as there are
1138 // no cycles in the graph.
1139 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1140 SDUse &Use = *I++;
1141 SDNode *Operand = Use.getNode();
1142 Use.set(SDValue());
1143
1144 // Now that we removed this operand, see if there are no uses of it left.
1145 if (Operand->use_empty())
1146 DeadNodes.push_back(Operand);
1147 }
1148
1149 DeallocateNode(N);
1150 }
1151}
1152
1154 SmallVector<SDNode*, 16> DeadNodes(1, N);
1155
1156 // Create a dummy node that adds a reference to the root node, preventing
1157 // it from being deleted. (This matters if the root is an operand of the
1158 // dead node.)
1159 HandleSDNode Dummy(getRoot());
1160
1161 RemoveDeadNodes(DeadNodes);
1162}
1163
1165 // First take this out of the appropriate CSE map.
1166 RemoveNodeFromCSEMaps(N);
1167
1168 // Finally, remove uses due to operands of this node, remove from the
1169 // AllNodes list, and delete the node.
1170 DeleteNodeNotInCSEMaps(N);
1171}
1172
1173void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1174 assert(N->getIterator() != AllNodes.begin() &&
1175 "Cannot delete the entry node!");
1176 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1177
1178 // Drop all of the operands and decrement used node's use counts.
1179 N->DropOperands();
1180
1181 DeallocateNode(N);
1182}
1183
1184void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1185 assert(!(V->isVariadic() && isParameter));
1186 if (isParameter)
1187 ByvalParmDbgValues.push_back(V);
1188 else
1189 DbgValues.push_back(V);
1190 for (const SDNode *Node : V->getSDNodes())
1191 if (Node)
1192 DbgValMap[Node].push_back(V);
1193}
1194
1196 DbgValMapType::iterator I = DbgValMap.find(Node);
1197 if (I == DbgValMap.end())
1198 return;
1199 for (auto &Val: I->second)
1200 Val->setIsInvalidated();
1201 DbgValMap.erase(I);
1202}
1203
1204void SelectionDAG::DeallocateNode(SDNode *N) {
1205 // If we have operands, deallocate them.
1207
1208 NodeAllocator.Deallocate(AllNodes.remove(N));
1209
1210 // Set the opcode to DELETED_NODE to help catch bugs when node
1211 // memory is reallocated.
1212 // FIXME: There are places in SDag that have grown a dependency on the opcode
1213 // value in the released node.
1214 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1215 N->NodeType = ISD::DELETED_NODE;
1216
1217 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1218 // them and forget about that node.
1219 DbgInfo->erase(N);
1220
1221 // Invalidate extra info.
1222 SDEI.erase(N);
1223}
1224
1225#ifndef NDEBUG
1226/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1227void SelectionDAG::verifyNode(SDNode *N) const {
1228 switch (N->getOpcode()) {
1229 default:
1230 if (N->isTargetOpcode())
1232 break;
1233 case ISD::BUILD_PAIR: {
1234 EVT VT = N->getValueType(0);
1235 assert(N->getNumValues() == 1 && "Too many results!");
1236 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1237 "Wrong return type!");
1238 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1239 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1240 "Mismatched operand types!");
1241 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1242 "Wrong operand type!");
1243 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1244 "Wrong return type size");
1245 break;
1246 }
1247 case ISD::BUILD_VECTOR: {
1248 assert(N->getNumValues() == 1 && "Too many results!");
1249 assert(N->getValueType(0).isVector() && "Wrong return type!");
1250 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1251 "Wrong number of operands!");
1252 EVT EltVT = N->getValueType(0).getVectorElementType();
1253 for (const SDUse &Op : N->ops()) {
1254 assert((Op.getValueType() == EltVT ||
1255 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1256 EltVT.bitsLE(Op.getValueType()))) &&
1257 "Wrong operand type!");
1258 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1259 "Operands must all have the same type");
1260 }
1261 break;
1262 }
1263 case ISD::SADDO:
1264 case ISD::UADDO:
1265 case ISD::SSUBO:
1266 case ISD::USUBO:
1267 assert(N->getNumValues() == 2 && "Wrong number of results!");
1268 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1269 "Invalid add/sub overflow op!");
1270 assert(N->getVTList().VTs[0].isInteger() &&
1271 N->getVTList().VTs[1].isInteger() &&
1272 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1273 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1274 "Binary operator types must match!");
1275 break;
1276 }
1277}
1278#endif // NDEBUG
1279
1280/// Insert a newly allocated node into the DAG.
1281///
1282/// Handles insertion into the all nodes list and CSE map, as well as
1283/// verification and other common operations when a new node is allocated.
1284void SelectionDAG::InsertNode(SDNode *N) {
1285 AllNodes.push_back(N);
1286#ifndef NDEBUG
1287 N->PersistentId = NextPersistentId++;
1288 verifyNode(N);
1289#endif
1290 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1291 DUL->NodeInserted(N);
1292}
1293
1294/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1295/// correspond to it. This is useful when we're about to delete or repurpose
1296/// the node. We don't want future request for structurally identical nodes
1297/// to return N anymore.
1298bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1299 bool Erased = false;
1300 switch (N->getOpcode()) {
1301 case ISD::HANDLENODE: return false; // noop.
1302 case ISD::CONDCODE:
1303 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1304 "Cond code doesn't exist!");
1305 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1306 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1307 break;
1309 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1310 break;
1312 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1313 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1314 ESN->getSymbol(), ESN->getTargetFlags()));
1315 break;
1316 }
1317 case ISD::MCSymbol: {
1318 auto *MCSN = cast<MCSymbolSDNode>(N);
1319 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1320 break;
1321 }
1322 case ISD::VALUETYPE: {
1323 EVT VT = cast<VTSDNode>(N)->getVT();
1324 if (VT.isExtended()) {
1325 Erased = ExtendedValueTypeNodes.erase(VT);
1326 } else {
1327 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1328 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1329 }
1330 break;
1331 }
1332 default:
1333 // Remove it from the CSE Map.
1334 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1335 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1336 Erased = CSEMap.erase(N);
1337 break;
1338 }
1339#ifndef NDEBUG
1340 // Verify that the node was actually in one of the CSE maps, unless it has a
1341 // glue result (which cannot be CSE'd) or is one of the special cases that are
1342 // not subject to CSE.
1343 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1344 !N->isMachineOpcode() && !doNotCSE(N)) {
1345 N->dump(this);
1346 dbgs() << "\n";
1347 llvm_unreachable("Node is not in map!");
1348 }
1349#endif
1350 return Erased;
1351}
1352
1353/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1354/// maps and modified in place. Add it back to the CSE maps, unless an identical
1355/// node already exists, in which case transfer all its users to the existing
1356/// node. This transfer can potentially trigger recursive merging.
1357void
1358SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1359 // For node types that aren't CSE'd, just act as if no identical node
1360 // already exists.
1361 if (!doNotCSE(N)) {
1362 SDNode *Existing = CSEMap.getOrInsert(N);
1363 if (Existing != N) {
1364 // If there was already an existing matching node, use ReplaceAllUsesWith
1365 // to replace the dead one with the existing one. This can cause
1366 // recursive merging of other unrelated nodes down the line.
1367 Existing->intersectFlagsWith(N->getFlags());
1368 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1370 cast<MemSDNode>(N)->memoperands();
1371 // Range and cache hint metadata are not part of the DAG CSE key because
1372 // we prefer to CSE even when metadata does not match. Merge potentially
1373 // differing metadata conservatively.
1374 MemNode->refineMMOMetadata(NewMMOs);
1375 }
1376 ReplaceAllUsesWith(N, Existing);
1377
1378 // N is now dead. Inform the listeners and delete it.
1379 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1380 DUL->NodeDeleted(N, Existing);
1381 DeleteNodeNotInCSEMaps(N);
1382 return;
1383 }
1384 }
1385
1386 // If the node doesn't already exist, we updated it. Inform listeners.
1387 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1388 DUL->NodeUpdated(N);
1389}
1390
1391/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1392/// were replaced with those specified. If this node is never memoized,
1393/// return null, otherwise return a pointer to the slot it would take. If a
1394/// node already exists with these operands, the slot will be non-null.
1395SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1396 FoldingSetInsertToken &InsertToken) {
1397 if (doNotCSE(N))
1398 return nullptr;
1399
1400 SDValue Ops[] = { Op };
1401 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1402 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1403 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1404 if (Node)
1405 Node->intersectFlagsWith(N->getFlags());
1406 return Node;
1407}
1408
1409/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1410/// were replaced with those specified. If this node is never memoized,
1411/// return null, otherwise return a pointer to the slot it would take. If a
1412/// node already exists with these operands, the slot will be non-null.
1413SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1414 FoldingSetInsertToken &InsertToken) {
1415 if (doNotCSE(N))
1416 return nullptr;
1417
1418 SDValue Ops[] = { Op1, Op2 };
1419 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1420 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1421 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1422 if (Node)
1423 Node->intersectFlagsWith(N->getFlags());
1424 return Node;
1425}
1426
1427/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1428/// were replaced with those specified. If this node is never memoized,
1429/// return null, otherwise return a pointer to the slot it would take. If a
1430/// node already exists with these operands, the slot will be non-null.
1431SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1432 FoldingSetInsertToken &InsertToken) {
1433 if (doNotCSE(N))
1434 return nullptr;
1435
1436 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1437 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1438 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1439 if (Node)
1440 Node->intersectFlagsWith(N->getFlags());
1441 return Node;
1442}
1443
1445 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1446 : VT.getTypeForEVT(*getContext());
1447
1448 return getDataLayout().getABITypeAlign(Ty);
1449}
1450
1451// EntryNode could meaningfully have debug info if we can find it...
1453 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1454 getVTList(MVT::Other, MVT::Glue)),
1455 Root(getEntryNode()) {
1456 InsertNode(&EntryNode);
1457 DbgInfo = new SDDbgInfo();
1458}
1459
1461 const TargetLibraryInfo *LibraryInfo,
1462 const LibcallLoweringInfo *LibcallsInfo,
1463 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1464 BlockFrequencyInfo *BFIin,
1465 FunctionVarLocs const *VarLocs) {
1466 MF = &NewMF;
1469 LibInfo = LibraryInfo;
1470 Libcalls = LibcallsInfo;
1471 Context = &MF->getFunction().getContext();
1472 UA = NewUA;
1473 PSI = PSIin;
1474 BFI = BFIin;
1475 FnVarLocs = VarLocs;
1476}
1477
1479 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1480 allnodes_clear();
1481 OperandRecycler.clear(OperandAllocator);
1482 delete DbgInfo;
1483}
1484
1486 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1487}
1488
1490 return FLI->MBB->getBasicBlock();
1491}
1492
1493void SelectionDAG::allnodes_clear() {
1494 assert(&*AllNodes.begin() == &EntryNode);
1495 AllNodes.remove(AllNodes.begin());
1496 while (!AllNodes.empty())
1497 DeallocateNode(&AllNodes.front());
1498#ifndef NDEBUG
1499 NextPersistentId = 0;
1500#endif
1501}
1502
1503SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key,
1504 FoldingSetInsertToken &InsertToken) {
1505 SDNode *N = CSEMap.lookup(Key, InsertToken);
1506 if (N) {
1507 switch (N->getOpcode()) {
1508 default: break;
1509 case ISD::Constant:
1510 case ISD::ConstantFP:
1511 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1512 "debug location. Use another overload.");
1513 }
1514 }
1515 return N;
1516}
1517
1518SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key, const SDLoc &DL,
1519 FoldingSetInsertToken &InsertToken) {
1520 SDNode *N = CSEMap.lookup(Key, InsertToken);
1521 if (N) {
1522 switch (N->getOpcode()) {
1523 case ISD::Constant:
1524 case ISD::ConstantFP:
1525 // Erase debug location from the node if the node is used at several
1526 // different places. Do not propagate one location to all uses as it
1527 // will cause a worse single stepping debugging experience.
1528 if (N->getDebugLoc() != DL.getDebugLoc())
1529 N->setDebugLoc(DebugLoc());
1530 break;
1531 default:
1532 // When the node's point of use is located earlier in the instruction
1533 // sequence than its prior point of use, update its debug info to the
1534 // earlier location.
1535 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1536 N->setDebugLoc(DL.getDebugLoc());
1537 break;
1538 }
1539 }
1540 return N;
1541}
1542
1544 allnodes_clear();
1545 OperandRecycler.clear(OperandAllocator);
1546 OperandAllocator.Reset();
1547 CSEMap.clear();
1548
1549 ExtendedValueTypeNodes.clear();
1550 ExternalSymbols.clear();
1551 TargetExternalSymbols.clear();
1552 MCSymbols.clear();
1553 SDEI.clear();
1554 llvm::fill(CondCodeNodes, nullptr);
1555 llvm::fill(ValueTypeNodes, nullptr);
1556
1557 EntryNode.UseList = nullptr;
1558 InsertNode(&EntryNode);
1559 Root = getEntryNode();
1560 DbgInfo->clear();
1561}
1562
1564 return VT.bitsGT(Op.getValueType())
1565 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1566 : getNode(ISD::FP_ROUND, DL, VT, Op,
1567 getIntPtrConstant(0, DL, /*isTarget=*/true));
1568}
1569
1570std::pair<SDValue, SDValue>
1572 const SDLoc &DL, EVT VT) {
1573 assert(!VT.bitsEq(Op.getValueType()) &&
1574 "Strict no-op FP extend/round not allowed.");
1575 SDValue Res =
1576 VT.bitsGT(Op.getValueType())
1577 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1578 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1579 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1580
1581 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1582}
1583
1585 return VT.bitsGT(Op.getValueType()) ?
1586 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1587 getNode(ISD::TRUNCATE, DL, VT, Op);
1588}
1589
1591 return VT.bitsGT(Op.getValueType()) ?
1592 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1593 getNode(ISD::TRUNCATE, DL, VT, Op);
1594}
1595
1597 return VT.bitsGT(Op.getValueType()) ?
1598 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1599 getNode(ISD::TRUNCATE, DL, VT, Op);
1600}
1601
1603 EVT VT) {
1604 assert(!VT.isVector());
1605 auto Type = Op.getValueType();
1606 SDValue DestOp;
1607 if (Type == VT)
1608 return Op;
1609 auto Size = Op.getValueSizeInBits();
1610 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1611 if (DestOp.getValueType() == VT)
1612 return DestOp;
1613
1614 return getAnyExtOrTrunc(DestOp, DL, VT);
1615}
1616
1618 EVT OpVT) {
1619 if (VT.bitsLE(Op.getValueType()))
1620 return getNode(ISD::TRUNCATE, SL, VT, Op);
1621
1622 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1623 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1624}
1625
1627 EVT OpVT = Op.getValueType();
1628 assert(VT.isInteger() && OpVT.isInteger() &&
1629 "Cannot getZeroExtendInReg FP types");
1630 assert(VT.isVector() == OpVT.isVector() &&
1631 "getZeroExtendInReg type should be vector iff the operand "
1632 "type is vector!");
1633 assert((!VT.isVector() ||
1635 "Vector element counts must match in getZeroExtendInReg");
1636 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1637 if (OpVT == VT)
1638 return Op;
1639 // TODO: Use computeKnownBits instead of AssertZext.
1640 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1641 ->getVT()
1642 .getScalarType()
1643 .bitsLE(VT.getScalarType()))
1644 return Op;
1646 VT.getScalarSizeInBits());
1647 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1648}
1649
1651 // Only unsigned pointer semantics are supported right now. In the future this
1652 // might delegate to TLI to check pointer signedness.
1653 return getZExtOrTrunc(Op, DL, VT);
1654}
1655
1657 // Only unsigned pointer semantics are supported right now. In the future this
1658 // might delegate to TLI to check pointer signedness.
1659 return getZeroExtendInReg(Op, DL, VT);
1660}
1661
1663 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1664}
1665
1666/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1668 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1669}
1670
1672 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1673 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1674}
1675
1677 EVT OpVT) {
1678 if (!V)
1679 return getConstant(0, DL, VT);
1680
1681 switch (TLI->getBooleanContents(OpVT)) {
1684 return getConstant(1, DL, VT);
1686 return getAllOnesConstant(DL, VT);
1687 }
1688 llvm_unreachable("Unexpected boolean content enum!");
1689}
1690
1692 bool isT, bool isO) {
1693 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1694 DL, VT, isT, isO);
1695}
1696
1698 bool isT, bool isO) {
1699 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1700}
1701
1703 EVT VT, bool isT, bool isO) {
1704 assert(VT.isInteger() && "Cannot create FP integer constant!");
1705
1706 EVT EltVT = VT.getScalarType();
1707 const ConstantInt *Elt = &Val;
1708
1709 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1710 // to-be-splatted scalar ConstantInt.
1711 if (isa<VectorType>(Elt->getType()))
1712 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1713
1714 // In some cases the vector type is legal but the element type is illegal and
1715 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1716 // inserted value (the type does not need to match the vector element type).
1717 // Any extra bits introduced will be truncated away.
1718 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1720 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1721 APInt NewVal;
1722 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1723 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1724 else
1725 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1726 Elt = ConstantInt::get(*getContext(), NewVal);
1727 }
1728 // In other cases the element type is illegal and needs to be expanded, for
1729 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1730 // the value into n parts and use a vector type with n-times the elements.
1731 // Then bitcast to the type requested.
1732 // Legalizing constants too early makes the DAGCombiner's job harder so we
1733 // only legalize if the DAG tells us we must produce legal types.
1734 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1735 TLI->getTypeAction(*getContext(), EltVT) ==
1737 const APInt &NewVal = Elt->getValue();
1738 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1739 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1740
1741 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1742 if (VT.isScalableVector() ||
1743 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1744 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1745 "Can only handle an even split!");
1746 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1747
1748 SmallVector<SDValue, 2> ScalarParts;
1749 for (unsigned i = 0; i != Parts; ++i)
1750 ScalarParts.push_back(getConstant(
1751 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1752 ViaEltVT, isT, isO));
1753
1754 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1755 }
1756
1757 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1758 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1759
1760 // Check the temporary vector is the correct size. If this fails then
1761 // getTypeToTransformTo() probably returned a type whose size (in bits)
1762 // isn't a power-of-2 factor of the requested type size.
1763 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1764
1765 SmallVector<SDValue, 2> EltParts;
1766 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1767 EltParts.push_back(getConstant(
1768 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1769 ViaEltVT, isT, isO));
1770
1771 // EltParts is currently in little endian order. If we actually want
1772 // big-endian order then reverse it now.
1773 if (getDataLayout().isBigEndian())
1774 std::reverse(EltParts.begin(), EltParts.end());
1775
1776 // The elements must be reversed when the element order is different
1777 // to the endianness of the elements (because the BITCAST is itself a
1778 // vector shuffle in this situation). However, we do not need any code to
1779 // perform this reversal because getConstant() is producing a vector
1780 // splat.
1781 // This situation occurs in MIPS MSA.
1782
1784 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1785 llvm::append_range(Ops, EltParts);
1786
1787 SDValue V =
1788 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1789 return V;
1790 }
1791
1792 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1793 "APInt size does not match type size!");
1794 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1795 SDVTList VTs = getVTList(EltVT);
1796 SDNodeKey ID(Opc, VTs, {});
1797 ID.AddPointer(Elt);
1798 ID.AddBoolean(isO);
1799 FoldingSetInsertToken InsertToken;
1800 SDNode *N = nullptr;
1801 if ((N = lookupNode(ID, DL, InsertToken)))
1802 if (!VT.isVector())
1803 return SDValue(N, 0);
1804
1805 if (!N) {
1806 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1807 if (!isT)
1808 N->setDebugLoc(DL.getDebugLoc());
1809 CSEMap.insert(N, InsertToken);
1810 InsertNode(N);
1811 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1812 }
1813
1814 SDValue Result(N, 0);
1815 if (VT.isVector())
1816 Result = getSplat(VT, DL, Result);
1817 return Result;
1818}
1819
1821 bool isT, bool isO) {
1822 unsigned Size = VT.getScalarSizeInBits();
1823 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1824}
1825
1827 bool IsOpaque) {
1829 IsTarget, IsOpaque);
1830}
1831
1833 bool isTarget) {
1834 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1835}
1836
1838 const SDLoc &DL) {
1839 assert(VT.isInteger() && "Shift amount is not an integer type!");
1840 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1841 return getConstant(Val, DL, ShiftVT);
1842}
1843
1845 const SDLoc &DL) {
1846 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1847 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1848}
1849
1851 bool isTarget) {
1852 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1853}
1854
1856 bool isTarget) {
1857 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1858}
1859
1861 EVT VT, bool isTarget) {
1862 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1863
1864 EVT EltVT = VT.getScalarType();
1865 const ConstantFP *Elt = &V;
1866
1867 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1868 // the to-be-splatted scalar ConstantFP.
1869 if (isa<VectorType>(Elt->getType()))
1870 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1871
1872 // Do the map lookup using the actual bit pattern for the floating point
1873 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1874 // we don't have issues with SNANs.
1875 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1876 SDVTList VTs = getVTList(EltVT);
1877 SDNodeKey ID(Opc, VTs, {});
1878 ID.AddPointer(Elt);
1879 FoldingSetInsertToken InsertToken;
1880 SDNode *N = nullptr;
1881 if ((N = lookupNode(ID, DL, InsertToken)))
1882 if (!VT.isVector())
1883 return SDValue(N, 0);
1884
1885 if (!N) {
1886 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1887 CSEMap.insert(N, InsertToken);
1888 InsertNode(N);
1889 }
1890
1891 SDValue Result(N, 0);
1892 if (VT.isVector())
1893 Result = getSplat(VT, DL, Result);
1894 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1895 return Result;
1896}
1897
1899 bool isTarget) {
1900 EVT EltVT = VT.getScalarType();
1901 if (EltVT == MVT::f32)
1902 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1903 if (EltVT == MVT::f64)
1904 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1905 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1906 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1907 bool Ignored;
1908 APFloat APF = APFloat(Val);
1910 &Ignored);
1911 return getConstantFP(APF, DL, VT, isTarget);
1912 }
1913 llvm_unreachable("Unsupported type in getConstantFP");
1914}
1915
1917 EVT VT, int64_t Offset, bool isTargetGA,
1918 unsigned TargetFlags) {
1919 assert((TargetFlags == 0 || isTargetGA) &&
1920 "Cannot set target flags on target-independent globals");
1921
1922 // Truncate (with sign-extension) the offset value to the pointer size.
1924 if (BitWidth < 64)
1926
1927 unsigned Opc;
1928 if (GV->isThreadLocal())
1930 else
1932
1933 SDVTList VTs = getVTList(VT);
1934 SDNodeKey ID(Opc, VTs, {});
1935 ID.AddPointer(GV);
1936 ID.AddInteger(Offset);
1937 ID.AddInteger(TargetFlags);
1938 FoldingSetInsertToken InsertToken;
1939 if (SDNode *E = lookupNode(ID, DL, InsertToken))
1940 return SDValue(E, 0);
1941
1942 auto *N = newSDNode<GlobalAddressSDNode>(
1943 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1944 CSEMap.insert(N, InsertToken);
1945 InsertNode(N);
1946 return SDValue(N, 0);
1947}
1948
1950 SDVTList VTs = getVTList(MVT::Untyped);
1952 ID.AddPointer(GV);
1953 FoldingSetInsertToken InsertToken;
1954 if (SDNode *E = lookupNode(ID, SDLoc(), InsertToken))
1955 return SDValue(E, 0);
1956
1957 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1958 CSEMap.insert(N, InsertToken);
1959 InsertNode(N);
1960 return SDValue(N, 0);
1961}
1962
1963SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1964 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1965 SDVTList VTs = getVTList(VT);
1966 SDNodeKey ID(Opc, VTs, {});
1967 ID.AddInteger(FI);
1968 FoldingSetInsertToken InsertToken;
1969 if (SDNode *E = lookupNode(ID, InsertToken))
1970 return SDValue(E, 0);
1971
1972 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1973 CSEMap.insert(N, InsertToken);
1974 InsertNode(N);
1975 return SDValue(N, 0);
1976}
1977
1978SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1979 unsigned TargetFlags) {
1980 assert((TargetFlags == 0 || isTarget) &&
1981 "Cannot set target flags on target-independent jump tables");
1982 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1983 SDVTList VTs = getVTList(VT);
1984 SDNodeKey ID(Opc, VTs, {});
1985 ID.AddInteger(JTI);
1986 ID.AddInteger(TargetFlags);
1987 FoldingSetInsertToken InsertToken;
1988 if (SDNode *E = lookupNode(ID, InsertToken))
1989 return SDValue(E, 0);
1990
1991 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
1992 CSEMap.insert(N, InsertToken);
1993 InsertNode(N);
1994 return SDValue(N, 0);
1995}
1996
1998 const SDLoc &DL) {
2000 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2001 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2002}
2003
2005 MaybeAlign Alignment, int Offset,
2006 bool isTarget, unsigned TargetFlags) {
2007 assert((TargetFlags == 0 || isTarget) &&
2008 "Cannot set target flags on target-independent globals");
2009 if (!Alignment)
2010 Alignment = shouldOptForSize()
2011 ? getDataLayout().getABITypeAlign(C->getType())
2012 : getDataLayout().getPrefTypeAlign(C->getType());
2013 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2014 SDVTList VTs = getVTList(VT);
2015 SDNodeKey ID(Opc, VTs, {});
2016 ID.AddInteger(Alignment->value());
2017 ID.AddInteger(Offset);
2018 ID.AddPointer(C);
2019 ID.AddInteger(TargetFlags);
2020 FoldingSetInsertToken InsertToken;
2021 if (SDNode *E = lookupNode(ID, InsertToken))
2022 return SDValue(E, 0);
2023
2024 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2025 TargetFlags);
2026 CSEMap.insert(N, InsertToken);
2027 InsertNode(N);
2028 SDValue V = SDValue(N, 0);
2029 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2030 return V;
2031}
2032
2034 MaybeAlign Alignment, int Offset,
2035 bool isTarget, unsigned TargetFlags) {
2036 assert((TargetFlags == 0 || isTarget) &&
2037 "Cannot set target flags on target-independent globals");
2038 if (!Alignment)
2039 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2040 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2041 SDVTList VTs = getVTList(VT);
2042 SDNodeKey ID(Opc, VTs, {});
2043 ID.AddInteger(Alignment->value());
2044 ID.AddInteger(Offset);
2045 C->addSelectionDAGCSEId(ID.Tail);
2046 ID.AddInteger(TargetFlags);
2047 FoldingSetInsertToken InsertToken;
2048 if (SDNode *E = lookupNode(ID, InsertToken))
2049 return SDValue(E, 0);
2050
2051 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2052 TargetFlags);
2053 CSEMap.insert(N, InsertToken);
2054 InsertNode(N);
2055 return SDValue(N, 0);
2056}
2057
2059 SDNodeKey ID(ISD::BasicBlock, getVTList(MVT::Other), {});
2060 ID.AddPointer(MBB);
2061 FoldingSetInsertToken InsertToken;
2062 if (SDNode *E = lookupNode(ID, InsertToken))
2063 return SDValue(E, 0);
2064
2065 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2066 CSEMap.insert(N, InsertToken);
2067 InsertNode(N);
2068 return SDValue(N, 0);
2069}
2070
2072 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2073 ValueTypeNodes.size())
2074 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2075
2076 SDNode *&N = VT.isExtended() ?
2077 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2078
2079 if (N) return SDValue(N, 0);
2080 N = newSDNode<VTSDNode>(VT);
2081 InsertNode(N);
2082 return SDValue(N, 0);
2083}
2084
2086 SDNode *&N = ExternalSymbols[Sym];
2087 if (N) return SDValue(N, 0);
2088 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2089 InsertNode(N);
2090 return SDValue(N, 0);
2091}
2092
2093SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2095 return getExternalSymbol(SymName.data(), VT);
2096}
2097
2099 SDNode *&N = MCSymbols[Sym];
2100 if (N)
2101 return SDValue(N, 0);
2102 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2103 InsertNode(N);
2104 return SDValue(N, 0);
2105}
2106
2108 unsigned TargetFlags) {
2109 SDNode *&N =
2110 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2111 if (N) return SDValue(N, 0);
2112 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2113 InsertNode(N);
2114 return SDValue(N, 0);
2115}
2116
2118 EVT VT, unsigned TargetFlags) {
2120 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2121}
2122
2124 if ((unsigned)Cond >= CondCodeNodes.size())
2125 CondCodeNodes.resize(Cond+1);
2126
2127 if (!CondCodeNodes[Cond]) {
2128 auto *N = newSDNode<CondCodeSDNode>(Cond);
2129 CondCodeNodes[Cond] = N;
2130 InsertNode(N);
2131 }
2132
2133 return SDValue(CondCodeNodes[Cond], 0);
2134}
2135
2137 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2138 "APInt size does not match type size!");
2139
2140 if (MulImm == 0)
2141 return getConstant(0, DL, VT);
2142
2143 const MachineFunction &MF = getMachineFunction();
2144 const Function &F = MF.getFunction();
2145 ConstantRange CR = getVScaleRange(&F, 64);
2146 if (const APInt *C = CR.getSingleElement())
2147 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2148
2149 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2150}
2151
2152/// \returns a value of type \p VT that represents the runtime value of \p
2153/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2154/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2155/// or TypeSize.
2156template <typename Ty>
2158 EVT VT, Ty Quantity) {
2159 if (Quantity.isScalable())
2160 return DAG.getVScale(
2161 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2162
2163 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2164}
2165
2167 ElementCount EC) {
2168 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2169}
2170
2172 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2173}
2174
2176 ElementCount EC) {
2177 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2178 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2179 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2180 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2181}
2182
2184 APInt One(ResVT.getScalarSizeInBits(), 1);
2185 return getStepVector(DL, ResVT, One);
2186}
2187
2189 const APInt &StepVal) {
2190 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2191 if (ResVT.isScalableVector())
2192 return getNode(
2193 ISD::STEP_VECTOR, DL, ResVT,
2194 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2195
2196 SmallVector<SDValue, 16> OpsStepConstants;
2197 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2198 OpsStepConstants.push_back(
2199 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2200 return getBuildVector(ResVT, DL, OpsStepConstants);
2201}
2202
2203/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2204/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2209
2211 SDValue N2, ArrayRef<int> Mask) {
2212 assert(VT.getVectorNumElements() == Mask.size() &&
2213 "Must have the same number of vector elements as mask elements!");
2214 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2215 "Invalid VECTOR_SHUFFLE");
2216
2217 // Canonicalize shuffle undef, undef -> undef
2218 if (N1.isUndef() && N2.isUndef()) {
2219 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2220 return getPOISON(VT);
2221 return getUNDEF(VT);
2222 }
2223
2224 // Validate that all indices in Mask are within the range of the elements
2225 // input to the shuffle.
2226 int NElts = Mask.size();
2227 assert(llvm::all_of(Mask,
2228 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2229 "Index out of range");
2230
2231 // Copy the mask so we can do any needed cleanup.
2232 SmallVector<int, 8> MaskVec(Mask);
2233
2234 // Canonicalize shuffle v, v -> v, poison
2235 if (N1 == N2) {
2236 N2 = getPOISON(VT);
2237 for (int i = 0; i != NElts; ++i)
2238 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2239 }
2240
2241 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2242 if (N1.isUndef())
2243 commuteShuffle(N1, N2, MaskVec);
2244
2245 if (TLI->hasVectorBlend()) {
2246 // If shuffling a splat, try to blend the splat instead. We do this here so
2247 // that even when this arises during lowering we don't have to re-handle it.
2248 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2249 BitVector UndefElements;
2250 SDValue Splat = BV->getSplatValue(&UndefElements);
2251 if (!Splat)
2252 return;
2253
2254 for (int i = 0; i < NElts; ++i) {
2255 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2256 continue;
2257
2258 // If this input comes from undef, mark it as such.
2259 if (UndefElements[MaskVec[i] - Offset]) {
2260 MaskVec[i] = -1;
2261 continue;
2262 }
2263
2264 // If we can blend a non-undef lane, use that instead.
2265 if (!UndefElements[i])
2266 MaskVec[i] = i + Offset;
2267 }
2268 };
2269 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2270 BlendSplat(N1BV, 0);
2271 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2272 BlendSplat(N2BV, NElts);
2273 }
2274
2275 // Canonicalize all index into lhs, -> shuffle lhs, poison
2276 // Canonicalize all index into rhs, -> shuffle rhs, poison
2277 bool AllLHS = true, AllRHS = true;
2278 bool N2Undef = N2.isUndef();
2279 for (int i = 0; i != NElts; ++i) {
2280 if (MaskVec[i] >= NElts) {
2281 if (N2Undef)
2282 MaskVec[i] = -1;
2283 else
2284 AllLHS = false;
2285 } else if (MaskVec[i] >= 0) {
2286 AllRHS = false;
2287 }
2288 }
2289 if (AllLHS && AllRHS)
2290 return getPOISON(VT);
2291 if (AllLHS && !N2Undef)
2292 N2 = getPOISON(VT);
2293 if (AllRHS) {
2294 N1 = getPOISON(VT);
2295 commuteShuffle(N1, N2, MaskVec);
2296 }
2297 // Reset our undef status after accounting for the mask.
2298 N2Undef = N2.isUndef();
2299 // Re-check whether both sides ended up undef.
2300 if (N1.isUndef() && N2Undef) {
2301 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2302 return getPOISON(VT);
2303 return getUNDEF(VT);
2304 }
2305
2306 // If Identity shuffle return that node.
2307 bool Identity = true, AllSame = true;
2308 for (int i = 0; i != NElts; ++i) {
2309 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2310 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2311 }
2312 if (Identity && NElts)
2313 return N1;
2314
2315 // Shuffling a constant splat doesn't change the result.
2316 if (N2Undef) {
2317 SDValue V = N1;
2318
2319 // Look through any bitcasts. We check that these don't change the number
2320 // (and size) of elements and just changes their types.
2321 while (V.getOpcode() == ISD::BITCAST)
2322 V = V->getOperand(0);
2323
2324 // A splat should always show up as a build vector node.
2325 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2326 BitVector UndefElements;
2327 SDValue Splat = BV->getSplatValue(&UndefElements);
2328 // If this is a splat of an undef, shuffling it is also undef.
2329 if (Splat && Splat.isUndef())
2330 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2331
2332 bool SameNumElts =
2333 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2334
2335 // We only have a splat which can skip shuffles if there is a splatted
2336 // value and no undef lanes rearranged by the shuffle.
2337 if (Splat && UndefElements.none()) {
2338 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2339 // number of elements match or the value splatted is a zero constant.
2340 if (SameNumElts || isNullConstant(Splat))
2341 return N1;
2342 }
2343
2344 // If the shuffle itself creates a splat, build the vector directly.
2345 if (AllSame && SameNumElts) {
2346 EVT BuildVT = BV->getValueType(0);
2347 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2348 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2349
2350 // We may have jumped through bitcasts, so the type of the
2351 // BUILD_VECTOR may not match the type of the shuffle.
2352 if (BuildVT != VT)
2353 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2354 return NewBV;
2355 }
2356 }
2357 }
2358
2359 SDVTList VTs = getVTList(VT);
2360 SDValue Ops[2] = { N1, N2 };
2362 for (int i = 0; i != NElts; ++i)
2363 ID.AddInteger(MaskVec[i]);
2364
2365 FoldingSetInsertToken InsertToken;
2366 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2367 return SDValue(E, 0);
2368
2369 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2370 // SDNode doesn't have access to it. This memory will be "leaked" when
2371 // the node is deallocated, but recovered when the NodeAllocator is released.
2372 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2373 llvm::copy(MaskVec, MaskAlloc);
2374
2375 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2376 dl.getDebugLoc(), MaskAlloc);
2377 createOperands(N, Ops);
2378
2379 CSEMap.insert(N, InsertToken);
2380 InsertNode(N);
2381 SDValue V = SDValue(N, 0);
2382 NewSDValueDbgMsg(V, "Creating new node: ", this);
2383 return V;
2384}
2385
2387 EVT VT = SV.getValueType(0);
2388 SmallVector<int, 8> MaskVec(SV.getMask());
2390
2391 SDValue Op0 = SV.getOperand(0);
2392 SDValue Op1 = SV.getOperand(1);
2393 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2394}
2395
2397 SDVTList VTs = getVTList(VT);
2398 SDNodeKey ID(ISD::Register, VTs, {});
2399 ID.AddInteger(Reg.id());
2400 FoldingSetInsertToken InsertToken;
2401 if (SDNode *E = lookupNode(ID, InsertToken))
2402 return SDValue(E, 0);
2403
2404 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2405 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2406 CSEMap.insert(N, InsertToken);
2407 InsertNode(N);
2408 return SDValue(N, 0);
2409}
2410
2412 SDNodeKey ID(ISD::RegisterMask, getVTList(MVT::Untyped), {});
2413 ID.AddPointer(RegMask);
2414 FoldingSetInsertToken InsertToken;
2415 if (SDNode *E = lookupNode(ID, InsertToken))
2416 return SDValue(E, 0);
2417
2418 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2419 CSEMap.insert(N, InsertToken);
2420 InsertNode(N);
2421 return SDValue(N, 0);
2422}
2423
2425 MCSymbol *Label) {
2426 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2427}
2428
2429SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2430 SDValue Root, MCSymbol *Label) {
2431 SDValue Ops[] = { Root };
2432 SDNodeKey ID(Opcode, getVTList(MVT::Other), Ops);
2433 ID.AddPointer(Label);
2434 FoldingSetInsertToken InsertToken;
2435 if (SDNode *E = lookupNode(ID, InsertToken))
2436 return SDValue(E, 0);
2437
2438 auto *N =
2439 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2440 createOperands(N, Ops);
2441
2442 CSEMap.insert(N, InsertToken);
2443 InsertNode(N);
2444 return SDValue(N, 0);
2445}
2446
2448 int64_t Offset, bool isTarget,
2449 unsigned TargetFlags) {
2450 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2451 SDVTList VTs = getVTList(VT);
2452
2453 SDNodeKey ID(Opc, VTs, {});
2454 ID.AddPointer(BA);
2455 ID.AddInteger(Offset);
2456 ID.AddInteger(TargetFlags);
2457 FoldingSetInsertToken InsertToken;
2458 if (SDNode *E = lookupNode(ID, InsertToken))
2459 return SDValue(E, 0);
2460
2461 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2462 CSEMap.insert(N, InsertToken);
2463 InsertNode(N);
2464 return SDValue(N, 0);
2465}
2466
2468 SDNodeKey ID(ISD::SRCVALUE, getVTList(MVT::Other), {});
2469 ID.AddPointer(V);
2470
2471 FoldingSetInsertToken InsertToken;
2472 if (SDNode *E = lookupNode(ID, InsertToken))
2473 return SDValue(E, 0);
2474
2475 auto *N = newSDNode<SrcValueSDNode>(V);
2476 CSEMap.insert(N, InsertToken);
2477 InsertNode(N);
2478 return SDValue(N, 0);
2479}
2480
2482 SDNodeKey ID(ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2483 ID.AddPointer(MD);
2484
2485 FoldingSetInsertToken InsertToken;
2486 if (SDNode *E = lookupNode(ID, InsertToken))
2487 return SDValue(E, 0);
2488
2489 auto *N = newSDNode<MDNodeSDNode>(MD);
2490 CSEMap.insert(N, InsertToken);
2491 InsertNode(N);
2492 return SDValue(N, 0);
2493}
2494
2496 if (VT == V.getValueType())
2497 return V;
2498
2499 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2500}
2501
2503 unsigned SrcAS, unsigned DestAS,
2504 const SDNodeFlags Flags) {
2505 SDVTList VTs = getVTList(VT);
2506 SDValue Ops[] = {Ptr};
2508 ID.AddInteger(SrcAS);
2509 ID.AddInteger(DestAS);
2510
2511 FoldingSetInsertToken InsertToken;
2512 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
2513 E->intersectFlagsWith(Flags);
2514 return SDValue(E, 0);
2515 }
2516
2517 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2518 VTs, SrcAS, DestAS);
2519 N->setFlags(Flags);
2520 createOperands(N, Ops);
2521
2522 CSEMap.insert(N, InsertToken);
2523 InsertNode(N);
2524 return SDValue(N, 0);
2525}
2526
2528 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2529}
2530
2532 UndefPoisonKind Kind) {
2533 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2534 return V;
2535 return getFreeze(V);
2536}
2537
2538/// getShiftAmountOperand - Return the specified value casted to
2539/// the target's desired shift amount type.
2541 EVT OpTy = Op.getValueType();
2542 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2543 if (OpTy == ShTy || OpTy.isVector()) return Op;
2544
2545 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2546}
2547
2549 SDLoc dl(Node);
2551 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2552 EVT VT = Node->getValueType(0);
2553 SDValue Tmp1 = Node->getOperand(0);
2554 SDValue Tmp2 = Node->getOperand(1);
2555 const MaybeAlign MA(Node->getConstantOperandVal(3));
2556
2557 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2558 Tmp2, MachinePointerInfo(V));
2559 SDValue VAList = VAListLoad;
2560
2561 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2562 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2563 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2564
2565 VAList = getNode(
2566 ISD::AND, dl, VAList.getValueType(), VAList,
2567 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2568 }
2569
2570 // Increment the pointer, VAList, to the next vaarg
2571 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2572 getConstant(getDataLayout().getTypeAllocSize(
2573 VT.getTypeForEVT(*getContext())),
2574 dl, VAList.getValueType()));
2575 // Store the incremented VAList to the legalized pointer
2576 Tmp1 =
2577 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2578 // Load the actual argument out of the pointer VAList
2579 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2580}
2581
2583 SDLoc dl(Node);
2585 // This defaults to loading a pointer from the input and storing it to the
2586 // output, returning the chain.
2587 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2588 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2589 SDValue Tmp1 =
2590 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2591 Node->getOperand(2), MachinePointerInfo(VS));
2592 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2593 MachinePointerInfo(VD));
2594}
2595
2597 const DataLayout &DL = getDataLayout();
2598 Type *Ty = VT.getTypeForEVT(*getContext());
2599 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2600
2601 if (TLI->isTypeLegal(VT) || !VT.isVector())
2602 return RedAlign;
2603
2604 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2605 const Align StackAlign = TFI->getStackAlign();
2606
2607 // See if we can choose a smaller ABI alignment in cases where it's an
2608 // illegal vector type that will get broken down.
2609 if (RedAlign > StackAlign) {
2610 EVT IntermediateVT;
2611 MVT RegisterVT;
2612 unsigned NumIntermediates;
2613 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2614 NumIntermediates, RegisterVT);
2615 Ty = IntermediateVT.getTypeForEVT(*getContext());
2616 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2617 if (RedAlign2 < RedAlign)
2618 RedAlign = RedAlign2;
2619
2620 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2621 // If the stack is not realignable, the alignment should be limited to the
2622 // StackAlignment
2623 RedAlign = std::min(RedAlign, StackAlign);
2624 }
2625
2626 return RedAlign;
2627}
2628
2630 MachineFrameInfo &MFI = MF->getFrameInfo();
2631 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2632 int StackID = 0;
2633 if (Bytes.isScalable())
2634 StackID = TFI->getStackIDForScalableVectors();
2635 // The stack id gives an indication of whether the object is scalable or
2636 // not, so it's safe to pass in the minimum size here.
2637 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2638 false, nullptr, StackID);
2639 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2640}
2641
2643 Type *Ty = VT.getTypeForEVT(*getContext());
2644 Align StackAlign =
2645 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2646 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2647}
2648
2650 TypeSize VT1Size = VT1.getStoreSize();
2651 TypeSize VT2Size = VT2.getStoreSize();
2652 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2653 "Don't know how to choose the maximum size when creating a stack "
2654 "temporary");
2655 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2656 ? VT1Size
2657 : VT2Size;
2658
2659 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2660 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2661 const DataLayout &DL = getDataLayout();
2662 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2663 return CreateStackTemporary(Bytes, Align);
2664}
2665
2667 const SDLoc &DL, SDValue Chain) {
2668 EVT SrcVT = SrcOp.getValueType();
2669 Type *DestType = DestVT.getTypeForEVT(*getContext());
2670 Align DestAlign = getDataLayout().getPrefTypeAlign(DestType);
2671
2672 // Create the stack frame object.
2673 Align SrcAlign =
2675 SDValue FIPtr = CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
2676
2677 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
2678 int SPFI = StackPtrFI->getIndex();
2679 MachinePointerInfo PtrInfo =
2681
2682 // Emit a store to the stack slot. Use a truncstore if the input value is
2683 // later than DestVT.
2684 SDValue Store;
2685
2686 if (SrcVT.bitsGT(SlotVT))
2687 Store = getTruncStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SlotVT, SrcAlign);
2688 else {
2689 assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
2690 Store = getStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SrcAlign);
2691 }
2692
2693 // Result is a load from the stack slot.
2694 if (SlotVT.bitsEq(DestVT))
2695 return getLoad(DestVT, DL, Store, FIPtr, PtrInfo, DestAlign);
2696
2697 assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
2698 return getExtLoad(ISD::EXTLOAD, DL, DestVT, Store, FIPtr, PtrInfo, SlotVT,
2699 DestAlign);
2700}
2701
2703 ISD::CondCode Cond, const SDLoc &dl,
2704 SDNodeFlags Flags) {
2705 EVT OpVT = N1.getValueType();
2706
2707 auto GetUndefBooleanConstant = [&]() {
2708 if (VT.getScalarType() == MVT::i1 ||
2709 TLI->getBooleanContents(OpVT) ==
2711 return getUNDEF(VT);
2712 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2713 // so we cannot use getUNDEF(). Return zero instead.
2714 return getConstant(0, dl, VT);
2715 };
2716
2717 // These setcc operations always fold.
2718 switch (Cond) {
2719 default: break;
2720 case ISD::SETFALSE:
2721 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2722 case ISD::SETTRUE:
2723 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2724
2725 case ISD::SETOEQ:
2726 case ISD::SETOGT:
2727 case ISD::SETOGE:
2728 case ISD::SETOLT:
2729 case ISD::SETOLE:
2730 case ISD::SETONE:
2731 case ISD::SETO:
2732 case ISD::SETUO:
2733 case ISD::SETUEQ:
2734 case ISD::SETUNE:
2735 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2736 break;
2737 }
2738
2739 if (OpVT.isInteger()) {
2740 // For EQ and NE, we can always pick a value for the undef to make the
2741 // predicate pass or fail, so we can return undef.
2742 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2743 // icmp eq/ne X, undef -> undef.
2744 if ((N1.isUndef() || N2.isUndef()) &&
2745 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2746 return GetUndefBooleanConstant();
2747
2748 // If both operands are undef, we can return undef for int comparison.
2749 // icmp undef, undef -> undef.
2750 if (N1.isUndef() && N2.isUndef())
2751 return GetUndefBooleanConstant();
2752
2753 // icmp X, X -> true/false
2754 // icmp X, undef -> true/false because undef could be X.
2755 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2756 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2757 }
2758
2759 if (ConstantSDNode *N2C = isConstOrConstSplat(N2)) {
2760 const APInt &C2 = N2C->getAPIntValue();
2761 if (ConstantSDNode *N1C = isConstOrConstSplat(N1)) {
2762 const APInt &C1 = N1C->getAPIntValue();
2763
2765 dl, VT, OpVT);
2766 }
2767 }
2768
2769 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2770 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2771
2772 if (N1CFP && N2CFP) {
2773 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2774 switch (Cond) {
2775 default: break;
2776 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2777 return GetUndefBooleanConstant();
2778 [[fallthrough]];
2779 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2780 OpVT);
2781 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2782 return GetUndefBooleanConstant();
2783 [[fallthrough]];
2785 R==APFloat::cmpLessThan, dl, VT,
2786 OpVT);
2787 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2788 return GetUndefBooleanConstant();
2789 [[fallthrough]];
2790 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2791 OpVT);
2792 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2793 return GetUndefBooleanConstant();
2794 [[fallthrough]];
2796 VT, OpVT);
2797 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2798 return GetUndefBooleanConstant();
2799 [[fallthrough]];
2801 R==APFloat::cmpEqual, dl, VT,
2802 OpVT);
2803 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2804 return GetUndefBooleanConstant();
2805 [[fallthrough]];
2807 R==APFloat::cmpEqual, dl, VT, OpVT);
2808 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2809 OpVT);
2810 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2811 OpVT);
2813 R==APFloat::cmpEqual, dl, VT,
2814 OpVT);
2815 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2816 OpVT);
2818 R==APFloat::cmpLessThan, dl, VT,
2819 OpVT);
2821 R==APFloat::cmpUnordered, dl, VT,
2822 OpVT);
2824 VT, OpVT);
2825 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2826 OpVT);
2827 }
2828 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2829 // Ensure that the constant occurs on the RHS.
2831 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2832 return SDValue();
2833 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2834 /*IsSignaling=*/false, Flags);
2835 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2836 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2837 // If an operand is known to be a nan (or undef that could be a nan), we can
2838 // fold it.
2839 // Choosing NaN for the undef will always make unordered comparison succeed
2840 // and ordered comparison fails.
2841 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2842 switch (ISD::getUnorderedFlavor(Cond)) {
2843 default:
2844 llvm_unreachable("Unknown flavor!");
2845 case 0: // Known false.
2846 return getBoolConstant(false, dl, VT, OpVT);
2847 case 1: // Known true.
2848 return getBoolConstant(true, dl, VT, OpVT);
2849 case 2: // Undefined.
2850 return GetUndefBooleanConstant();
2851 }
2852 }
2853
2854 // Could not fold it.
2855 return SDValue();
2856}
2857
2858/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2859/// use this predicate to simplify operations downstream.
2861 unsigned BitWidth = Op.getScalarValueSizeInBits();
2863}
2864
2865// TODO: Should have argument to specify if sign bit of nan is ignorable.
2867 if (Depth >= MaxRecursionDepth)
2868 return false; // Limit search depth.
2869
2870 unsigned Opc = Op.getOpcode();
2871 switch (Opc) {
2872 case ISD::FABS:
2873 return true;
2874 case ISD::AssertNoFPClass: {
2875 FPClassTest NoFPClass =
2876 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2877
2878 const FPClassTest TestMask = fcNan | fcNegative;
2879 return (NoFPClass & TestMask) == TestMask;
2880 }
2881 case ISD::ARITH_FENCE:
2882 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2883 case ISD::FEXP:
2884 case ISD::FEXP2:
2885 case ISD::FEXP10:
2886 return Op->getFlags().hasNoNaNs();
2887 case ISD::FMINNUM:
2888 case ISD::FMINNUM_IEEE:
2889 case ISD::FMINIMUM:
2890 case ISD::FMINIMUMNUM:
2891 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2892 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2893 case ISD::FMAXNUM:
2894 case ISD::FMAXNUM_IEEE:
2895 case ISD::FMAXIMUM:
2896 case ISD::FMAXIMUMNUM:
2897 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2898 // is sufficient.
2899 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2900 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2901 default:
2902 return false;
2903 }
2904
2905 llvm_unreachable("covered opcode switch");
2906}
2907
2908/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2909/// this predicate to simplify operations downstream. Mask is known to be zero
2910/// for bits that V cannot have.
2912 unsigned Depth) const {
2913 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2914}
2915
2916/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2917/// DemandedElts. We use this predicate to simplify operations downstream.
2918/// Mask is known to be zero for bits that V cannot have.
2920 const APInt &DemandedElts,
2921 unsigned Depth) const {
2922 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2923}
2924
2925/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2926/// DemandedElts. We use this predicate to simplify operations downstream.
2928 unsigned Depth /* = 0 */) const {
2929 return computeKnownBits(V, DemandedElts, Depth).isZero();
2930}
2931
2932/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2934 unsigned Depth) const {
2935 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2936}
2937
2939 const APInt &DemandedElts,
2940 unsigned Depth) const {
2941 EVT VT = Op.getValueType();
2942 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2943
2944 unsigned NumElts = VT.getVectorNumElements();
2945 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2946
2947 APInt KnownZeroElements = APInt::getZero(NumElts);
2948 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2949 if (!DemandedElts[EltIdx])
2950 continue; // Don't query elements that are not demanded.
2951 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2952 if (MaskedVectorIsZero(Op, Mask, Depth))
2953 KnownZeroElements.setBit(EltIdx);
2954 }
2955 return KnownZeroElements;
2956}
2957
2958/// isSplatValue - Return true if the vector V has the same value
2959/// across all DemandedElts. For scalable vectors, we don't know the
2960/// number of lanes at compile time. Instead, we use a 1 bit APInt
2961/// to represent a conservative value for all lanes; that is, that
2962/// one bit value is implicitly splatted across all lanes.
2963bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2964 APInt &UndefElts, unsigned Depth) const {
2965 unsigned Opcode = V.getOpcode();
2966 EVT VT = V.getValueType();
2967 assert(VT.isVector() && "Vector type expected");
2968 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2969 "scalable demanded bits are ignored");
2970
2971 if (!DemandedElts)
2972 return false; // No demanded elts, better to assume we don't know anything.
2973
2974 if (Depth >= MaxRecursionDepth)
2975 return false; // Limit search depth.
2976
2977 // Deal with some common cases here that work for both fixed and scalable
2978 // vector types.
2979 switch (Opcode) {
2980 case ISD::SPLAT_VECTOR:
2981 UndefElts = V.getOperand(0).isUndef()
2982 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2983 : APInt(DemandedElts.getBitWidth(), 0);
2984 return true;
2985 case ISD::ADD:
2986 case ISD::SUB:
2987 case ISD::AND:
2988 case ISD::XOR:
2989 case ISD::OR: {
2990 APInt UndefLHS, UndefRHS;
2991 SDValue LHS = V.getOperand(0);
2992 SDValue RHS = V.getOperand(1);
2993 // Only recognize splats with the same demanded undef elements for both
2994 // operands, otherwise we might fail to handle binop-specific undef
2995 // handling.
2996 // e.g. (and undef, 0) -> 0 etc.
2997 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2998 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2999 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
3000 UndefElts = UndefLHS | UndefRHS;
3001 return true;
3002 }
3003 return false;
3004 }
3005 case ISD::ABS:
3007 case ISD::TRUNCATE:
3008 case ISD::SIGN_EXTEND:
3009 case ISD::ZERO_EXTEND:
3010 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3011 default:
3012 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3013 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3014 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3015 Depth);
3016 break;
3017 }
3018
3019 // We don't support other cases than those above for scalable vectors at
3020 // the moment.
3021 if (VT.isScalableVector())
3022 return false;
3023
3024 unsigned NumElts = VT.getVectorNumElements();
3025 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3026 UndefElts = APInt::getZero(NumElts);
3027
3028 switch (Opcode) {
3029 case ISD::BUILD_VECTOR: {
3030 SDValue Scl;
3031 for (unsigned i = 0; i != NumElts; ++i) {
3032 SDValue Op = V.getOperand(i);
3033 if (Op.isUndef()) {
3034 UndefElts.setBit(i);
3035 continue;
3036 }
3037 if (!DemandedElts[i])
3038 continue;
3039 if (Scl && Scl != Op)
3040 return false;
3041 Scl = Op;
3042 }
3043 return true;
3044 }
3045 case ISD::VECTOR_SHUFFLE: {
3046 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3047 APInt DemandedLHS = APInt::getZero(NumElts);
3048 APInt DemandedRHS = APInt::getZero(NumElts);
3049 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3050 for (int i = 0; i != (int)NumElts; ++i) {
3051 int M = Mask[i];
3052 if (M < 0) {
3053 UndefElts.setBit(i);
3054 continue;
3055 }
3056 if (!DemandedElts[i])
3057 continue;
3058 if (M < (int)NumElts)
3059 DemandedLHS.setBit(M);
3060 else
3061 DemandedRHS.setBit(M - NumElts);
3062 }
3063
3064 // If we aren't demanding either op, assume there's no splat.
3065 // If we are demanding both ops, assume there's no splat.
3066 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3067 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3068 return false;
3069
3070 // See if the demanded elts of the source op is a splat or we only demand
3071 // one element, which should always be a splat.
3072 // TODO: Handle source ops splats with undefs.
3073 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3074 APInt SrcUndefs;
3075 return (SrcElts.popcount() == 1) ||
3076 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3077 (SrcElts & SrcUndefs).isZero());
3078 };
3079 if (!DemandedLHS.isZero())
3080 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3081 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3082 }
3084 // Offset the demanded elts by the subvector index.
3085 SDValue Src = V.getOperand(0);
3086 // We don't support scalable vectors at the moment.
3087 if (Src.getValueType().isScalableVector())
3088 return false;
3089 uint64_t Idx = V.getConstantOperandVal(1);
3090 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3091 APInt UndefSrcElts;
3092 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3093 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3094 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3095 return true;
3096 }
3097 break;
3098 }
3102 // Widen the demanded elts by the src element count.
3103 SDValue Src = V.getOperand(0);
3104 // We don't support scalable vectors at the moment.
3105 if (Src.getValueType().isScalableVector())
3106 return false;
3107 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3108 APInt UndefSrcElts;
3109 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3110 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3111 UndefElts = UndefSrcElts.trunc(NumElts);
3112 return true;
3113 }
3114 break;
3115 }
3116 case ISD::BITCAST: {
3117 SDValue Src = V.getOperand(0);
3118 EVT SrcVT = Src.getValueType();
3119 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3120 unsigned BitWidth = VT.getScalarSizeInBits();
3121
3122 // Ignore bitcasts from unsupported types.
3123 // TODO: Add fp support?
3124 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3125 break;
3126
3127 // Bitcast 'small element' vector to 'large element' vector.
3128 if ((BitWidth % SrcBitWidth) == 0) {
3129 // See if each sub element is a splat.
3130 unsigned Scale = BitWidth / SrcBitWidth;
3131 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3132 APInt ScaledDemandedElts =
3133 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3134 for (unsigned I = 0; I != Scale; ++I) {
3135 APInt SubUndefElts;
3136 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3137 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3138 SubDemandedElts &= ScaledDemandedElts;
3139 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3140 return false;
3141 // TODO: Add support for merging sub undef elements.
3142 if (!SubUndefElts.isZero())
3143 return false;
3144 }
3145 return true;
3146 }
3147 break;
3148 }
3149 }
3150
3151 return false;
3152}
3153
3154/// Helper wrapper to main isSplatValue function.
3155bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3156 EVT VT = V.getValueType();
3157 assert(VT.isVector() && "Vector type expected");
3158
3159 APInt UndefElts;
3160 // Since the number of lanes in a scalable vector is unknown at compile time,
3161 // we track one bit which is implicitly broadcast to all lanes. This means
3162 // that all lanes in a scalable vector are considered demanded.
3163 APInt DemandedElts
3165 return isSplatValue(V, DemandedElts, UndefElts) &&
3166 (AllowUndefs || !UndefElts);
3167}
3168
3171
3172 EVT VT = V.getValueType();
3173 unsigned Opcode = V.getOpcode();
3174 switch (Opcode) {
3175 default: {
3176 APInt UndefElts;
3177 // Since the number of lanes in a scalable vector is unknown at compile time,
3178 // we track one bit which is implicitly broadcast to all lanes. This means
3179 // that all lanes in a scalable vector are considered demanded.
3180 APInt DemandedElts
3182
3183 if (isSplatValue(V, DemandedElts, UndefElts)) {
3184 if (VT.isScalableVector()) {
3185 // DemandedElts and UndefElts are ignored for scalable vectors, since
3186 // the only supported cases are SPLAT_VECTOR nodes.
3187 SplatIdx = 0;
3188 } else {
3189 // Handle case where all demanded elements are UNDEF.
3190 if (DemandedElts.isSubsetOf(UndefElts)) {
3191 SplatIdx = 0;
3192 return getUNDEF(VT);
3193 }
3194 SplatIdx = (UndefElts & DemandedElts).countr_one();
3195 }
3196 return V;
3197 }
3198 break;
3199 }
3200 case ISD::SPLAT_VECTOR:
3201 SplatIdx = 0;
3202 return V;
3203 case ISD::VECTOR_SHUFFLE: {
3204 assert(!VT.isScalableVector());
3205 // Check if this is a shuffle node doing a splat.
3206 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3207 // getTargetVShiftNode currently struggles without the splat source.
3208 auto *SVN = cast<ShuffleVectorSDNode>(V);
3209 if (!SVN->isSplat())
3210 break;
3211 int Idx = SVN->getSplatIndex();
3212 int NumElts = V.getValueType().getVectorNumElements();
3213 SplatIdx = Idx % NumElts;
3214 return V.getOperand(Idx / NumElts);
3215 }
3216 }
3217
3218 return SDValue();
3219}
3220
3222 int SplatIdx;
3223 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3224 EVT SVT = SrcVector.getValueType().getScalarType();
3225 EVT LegalSVT = SVT;
3226 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3227 if (!SVT.isInteger())
3228 return SDValue();
3229 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3230 if (LegalSVT.bitsLT(SVT))
3231 return SDValue();
3232 }
3233 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3234 }
3235 return SDValue();
3236}
3237
3238std::optional<ConstantRange>
3240 unsigned Depth) const {
3241 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3242 V.getOpcode() == ISD::SRA) &&
3243 "Unknown shift node");
3244 // Shifting more than the bitwidth is not valid.
3245 unsigned BitWidth = V.getScalarValueSizeInBits();
3246
3247 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3248 const APInt &ShAmt = Cst->getAPIntValue();
3249 if (ShAmt.uge(BitWidth))
3250 return std::nullopt;
3251 return ConstantRange(ShAmt);
3252 }
3253
3254 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3255 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3256 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3257 if (!DemandedElts[i])
3258 continue;
3259 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3260 if (!SA) {
3261 MinAmt = MaxAmt = nullptr;
3262 break;
3263 }
3264 const APInt &ShAmt = SA->getAPIntValue();
3265 if (ShAmt.uge(BitWidth))
3266 return std::nullopt;
3267 if (!MinAmt || MinAmt->ugt(ShAmt))
3268 MinAmt = &ShAmt;
3269 if (!MaxAmt || MaxAmt->ult(ShAmt))
3270 MaxAmt = &ShAmt;
3271 }
3272 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3273 "Failed to find matching min/max shift amounts");
3274 if (MinAmt && MaxAmt)
3275 return ConstantRange(*MinAmt, *MaxAmt + 1);
3276 }
3277
3278 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3279 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3280 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3281 if (KnownAmt.getMaxValue().ult(BitWidth))
3282 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3283
3284 return std::nullopt;
3285}
3286
3287std::optional<unsigned>
3289 unsigned Depth) const {
3290 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3291 V.getOpcode() == ISD::SRA) &&
3292 "Unknown shift node");
3293 if (std::optional<ConstantRange> AmtRange =
3294 getValidShiftAmountRange(V, DemandedElts, Depth))
3295 if (const APInt *ShAmt = AmtRange->getSingleElement())
3296 return ShAmt->getZExtValue();
3297 return std::nullopt;
3298}
3299
3300std::optional<unsigned>
3302 APInt DemandedElts = getDemandAllEltsMask(V);
3303 return getValidShiftAmount(V, DemandedElts, Depth);
3304}
3305
3306std::optional<unsigned>
3308 unsigned Depth) const {
3309 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3310 V.getOpcode() == ISD::SRA) &&
3311 "Unknown shift node");
3312 if (std::optional<ConstantRange> AmtRange =
3313 getValidShiftAmountRange(V, DemandedElts, Depth))
3314 return AmtRange->getUnsignedMin().getZExtValue();
3315 return std::nullopt;
3316}
3317
3318std::optional<unsigned>
3320 APInt DemandedElts = getDemandAllEltsMask(V);
3321 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3322}
3323
3324std::optional<unsigned>
3326 unsigned Depth) const {
3327 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3328 V.getOpcode() == ISD::SRA) &&
3329 "Unknown shift node");
3330 if (std::optional<ConstantRange> AmtRange =
3331 getValidShiftAmountRange(V, DemandedElts, Depth))
3332 return AmtRange->getUnsignedMax().getZExtValue();
3333 return std::nullopt;
3334}
3335
3336std::optional<unsigned>
3338 APInt DemandedElts = getDemandAllEltsMask(V);
3339 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3340}
3341
3342/// Determine which bits of Op are known to be either zero or one and return
3343/// them in Known. For vectors, the known bits are those that are shared by
3344/// every vector element.
3346 APInt DemandedElts = getDemandAllEltsMask(Op);
3347 return computeKnownBits(Op, DemandedElts, Depth);
3348}
3349
3350/// Determine which bits of Op are known to be either zero or one and return
3351/// them in Known. The DemandedElts argument allows us to only collect the known
3352/// bits that are shared by the requested vector elements.
3354 unsigned Depth) const {
3355 unsigned BitWidth = Op.getScalarValueSizeInBits();
3356
3357 KnownBits Known(BitWidth); // Don't know anything.
3358
3359 if (auto OptAPInt = Op->bitcastToAPInt()) {
3360 // We know all of the bits for a constant!
3361 APInt V = *std::move(OptAPInt);
3362
3363 // Swap the low-order and high-order double of a ppc_fp128 when casting to
3364 // i128, see #44482.
3365 //
3366 // A ppc_fp128 is two doubles, with the high-order double stored at the
3367 // lower address. Reading that as an integer therefore puts the high-order
3368 // double in the high 64 bits on big-endian targets and in the low 64 bits
3369 // on little-endian targets.
3370 //
3371 // But APFloat::bitcastToAPInt is endianness-agnostic and always places the
3372 // high-order double in the low 64 bits. Hence the two doubles must be
3373 // flipped on big-endian targets.
3374 if (getDataLayout().isBigEndian() && Op.getValueType() == MVT::ppcf128)
3375 V = V.rotl(64);
3376
3377 return KnownBits::makeConstant(V);
3378 }
3379
3380 if (Depth >= MaxRecursionDepth)
3381 return Known; // Limit search depth.
3382
3383 KnownBits Known2;
3384 unsigned NumElts = DemandedElts.getBitWidth();
3385 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3386 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3387 assert((!Op.getValueType().isFixedLengthVector() ||
3388 NumElts == Op.getValueType().getVectorNumElements()) &&
3389 "Unexpected vector size");
3390
3391 if (!DemandedElts)
3392 return Known; // No demanded elts, better to assume we don't know anything.
3393
3394 unsigned Opcode = Op.getOpcode();
3395 switch (Opcode) {
3396 case ISD::FREEZE: {
3397 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3399 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3400 break;
3401 }
3402 case ISD::MERGE_VALUES:
3403 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3404 Depth + 1);
3405 case ISD::SPLAT_VECTOR: {
3406 SDValue SrcOp = Op.getOperand(0);
3407 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3408 "Expected SPLAT_VECTOR implicit truncation");
3409 // Implicitly truncate the bits to match the official semantics of
3410 // SPLAT_VECTOR.
3412 break;
3413 }
3415 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3416 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3417 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3418 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3419 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3420 }
3421 break;
3422 }
3423 case ISD::STEP_VECTOR: {
3424 const APInt &Step = Op.getConstantOperandAPInt(0);
3425
3426 if (Step.isPowerOf2())
3427 Known.Zero.setLowBits(Step.logBase2());
3428
3430
3431 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3432 break;
3433 const APInt MinNumElts =
3434 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3435
3436 bool Overflow;
3437 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3439 .umul_ov(MinNumElts, Overflow);
3440 if (Overflow)
3441 break;
3442
3443 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3444 if (Overflow)
3445 break;
3446
3447 Known.Zero.setHighBits(MaxValue.countl_zero());
3448 break;
3449 }
3450 case ISD::BUILD_VECTOR:
3451 assert(!Op.getValueType().isScalableVector());
3452 // Collect the known bits that are shared by every demanded vector element.
3453 Known.setAllConflict();
3454 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3455 if (!DemandedElts[i])
3456 continue;
3457
3458 SDValue SrcOp = Op.getOperand(i);
3459 if (SrcOp.getOpcode() == ISD::POISON)
3460 continue;
3461
3462 Known2 = computeKnownBits(SrcOp, Depth + 1);
3463
3464 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3465 if (SrcOp.getValueSizeInBits() != BitWidth) {
3466 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3467 "Expected BUILD_VECTOR implicit truncation");
3468 Known2 = Known2.trunc(BitWidth);
3469 }
3470
3471 // Known bits are the values that are shared by every demanded element.
3472 Known = Known.intersectWith(Known2);
3473
3474 // If we don't know any bits, early out.
3475 if (Known.isUnknown())
3476 break;
3477 }
3478
3479 // If every demanded element was poison, we know nothing.
3480 if (Known.hasConflict())
3481 Known.resetAll();
3482 break;
3483 case ISD::VECTOR_COMPRESS: {
3484 SDValue Vec = Op.getOperand(0);
3485 SDValue PassThru = Op.getOperand(2);
3486 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3487 // If we don't know any bits, early out.
3488 if (Known.isUnknown())
3489 break;
3490 Known2 = computeKnownBits(Vec, Depth + 1);
3491 Known = Known.intersectWith(Known2);
3492 break;
3493 }
3494 case ISD::VECTOR_SHUFFLE: {
3495 assert(!Op.getValueType().isScalableVector());
3496 // Collect the known bits that are shared by every vector element referenced
3497 // by the shuffle.
3498 APInt DemandedLHS, DemandedRHS;
3500 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3501 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3502 DemandedLHS, DemandedRHS))
3503 break;
3504
3505 // Known bits are the values that are shared by every demanded element.
3506 Known.setAllConflict();
3507 if (!!DemandedLHS) {
3508 SDValue LHS = Op.getOperand(0);
3509 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3510 Known = Known.intersectWith(Known2);
3511 }
3512 // If we don't know any bits, early out.
3513 if (Known.isUnknown())
3514 break;
3515 if (!!DemandedRHS) {
3516 SDValue RHS = Op.getOperand(1);
3517 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3518 Known = Known.intersectWith(Known2);
3519 }
3520 break;
3521 }
3522 case ISD::VSCALE: {
3524 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3526 break;
3527 }
3528 case ISD::CONCAT_VECTORS: {
3529 if (Op.getValueType().isScalableVector())
3530 break;
3531 // Split DemandedElts and test each of the demanded subvectors.
3532 Known.setAllConflict();
3533 EVT SubVectorVT = Op.getOperand(0).getValueType();
3534 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3535 unsigned NumSubVectors = Op.getNumOperands();
3536 for (unsigned i = 0; i != NumSubVectors; ++i) {
3537 APInt DemandedSub =
3538 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3539 if (!!DemandedSub) {
3540 SDValue Sub = Op.getOperand(i);
3541 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3542 Known = Known.intersectWith(Known2);
3543 }
3544 // If we don't know any bits, early out.
3545 if (Known.isUnknown())
3546 break;
3547 }
3548 break;
3549 }
3550 case ISD::INSERT_SUBVECTOR: {
3551 if (Op.getValueType().isScalableVector())
3552 break;
3553 // Demand any elements from the subvector and the remainder from the src its
3554 // inserted into.
3555 SDValue Src = Op.getOperand(0);
3556 SDValue Sub = Op.getOperand(1);
3557 uint64_t Idx = Op.getConstantOperandVal(2);
3558 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3559 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3560 APInt DemandedSrcElts = DemandedElts;
3561 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3562
3563 Known.setAllConflict();
3564 if (!!DemandedSubElts) {
3565 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3566 if (Known.isUnknown())
3567 break; // early-out.
3568 }
3569 if (!!DemandedSrcElts) {
3570 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3571 Known = Known.intersectWith(Known2);
3572 }
3573 break;
3574 }
3576 // Offset the demanded elts by the subvector index.
3577 SDValue Src = Op.getOperand(0);
3578
3579 APInt DemandedSrcElts;
3580 if (Src.getValueType().isScalableVector())
3581 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3582 else {
3583 uint64_t Idx = Op.getConstantOperandVal(1);
3584 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3585 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3586 }
3587 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3588 break;
3589 }
3590 case ISD::SCALAR_TO_VECTOR: {
3591 if (Op.getValueType().isScalableVector())
3592 break;
3593 // We know about scalar_to_vector as much as we know about it source,
3594 // which becomes the first element of otherwise unknown vector.
3595 if (DemandedElts != 1)
3596 break;
3597
3598 SDValue N0 = Op.getOperand(0);
3599 Known = computeKnownBits(N0, Depth + 1);
3600 if (N0.getValueSizeInBits() != BitWidth)
3601 Known = Known.trunc(BitWidth);
3602
3603 break;
3604 }
3605 case ISD::BITCAST: {
3606 if (Op.getValueType().isScalableVector())
3607 break;
3608
3609 SDValue N0 = Op.getOperand(0);
3610 EVT SubVT = N0.getValueType();
3611 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3612
3613 // Ignore bitcasts from unsupported types.
3614 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3615 break;
3616
3617 // Fast handling of 'identity' bitcasts.
3618 if (BitWidth == SubBitWidth) {
3619 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3620 break;
3621 }
3622
3623 bool IsLE = getDataLayout().isLittleEndian();
3624
3625 // Bitcast 'small element' vector to 'large element' scalar/vector.
3626 if ((BitWidth % SubBitWidth) == 0) {
3627 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3628
3629 // Collect known bits for the (larger) output by collecting the known
3630 // bits from each set of sub elements and shift these into place.
3631 // We need to separately call computeKnownBits for each set of
3632 // sub elements as the knownbits for each is likely to be different.
3633 unsigned SubScale = BitWidth / SubBitWidth;
3634 APInt SubDemandedElts(NumElts * SubScale, 0);
3635 for (unsigned i = 0; i != NumElts; ++i)
3636 if (DemandedElts[i])
3637 SubDemandedElts.setBit(i * SubScale);
3638
3639 for (unsigned i = 0; i != SubScale; ++i) {
3640 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3641 Depth + 1);
3642 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3643 Known.insertBits(Known2, SubBitWidth * Shifts);
3644 }
3645 }
3646
3647 // Bitcast 'large element' scalar/vector to 'small element' vector.
3648 if ((SubBitWidth % BitWidth) == 0) {
3649 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3650
3651 // Collect known bits for the (smaller) output by collecting the known
3652 // bits from the overlapping larger input elements and extracting the
3653 // sub sections we actually care about.
3654 unsigned SubScale = SubBitWidth / BitWidth;
3655 APInt SubDemandedElts =
3656 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3657 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3658
3659 Known.setAllConflict();
3660 for (unsigned i = 0; i != NumElts; ++i)
3661 if (DemandedElts[i]) {
3662 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3663 unsigned Offset = (Shifts % SubScale) * BitWidth;
3664 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3665 // If we don't know any bits, early out.
3666 if (Known.isUnknown())
3667 break;
3668 }
3669 }
3670 break;
3671 }
3672 case ISD::AND:
3673 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3674 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3675
3676 Known &= Known2;
3677 break;
3678 case ISD::OR:
3679 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3680 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3681
3682 Known |= Known2;
3683 break;
3684 case ISD::XOR:
3685 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3686 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3687
3688 Known ^= Known2;
3689 break;
3690 case ISD::MUL: {
3691 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3692 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3693 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3694 // TODO: SelfMultiply can be poison, but not undef.
3695 if (SelfMultiply)
3696 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3697 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3698 Depth + 1);
3699 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3700
3701 // If the multiplication is known not to overflow, the product of a number
3702 // with itself is non-negative. Only do this if we didn't already computed
3703 // the opposite value for the sign bit.
3704 if (Op->getFlags().hasNoSignedWrap() &&
3705 Op.getOperand(0) == Op.getOperand(1) &&
3706 !Known.isNegative())
3707 Known.makeNonNegative();
3708 break;
3709 }
3710 case ISD::MULHU: {
3711 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3712 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3713 Known = KnownBits::mulhu(Known, Known2);
3714 break;
3715 }
3716 case ISD::MULHS: {
3717 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3718 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3719 Known = KnownBits::mulhs(Known, Known2);
3720 break;
3721 }
3722 case ISD::ABDU: {
3723 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3724 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3725 Known = KnownBits::abdu(Known, Known2);
3726 break;
3727 }
3728 case ISD::ABDS: {
3729 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3730 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3731 Known = KnownBits::abds(Known, Known2);
3732 unsigned SignBits1 =
3733 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3734 if (SignBits1 == 1)
3735 break;
3736 unsigned SignBits0 =
3737 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3738 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3739 break;
3740 }
3741 case ISD::UMUL_LOHI: {
3742 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3743 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3744 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3745 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3746 if (Op.getResNo() == 0)
3747 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3748 else
3749 Known = KnownBits::mulhu(Known, Known2);
3750 break;
3751 }
3752 case ISD::SMUL_LOHI: {
3753 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3754 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3755 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3756 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3757 if (Op.getResNo() == 0)
3758 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3759 else
3760 Known = KnownBits::mulhs(Known, Known2);
3761 break;
3762 }
3763 case ISD::AVGFLOORU: {
3764 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3765 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3766 Known = KnownBits::avgFloorU(Known, Known2);
3767 break;
3768 }
3769 case ISD::AVGCEILU: {
3770 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3771 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3772 Known = KnownBits::avgCeilU(Known, Known2);
3773 break;
3774 }
3775 case ISD::AVGFLOORS: {
3776 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3777 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3778 Known = KnownBits::avgFloorS(Known, Known2);
3779 break;
3780 }
3781 case ISD::AVGCEILS: {
3782 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3783 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3784 Known = KnownBits::avgCeilS(Known, Known2);
3785 break;
3786 }
3787 case ISD::AVGSUBFLOORU:
3788 case ISD::AVGSUBFLOORS: {
3789 bool IsSigned = Op.getOpcode() == ISD::AVGSUBFLOORS;
3790 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3791 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3792 // Subtract in i[N+1] so the difference can't overflow, then halve.
3793 Known = IsSigned ? Known.sext(BitWidth + 1) : Known.zext(BitWidth + 1);
3794 Known2 = IsSigned ? Known2.sext(BitWidth + 1) : Known2.zext(BitWidth + 1);
3795 Known = KnownBits::sub(Known, Known2);
3796 // The shifted in top bit is unknown, but it is truncated away.
3797 Known >>= 1;
3798 Known = Known.trunc(BitWidth);
3799 break;
3800 }
3801 case ISD::SELECT:
3802 case ISD::VSELECT:
3803 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3804 // If we don't know any bits, early out.
3805 if (Known.isUnknown())
3806 break;
3807 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3808
3809 // Only known if known in both the LHS and RHS.
3810 Known = Known.intersectWith(Known2);
3811 break;
3812 case ISD::SELECT_CC:
3813 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3814 // If we don't know any bits, early out.
3815 if (Known.isUnknown())
3816 break;
3817 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3818
3819 // Only known if known in both the LHS and RHS.
3820 Known = Known.intersectWith(Known2);
3821 break;
3822 case ISD::SMULO:
3823 case ISD::UMULO:
3824 if (Op.getResNo() != 1)
3825 break;
3826 // The boolean result conforms to getBooleanContents.
3827 // If we know the result of a setcc has the top bits zero, use this info.
3828 // We know that we have an integer-based boolean since these operations
3829 // are only available for integer.
3830 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3832 BitWidth > 1)
3833 Known.Zero.setBitsFrom(1);
3834 break;
3835 case ISD::SETCC:
3836 case ISD::SETCCCARRY:
3837 case ISD::STRICT_FSETCC:
3838 case ISD::STRICT_FSETCCS: {
3839 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3840 // If we know the result of a setcc has the top bits zero, use this info.
3841 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3843 BitWidth > 1)
3844 Known.Zero.setBitsFrom(1);
3845 break;
3846 }
3847 case ISD::SHL: {
3848 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3849 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3850
3851 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3852 bool NSW = Op->getFlags().hasNoSignedWrap();
3853
3854 bool ShAmtNonZero = Known2.isNonZero();
3855
3856 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3857
3858 // Minimum shift low bits are known zero.
3859 if (std::optional<unsigned> ShMinAmt =
3860 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3861 Known.Zero.setLowBits(*ShMinAmt);
3862 break;
3863 }
3864 case ISD::SRL:
3865 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3866 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3867 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3868 Op->getFlags().hasExact());
3869
3870 // Minimum shift high bits are known zero.
3871 if (std::optional<unsigned> ShMinAmt =
3872 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3873 Known.Zero.setHighBits(*ShMinAmt);
3874 break;
3875 case ISD::SRA:
3876 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3877 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3878 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3879 Op->getFlags().hasExact());
3880 break;
3881 case ISD::ROTL:
3882 case ISD::ROTR:
3883 if (ConstantSDNode *C =
3884 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3885 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3886
3887 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3888
3889 // Canonicalize to ROTR.
3890 if (Opcode == ISD::ROTL && Amt != 0)
3891 Amt = BitWidth - Amt;
3892
3893 Known.Zero = Known.Zero.rotr(Amt);
3894 Known.One = Known.One.rotr(Amt);
3895 }
3896 break;
3897 case ISD::FSHL:
3898 case ISD::FSHR:
3899 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3900 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3901
3902 // For fshl, 0-shift returns the 1st arg.
3903 // For fshr, 0-shift returns the 2nd arg.
3904 if (Amt == 0) {
3905 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3906 DemandedElts, Depth + 1);
3907 break;
3908 }
3909
3910 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3911 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3912 const APInt ShAmt(BitWidth, Amt);
3913 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3914 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3915 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3916 : KnownBits::fshr(Known, Known2, ShAmt);
3917 }
3918 break;
3919 case ISD::SHL_PARTS:
3920 case ISD::SRA_PARTS:
3921 case ISD::SRL_PARTS: {
3922 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3923
3924 // Collect lo/hi source values and concatenate.
3925 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3926 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3927 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3928 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3929 Known = Known2.concat(Known);
3930
3931 // Collect shift amount.
3932 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3933
3934 if (Opcode == ISD::SHL_PARTS)
3935 Known = KnownBits::shl(Known, Known2);
3936 else if (Opcode == ISD::SRA_PARTS)
3937 Known = KnownBits::ashr(Known, Known2);
3938 else // if (Opcode == ISD::SRL_PARTS)
3939 Known = KnownBits::lshr(Known, Known2);
3940
3941 // TODO: Minimum shift low/high bits are known zero.
3942
3943 if (Op.getResNo() == 0)
3944 Known = Known.extractBits(LoBits, 0);
3945 else
3946 Known = Known.extractBits(HiBits, LoBits);
3947 break;
3948 }
3950 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3951 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3952 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3953 break;
3954 }
3955 case ISD::CTTZ:
3956 case ISD::CTTZ_ZERO_POISON: {
3957 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3958 // If we have a known 1, its position is our upper bound.
3959 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3960 unsigned LowBits = llvm::bit_width(PossibleTZ);
3961 Known.Zero.setBitsFrom(LowBits);
3962 break;
3963 }
3964 case ISD::CTLZ:
3965 case ISD::CTLZ_ZERO_POISON: {
3966 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3967 // If we have a known 1, its position is our upper bound.
3968 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3969 unsigned LowBits = llvm::bit_width(PossibleLZ);
3970 Known.Zero.setBitsFrom(LowBits);
3971 break;
3972 }
3973 case ISD::CTLS: {
3974 unsigned MinRedundantSignBits =
3975 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3976 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3978 Known = Range.toKnownBits();
3979 break;
3980 }
3981 case ISD::CTPOP: {
3982 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3983 // If we know some of the bits are zero, they can't be one.
3984 unsigned PossibleOnes = Known2.countMaxPopulation();
3985 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3986 break;
3987 }
3988 case ISD::PARITY: {
3989 // Parity returns 0 everywhere but the LSB.
3990 Known.Zero.setBitsFrom(1);
3991 break;
3992 }
3993 case ISD::PDEP: {
3994 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3995 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3996 Known = KnownBits::pdep(Known2, Known);
3997 break;
3998 }
3999 case ISD::PEXT: {
4000 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4001 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4002 Known = KnownBits::pext(Known2, Known);
4003 break;
4004 }
4005 case ISD::CLMUL: {
4006 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4007 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4008 Known = KnownBits::clmul(Known, Known2);
4009 break;
4010 }
4011 case ISD::MGATHER:
4012 case ISD::MLOAD: {
4013 ISD::LoadExtType ETy =
4014 (Opcode == ISD::MGATHER)
4015 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
4016 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
4017 if (ETy == ISD::ZEXTLOAD) {
4018 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
4019 KnownBits Known0(MemVT.getScalarSizeInBits());
4020 return Known0.zext(BitWidth);
4021 }
4022 break;
4023 }
4024 case ISD::LOAD: {
4026 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4027 if (ISD::isNON_EXTLoad(LD) && Cst) {
4028 // Determine any common known bits from the loaded constant pool value.
4029 Type *CstTy = Cst->getType();
4030 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4031 !Op.getValueType().isScalableVector()) {
4032 // If its a vector splat, then we can (quickly) reuse the scalar path.
4033 // NOTE: We assume all elements match and none are UNDEF.
4034 if (CstTy->isVectorTy()) {
4035 if (const Constant *Splat = Cst->getSplatValue()) {
4036 Cst = Splat;
4037 CstTy = Cst->getType();
4038 }
4039 }
4040 // TODO - do we need to handle different bitwidths?
4041 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4042 // Iterate across all vector elements finding common known bits.
4043 Known.setAllConflict();
4044 for (unsigned i = 0; i != NumElts; ++i) {
4045 if (!DemandedElts[i])
4046 continue;
4047 if (Constant *Elt = Cst->getAggregateElement(i)) {
4048 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4049 const APInt &Value = CInt->getValue();
4050 Known.One &= Value;
4051 Known.Zero &= ~Value;
4052 continue;
4053 }
4054 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4055 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4056 Known.One &= Value;
4057 Known.Zero &= ~Value;
4058 continue;
4059 }
4060 }
4061 Known.One.clearAllBits();
4062 Known.Zero.clearAllBits();
4063 break;
4064 }
4065 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4066 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4067 Known = KnownBits::makeConstant(CInt->getValue());
4068 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4069 Known =
4070 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4071 }
4072 }
4073 }
4074 } else if (Op.getResNo() == 0) {
4075 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4076 KnownBits KnownScalarMemory(ScalarMemorySize);
4077 if (const MDNode *MD = LD->getRanges())
4078 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4079
4080 // Extend the Known bits from memory to the size of the scalar result.
4081 if (ISD::isZEXTLoad(Op.getNode()))
4082 Known = KnownScalarMemory.zext(BitWidth);
4083 else if (ISD::isSEXTLoad(Op.getNode()))
4084 Known = KnownScalarMemory.sext(BitWidth);
4085 else if (ISD::isEXTLoad(Op.getNode()))
4086 Known = KnownScalarMemory.anyext(BitWidth);
4087 else
4088 Known = KnownScalarMemory;
4089 assert(Known.getBitWidth() == BitWidth);
4090 return Known;
4091 }
4092 break;
4093 }
4095 if (Op.getValueType().isScalableVector())
4096 break;
4097 EVT InVT = Op.getOperand(0).getValueType();
4098 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4099 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4100 Known = Known.zext(BitWidth);
4101 break;
4102 }
4103 case ISD::ZERO_EXTEND: {
4104 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4105 Known = Known.zext(BitWidth);
4106 break;
4107 }
4109 if (Op.getValueType().isScalableVector())
4110 break;
4111 EVT InVT = Op.getOperand(0).getValueType();
4112 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4113 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4114 // If the sign bit is known to be zero or one, then sext will extend
4115 // it to the top bits, else it will just zext.
4116 Known = Known.sext(BitWidth);
4117 break;
4118 }
4119 case ISD::SIGN_EXTEND: {
4120 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4121 // If the sign bit is known to be zero or one, then sext will extend
4122 // it to the top bits, else it will just zext.
4123 Known = Known.sext(BitWidth);
4124 break;
4125 }
4127 if (Op.getValueType().isScalableVector())
4128 break;
4129 EVT InVT = Op.getOperand(0).getValueType();
4130 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4131 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4132 Known = Known.anyext(BitWidth);
4133 break;
4134 }
4135 case ISD::ANY_EXTEND: {
4136 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4137 Known = Known.anyext(BitWidth);
4138 break;
4139 }
4140 case ISD::TRUNCATE: {
4141 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4142 Known = Known.trunc(BitWidth);
4143 break;
4144 }
4145 case ISD::TRUNCATE_SSAT_S: {
4146 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4147 Known = Known.truncSSat(BitWidth);
4148 break;
4149 }
4150 case ISD::TRUNCATE_SSAT_U: {
4151 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4152 Known = Known.truncSSatU(BitWidth);
4153 break;
4154 }
4155 case ISD::TRUNCATE_USAT_U: {
4156 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4157 Known = Known.truncUSat(BitWidth);
4158 break;
4159 }
4160 case ISD::AssertZext: {
4161 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4163 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4164 Known.Zero |= (~InMask);
4165 Known.One &= (~Known.Zero);
4166 break;
4167 }
4168 case ISD::AssertAlign: {
4169 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4170 assert(LogOfAlign != 0);
4171
4172 // TODO: Should use maximum with source
4173 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4174 // well as clearing one bits.
4175 Known.Zero.setLowBits(LogOfAlign);
4176 Known.One.clearLowBits(LogOfAlign);
4177 break;
4178 }
4179 case ISD::AssertNoFPClass: {
4180 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4181
4182 FPClassTest NoFPClass =
4183 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4184 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4185 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4186 // Cannot be negative.
4187 Known.makeNonNegative();
4188 }
4189
4190 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4191 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4192 // Cannot be positive.
4193 Known.makeNegative();
4194 }
4195
4196 break;
4197 }
4198 case ISD::FABS:
4199 // fabs clears the sign bit
4200 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4201 Known.Zero.setSignBit();
4202 Known.One.clearSignBit();
4203 break;
4204 case ISD::FGETSIGN:
4205 // All bits are zero except the low bit.
4206 Known.Zero.setBitsFrom(1);
4207 break;
4208 case ISD::ADD: {
4209 SDNodeFlags Flags = Op.getNode()->getFlags();
4210 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4211 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4212 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4214 Op.getOperand(0), DemandedElts,
4216 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4217 Flags.hasNoUnsignedWrap(), SelfAdd);
4218 break;
4219 }
4220 case ISD::SUB: {
4221 SDNodeFlags Flags = Op.getNode()->getFlags();
4222 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4223 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4224 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4225 Flags.hasNoUnsignedWrap());
4226 break;
4227 }
4228 case ISD::USUBO:
4229 case ISD::SSUBO:
4230 case ISD::USUBO_CARRY:
4231 case ISD::SSUBO_CARRY:
4232 if (Op.getResNo() == 1) {
4233 // If we know the result of a setcc has the top bits zero, use this info.
4234 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4236 BitWidth > 1)
4237 Known.Zero.setBitsFrom(1);
4238 break;
4239 }
4240 [[fallthrough]];
4241 case ISD::SUBC: {
4242 assert(Op.getResNo() == 0 &&
4243 "We only compute knownbits for the difference here.");
4244
4245 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4246 KnownBits Borrow(1);
4247 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4248 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4249 // Borrow has bit width 1
4250 Borrow = Borrow.trunc(1);
4251 } else {
4252 Borrow.setAllZero();
4253 }
4254
4255 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4256 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4257 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4258 break;
4259 }
4260 case ISD::UADDO:
4261 case ISD::SADDO:
4262 case ISD::UADDO_CARRY:
4263 case ISD::SADDO_CARRY:
4264 if (Op.getResNo() == 1) {
4265 // If we know the result of a setcc has the top bits zero, use this info.
4266 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4268 BitWidth > 1)
4269 Known.Zero.setBitsFrom(1);
4270 break;
4271 }
4272 [[fallthrough]];
4273 case ISD::ADDC:
4274 case ISD::ADDE: {
4275 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4276
4277 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4278 KnownBits Carry(1);
4279 if (Opcode == ISD::ADDE)
4280 // Can't track carry from glue, set carry to unknown.
4281 Carry.resetAll();
4282 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4283 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4284 // Carry has bit width 1
4285 Carry = Carry.trunc(1);
4286 } else {
4287 Carry.setAllZero();
4288 }
4289
4290 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4291 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4292 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4293 break;
4294 }
4295 case ISD::UDIV: {
4296 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4297 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4298 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4299 break;
4300 }
4301 case ISD::SDIV: {
4302 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4303 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4304 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4305 break;
4306 }
4307 case ISD::SREM: {
4308 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4309 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4310 Known = KnownBits::srem(Known, Known2);
4311 break;
4312 }
4313 case ISD::UREM: {
4314 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4315 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4316 Known = KnownBits::urem(Known, Known2);
4317 break;
4318 }
4319 case ISD::EXTRACT_ELEMENT: {
4320 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4321 const unsigned Index = Op.getConstantOperandVal(1);
4322 const unsigned EltBitWidth = Op.getValueSizeInBits();
4323
4324 Known = Known.extractBits(EltBitWidth, Index * EltBitWidth);
4325 break;
4326 }
4328 SDValue InVec = Op.getOperand(0);
4329 SDValue EltNo = Op.getOperand(1);
4330 EVT VecVT = InVec.getValueType();
4331 // computeKnownBits not yet implemented for scalable vectors.
4332 if (VecVT.isScalableVector())
4333 break;
4334 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4335 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4336
4337 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4338 // anything about the extended bits.
4339 if (BitWidth > EltBitWidth)
4340 Known = Known.trunc(EltBitWidth);
4341
4342 // If we know the element index, just demand that vector element, else for
4343 // an unknown element index, ignore DemandedElts and demand them all.
4344 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4345 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4346 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4347 DemandedSrcElts =
4348 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4349
4350 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4351 if (BitWidth > EltBitWidth)
4352 Known = Known.anyext(BitWidth);
4353 break;
4354 }
4355 case ISD::BUILD_PAIR: {
4356 // Operand 0 is the low half and operand 1 the high half,
4357 // KnownBits::concat places its argument in the low bits.
4358 Known = computeKnownBits(Op.getOperand(0), Depth + 1);
4359 Known2 = computeKnownBits(Op.getOperand(1), Depth + 1);
4360 Known = Known2.concat(Known);
4361 break;
4362 }
4364 if (Op.getValueType().isScalableVector())
4365 break;
4366
4367 // If we know the element index, split the demand between the
4368 // source vector and the inserted element, otherwise assume we need
4369 // the original demanded vector elements and the value.
4370 SDValue InVec = Op.getOperand(0);
4371 SDValue InVal = Op.getOperand(1);
4372 SDValue EltNo = Op.getOperand(2);
4373 bool DemandedVal = true;
4374 APInt DemandedVecElts = DemandedElts;
4375 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4376 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4377 unsigned EltIdx = CEltNo->getZExtValue();
4378 DemandedVal = !!DemandedElts[EltIdx];
4379 DemandedVecElts.clearBit(EltIdx);
4380 }
4381 Known.setAllConflict();
4382 if (DemandedVal) {
4383 Known2 = computeKnownBits(InVal, Depth + 1);
4384 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4385 }
4386 if (!!DemandedVecElts) {
4387 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4388 Known = Known.intersectWith(Known2);
4389 }
4390 break;
4391 }
4392 case ISD::BITREVERSE: {
4393 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4394 Known = Known2.reverseBits();
4395 break;
4396 }
4397 case ISD::BSWAP: {
4398 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4399 Known = Known2.byteSwap();
4400 break;
4401 }
4402 case ISD::ABS:
4403 case ISD::ABS_MIN_POISON: {
4404 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4405 Known = Known2.abs();
4406 Known.Zero.setHighBits(
4407 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4408 break;
4409 }
4410 case ISD::USUBSAT: {
4411 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4412 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4413 Known = KnownBits::usub_sat(Known, Known2);
4414 break;
4415 }
4416 case ISD::UMIN: {
4417 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4418 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4419 Known = KnownBits::umin(Known, Known2);
4420 break;
4421 }
4422 case ISD::UMAX: {
4423 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4424 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4425 Known = KnownBits::umax(Known, Known2);
4426 break;
4427 }
4428 case ISD::SMIN:
4429 case ISD::SMAX: {
4430 // If we have a clamp pattern, we know that the number of sign bits will be
4431 // the minimum of the clamp min/max range.
4432 bool IsMax = (Opcode == ISD::SMAX);
4433 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4434 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4435 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4436 CstHigh =
4437 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4438 if (CstLow && CstHigh) {
4439 if (!IsMax)
4440 std::swap(CstLow, CstHigh);
4441
4442 const APInt &ValueLow = CstLow->getAPIntValue();
4443 const APInt &ValueHigh = CstHigh->getAPIntValue();
4444 if (ValueLow.sle(ValueHigh)) {
4445 unsigned LowSignBits = ValueLow.getNumSignBits();
4446 unsigned HighSignBits = ValueHigh.getNumSignBits();
4447 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4448 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4449 Known.One.setHighBits(MinSignBits);
4450 break;
4451 }
4452 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4453 Known.Zero.setHighBits(MinSignBits);
4454 break;
4455 }
4456 }
4457 }
4458
4459 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4460 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4461 if (IsMax)
4462 Known = KnownBits::smax(Known, Known2);
4463 else
4464 Known = KnownBits::smin(Known, Known2);
4465
4466 // For SMAX, if CstLow is non-negative we know the result will be
4467 // non-negative and thus all sign bits are 0.
4468 // TODO: There's an equivalent of this for smin with negative constant for
4469 // known ones.
4470 if (IsMax && CstLow) {
4471 const APInt &ValueLow = CstLow->getAPIntValue();
4472 if (ValueLow.isNonNegative()) {
4473 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4474 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4475 }
4476 }
4477
4478 break;
4479 }
4480 case ISD::UINT_TO_FP: {
4481 Known.makeNonNegative();
4482 break;
4483 }
4484 case ISD::SINT_TO_FP: {
4485 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4486 if (Known2.isNonNegative())
4487 Known.makeNonNegative();
4488 else if (Known2.isNegative())
4489 Known.makeNegative();
4490 break;
4491 }
4492 case ISD::FP_TO_UINT_SAT: {
4493 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4494 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4496 break;
4497 }
4498 case ISD::ATOMIC_LOAD: {
4499 // If we are looking at the loaded value.
4500 if (Op.getResNo() == 0) {
4501 auto *AT = cast<AtomicSDNode>(Op);
4502 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4503 KnownBits KnownScalarMemory(ScalarMemorySize);
4504 if (const MDNode *MD = AT->getRanges())
4505 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4506
4507 switch (AT->getExtensionType()) {
4508 case ISD::ZEXTLOAD:
4509 Known = KnownScalarMemory.zext(BitWidth);
4510 break;
4511 case ISD::SEXTLOAD:
4512 Known = KnownScalarMemory.sext(BitWidth);
4513 break;
4514 case ISD::EXTLOAD:
4515 switch (TLI->getExtendForAtomicOps()) {
4516 case ISD::ZERO_EXTEND:
4517 Known = KnownScalarMemory.zext(BitWidth);
4518 break;
4519 case ISD::SIGN_EXTEND:
4520 Known = KnownScalarMemory.sext(BitWidth);
4521 break;
4522 default:
4523 Known = KnownScalarMemory.anyext(BitWidth);
4524 break;
4525 }
4526 break;
4527 case ISD::NON_EXTLOAD:
4528 Known = KnownScalarMemory;
4529 break;
4530 }
4531 assert(Known.getBitWidth() == BitWidth);
4532 }
4533 break;
4534 }
4536 if (Op.getResNo() == 1) {
4537 // The boolean result conforms to getBooleanContents.
4538 // If we know the result of a setcc has the top bits zero, use this info.
4539 // We know that we have an integer-based boolean since these operations
4540 // are only available for integer.
4541 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4543 BitWidth > 1)
4544 Known.Zero.setBitsFrom(1);
4545 break;
4546 }
4547 [[fallthrough]];
4549 case ISD::ATOMIC_SWAP:
4560 case ISD::ATOMIC_LOAD_UMAX: {
4561 // If we are looking at the loaded value.
4562 if (Op.getResNo() == 0) {
4563 auto *AT = cast<AtomicSDNode>(Op);
4564 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4565
4566 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4567 Known.Zero.setBitsFrom(MemBits);
4568 }
4569 break;
4570 }
4571 case ISD::FrameIndex:
4572 case ISD::TargetFrameIndex: {
4573 const MachineFunction &MF = getMachineFunction();
4574 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4575 TLI->computeKnownBitsForStackObjectPointer(
4576 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4577 break;
4578 }
4579 case ISD::VP_LOAD_FF: {
4580 if (Op.getResNo() != 1)
4581 break;
4582 // The second result of vp.load.ff is an unsigned value that is less than or
4583 // equal to the EVL operand.
4584 KnownBits VLKB =
4585 computeKnownBits(Op.getOperand(3), DemandedElts, Depth + 1);
4586 // The new VL is also bounded by the largest vector length.
4587 EVT ResVT = Op->getValueType(0);
4588 auto ResKB = KnownBits::makeConstant(
4590 if (ResVT.isScalableVector()) {
4592 ResKB = KnownBits::mul(getVScaleRange(&F, BitWidth).toKnownBits(), ResKB);
4593 }
4594 Known.Zero.setHighBits(KnownBits::umin(VLKB, ResKB).countMinLeadingZeros());
4595 break;
4596 }
4597
4598 default:
4599 if (Opcode < ISD::BUILTIN_OP_END)
4600 break;
4601 [[fallthrough]];
4605 // Allow the target to implement this method for its nodes.
4606 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4607 break;
4608 }
4609
4610 return Known;
4611}
4612
4613/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4626
4629 // X + 0 never overflow
4630 if (isNullConstant(N1))
4631 return OFK_Never;
4632
4633 // If both operands each have at least two sign bits, the addition
4634 // cannot overflow.
4635 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4636 return OFK_Never;
4637
4638 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4639 return OFK_Sometime;
4640}
4641
4644 // X + 0 never overflow
4645 if (isNullConstant(N1))
4646 return OFK_Never;
4647
4648 // mulhi + 1 never overflow
4649 KnownBits N1Known = computeKnownBits(N1);
4650 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4651 N1Known.getMaxValue().ult(2))
4652 return OFK_Never;
4653
4654 KnownBits N0Known = computeKnownBits(N0);
4655 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4656 N0Known.getMaxValue().ult(2))
4657 return OFK_Never;
4658
4659 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4660 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4661 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4662 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4663}
4664
4667 // X - 0 never overflow
4668 if (isNullConstant(N1))
4669 return OFK_Never;
4670
4671 // If both operands each have at least two sign bits, the subtraction
4672 // cannot overflow.
4673 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4674 return OFK_Never;
4675
4676 KnownBits N0Known = computeKnownBits(N0);
4677 KnownBits N1Known = computeKnownBits(N1);
4678 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4679 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4680 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4681}
4682
4685 // X - 0 never overflow
4686 if (isNullConstant(N1))
4687 return OFK_Never;
4688
4689 ConstantRange N0Range =
4690 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4691 ConstantRange N1Range =
4692 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4693 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4694}
4695
4698 // X * 0 and X * 1 never overflow.
4699 if (isNullConstant(N1) || isOneConstant(N1))
4700 return OFK_Never;
4701
4704 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4705}
4706
4709 // X * 0 and X * 1 never overflow.
4710 if (isNullConstant(N1) || isOneConstant(N1))
4711 return OFK_Never;
4712
4713 // Get the size of the result.
4714 unsigned BitWidth = N0.getScalarValueSizeInBits();
4715
4716 // Sum of the sign bits.
4717 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4718
4719 // If we have enough sign bits, then there's no overflow.
4720 if (SignBits > BitWidth + 1)
4721 return OFK_Never;
4722
4723 if (SignBits == BitWidth + 1) {
4724 // The overflow occurs when the true multiplication of the
4725 // the operands is the minimum negative number.
4726 KnownBits N0Known = computeKnownBits(N0);
4727 KnownBits N1Known = computeKnownBits(N1);
4728 // If one of the operands is non-negative, then there's no
4729 // overflow.
4730 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4731 return OFK_Never;
4732 }
4733
4734 return OFK_Sometime;
4735}
4736
4738 unsigned Depth) const {
4739 APInt DemandedElts = getDemandAllEltsMask(Op);
4740 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4741}
4742
4744 const APInt &DemandedElts,
4745 bool ForSigned,
4746 unsigned Depth) const {
4747 EVT VT = Op.getValueType();
4748 unsigned BitWidth = VT.getScalarSizeInBits();
4749
4750 if (Depth >= MaxRecursionDepth)
4751 return ConstantRange::getFull(BitWidth);
4752
4753 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4754 return ConstantRange(C->getAPIntValue());
4755
4756 unsigned Opcode = Op.getOpcode();
4757 switch (Opcode) {
4758 case ISD::VSCALE: {
4760 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4761 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4762 }
4763 default:
4764 break;
4765 }
4766
4767 return ConstantRange::getFull(BitWidth);
4768}
4769
4772 unsigned Depth) const {
4773 APInt DemandedElts = getDemandAllEltsMask(Op);
4774 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4775 Depth);
4776}
4777
4779 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4780 unsigned Depth) const {
4781 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4783 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4786 return CR1.intersectWith(CR2, RangeType);
4787}
4788
4790 unsigned Depth) const {
4791 APInt DemandedElts = getDemandAllEltsMask(Val);
4792 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4793}
4794
4796 const APInt &DemandedElts,
4797 bool OrZero, unsigned Depth) const {
4798 if (Depth >= MaxRecursionDepth)
4799 return false; // Limit search depth.
4800
4801 EVT OpVT = Val.getValueType();
4802 unsigned BitWidth = OpVT.getScalarSizeInBits();
4803 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4804 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4805 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4806 assert(
4807 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4808 "Unexpected vector size");
4809
4810 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4811 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4812 return (OrZero && V.isZero()) || V.isPowerOf2();
4813 };
4814
4815 // Is the constant a known power of 2 or zero?
4816 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4817 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4818 return true;
4819
4820 switch (Val.getOpcode()) {
4822 SDValue InVec = Val.getOperand(0);
4823 SDValue EltNo = Val.getOperand(1);
4824 EVT VecVT = InVec.getValueType();
4825
4826 // Skip scalable vectors or implicit extensions.
4827 if (VecVT.isScalableVector() ||
4828 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4829 break;
4830
4831 // If we know the element index, just demand that vector element, else for
4832 // an unknown element index, ignore DemandedElts and demand them all.
4833 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4834 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4835 APInt DemandedSrcElts =
4836 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4837 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4838 : APInt::getAllOnes(NumSrcElts);
4839 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4840 }
4841
4842 case ISD::AND: {
4843 // Looking for `x & -x` pattern:
4844 // If x == 0:
4845 // x & -x -> 0
4846 // If x != 0:
4847 // x & -x -> non-zero pow2
4848 // so if we find the pattern return whether we know `x` is non-zero.
4849 SDValue X, Z;
4850 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4851 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4852 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4853 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4854 break;
4855 }
4856
4857 case ISD::SHL: {
4858 // A left-shift of a constant one will have exactly one bit set because
4859 // shifting the bit off the end is undefined.
4860 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4861 if (C && C->getAPIntValue() == 1)
4862 return true;
4863 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4864 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4865 Depth + 1);
4866 }
4867
4868 case ISD::SRL: {
4869 // A logical right-shift of a constant sign-bit will have exactly
4870 // one bit set.
4871 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4872 if (C && C->getAPIntValue().isSignMask())
4873 return true;
4874 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4875 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4876 Depth + 1);
4877 }
4878
4879 case ISD::TRUNCATE:
4880 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4881 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4882 Depth + 1);
4883
4884 case ISD::ROTL:
4885 case ISD::ROTR:
4886 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4887 Depth + 1);
4888 case ISD::BSWAP:
4889 case ISD::BITREVERSE:
4890 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4891 Depth + 1);
4892
4893 case ISD::SMIN:
4894 case ISD::SMAX:
4895 case ISD::UMIN:
4896 case ISD::UMAX:
4897 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4898 Depth + 1) &&
4899 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4900 Depth + 1);
4901
4902 case ISD::SELECT:
4903 case ISD::VSELECT:
4904 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4905 Depth + 1) &&
4906 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4907 Depth + 1);
4908
4909 case ISD::ZERO_EXTEND:
4910 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4911 Depth + 1);
4912
4913 case ISD::VSCALE:
4914 // vscale(power-of-two) is a power-of-two
4915 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4916 Depth + 1);
4917
4918 case ISD::VECTOR_SHUFFLE: {
4920 // Demanded elements with undef shuffle mask elements are unknown
4921 // - we cannot guarantee they are a power of two, so return false.
4922 APInt DemandedLHS, DemandedRHS;
4924 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4925 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4926 DemandedLHS, DemandedRHS))
4927 return false;
4928
4929 // All demanded elements from LHS must be known power of two.
4930 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4931 OrZero, Depth + 1))
4932 return false;
4933
4934 // All demanded elements from RHS must be known power of two.
4935 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4936 OrZero, Depth + 1))
4937 return false;
4938
4939 return true;
4940 }
4941 }
4942
4943 // More could be done here, though the above checks are enough
4944 // to handle some common cases.
4945 return false;
4946}
4947
4949 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4950 return C1->getValueAPF().getExactLog2Abs() >= 0;
4951
4952 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4953 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4954
4955 return false;
4956}
4957
4959 APInt DemandedElts = getDemandAllEltsMask(Op);
4960 return ComputeNumSignBits(Op, DemandedElts, Depth);
4961}
4962
4963unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4964 unsigned Depth) const {
4965 EVT VT = Op.getValueType();
4966 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4967 unsigned VTBits = VT.getScalarSizeInBits();
4968 unsigned NumElts = DemandedElts.getBitWidth();
4969 unsigned Tmp, Tmp2;
4970 unsigned FirstAnswer = 1;
4971
4972 assert((!VT.isScalableVector() || NumElts == 1) &&
4973 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4974
4975 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4976 const APInt &Val = C->getAPIntValue();
4977 return Val.getNumSignBits();
4978 }
4979
4980 if (Depth >= MaxRecursionDepth)
4981 return 1; // Limit search depth.
4982
4983 if (!DemandedElts)
4984 return 1; // No demanded elts, better to assume we don't know anything.
4985
4986 unsigned Opcode = Op.getOpcode();
4987 switch (Opcode) {
4988 default: break;
4989 case ISD::AssertSext:
4990 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4991 return VTBits-Tmp+1;
4992 case ISD::AssertZext:
4993 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4994 return VTBits-Tmp;
4995 case ISD::FREEZE:
4996 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4998 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4999 break;
5000 case ISD::MERGE_VALUES:
5001 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
5002 Depth + 1);
5003 case ISD::SPLAT_VECTOR: {
5004 // Check if the sign bits of source go down as far as the truncated value.
5005 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
5006 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5007 if (NumSrcSignBits > (NumSrcBits - VTBits))
5008 return NumSrcSignBits - (NumSrcBits - VTBits);
5009 break;
5010 }
5011 case ISD::BUILD_VECTOR:
5012 assert(!VT.isScalableVector());
5013 Tmp = VTBits;
5014 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
5015 if (!DemandedElts[i])
5016 continue;
5017
5018 SDValue SrcOp = Op.getOperand(i);
5019 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
5020 // for constant nodes to ensure we only look at the sign bits.
5022 APInt T = C->getAPIntValue().trunc(VTBits);
5023 Tmp2 = T.getNumSignBits();
5024 } else if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5025 SrcOp.getOperand(0).getScalarValueSizeInBits() >= VTBits) {
5026 // EXTRACT_VECTOR_ELT can extend the value with high bits undefined. If
5027 // this BUILD_VECTOR truncates those undefined bits we can just look
5028 // through the SrcOp and query the vector directly.
5029 SDValue InVec = SrcOp.getOperand(0);
5030 EVT InVecVT = InVec.getValueType();
5031
5032 APInt DemandedSrcElts;
5033 if (InVecVT.isScalableVector())
5034 // Demand all elements.
5035 DemandedSrcElts = APInt(1, 1);
5036 else {
5037 unsigned NumSrcElts = InVecVT.getVectorNumElements();
5038 auto *ConstEltNo = dyn_cast<ConstantSDNode>(SrcOp.getOperand(1));
5039 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5040 DemandedSrcElts =
5041 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5042 else
5043 DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5044 }
5045
5046 Tmp2 = ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5047 unsigned ExtraBits = InVec.getScalarValueSizeInBits() - VTBits;
5048 if (ExtraBits)
5049 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5050 } else {
5051 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
5052
5053 if (SrcOp.getValueSizeInBits() != VTBits) {
5054 assert(SrcOp.getValueSizeInBits() > VTBits &&
5055 "Expected BUILD_VECTOR implicit truncation");
5056 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
5057 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5058 }
5059 }
5060 Tmp = std::min(Tmp, Tmp2);
5061 }
5062 return Tmp;
5063
5064 case ISD::VECTOR_COMPRESS: {
5065 SDValue Vec = Op.getOperand(0);
5066 SDValue PassThru = Op.getOperand(2);
5067 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5068 if (Tmp == 1)
5069 return 1;
5070 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5071 Tmp = std::min(Tmp, Tmp2);
5072 return Tmp;
5073 }
5074
5075 case ISD::VECTOR_SHUFFLE: {
5076 // Collect the minimum number of sign bits that are shared by every vector
5077 // element referenced by the shuffle.
5078 APInt DemandedLHS, DemandedRHS;
5080 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5081 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5082 DemandedLHS, DemandedRHS))
5083 return 1;
5084
5085 Tmp = std::numeric_limits<unsigned>::max();
5086 if (!!DemandedLHS)
5087 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5088 if (!!DemandedRHS) {
5089 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5090 Tmp = std::min(Tmp, Tmp2);
5091 }
5092 // If we don't know anything, early out and try computeKnownBits fall-back.
5093 if (Tmp == 1)
5094 break;
5095 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5096 return Tmp;
5097 }
5098
5099 case ISD::BITCAST: {
5100 if (VT.isScalableVector())
5101 break;
5102 SDValue N0 = Op.getOperand(0);
5103 EVT SrcVT = N0.getValueType();
5104 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5105
5106 // Ignore bitcasts from unsupported types..
5107 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5108 break;
5109
5110 // Fast handling of 'identity' bitcasts.
5111 if (VTBits == SrcBits)
5112 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5113
5114 bool IsLE = getDataLayout().isLittleEndian();
5115
5116 // Bitcast 'large element' scalar/vector to 'small element' vector.
5117 if ((SrcBits % VTBits) == 0) {
5118 assert(VT.isVector() && "Expected bitcast to vector");
5119
5120 unsigned Scale = SrcBits / VTBits;
5121 APInt SrcDemandedElts =
5122 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5123
5124 // Fast case - sign splat can be simply split across the small elements.
5125 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5126 if (Tmp == SrcBits)
5127 return VTBits;
5128
5129 // Slow case - determine how far the sign extends into each sub-element.
5130 Tmp2 = VTBits;
5131 for (unsigned i = 0; i != NumElts; ++i)
5132 if (DemandedElts[i]) {
5133 unsigned SubOffset = i % Scale;
5134 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5135 SubOffset = SubOffset * VTBits;
5136 if (Tmp <= SubOffset)
5137 return 1;
5138 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5139 }
5140 return Tmp2;
5141 }
5142 break;
5143 }
5144
5146 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5147 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5148 return VTBits - Tmp + 1;
5149 case ISD::SIGN_EXTEND:
5150 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5151 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5153 // Max of the input and what this extends.
5154 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5155 Tmp = VTBits-Tmp+1;
5156 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5157 return std::max(Tmp, Tmp2);
5159 if (VT.isScalableVector())
5160 break;
5161 SDValue Src = Op.getOperand(0);
5162 EVT SrcVT = Src.getValueType();
5163 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5164 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5165 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5166 }
5167 case ISD::SRA:
5168 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5169 // SRA X, C -> adds C sign bits.
5170 if (std::optional<unsigned> ShAmt =
5171 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5172 Tmp = std::min(Tmp + *ShAmt, VTBits);
5173 return Tmp;
5174 case ISD::SHL:
5175 if (std::optional<ConstantRange> ShAmtRange =
5176 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5177 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5178 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5179 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5180 // shifted out, then we can compute the number of sign bits for the
5181 // operand being extended. A future improvement could be to pass along the
5182 // "shifted left by" information in the recursive calls to
5183 // ComputeKnownSignBits. Allowing us to handle this more generically.
5184 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5185 SDValue Ext = Op.getOperand(0);
5186 EVT ExtVT = Ext.getValueType();
5187 SDValue Extendee = Ext.getOperand(0);
5188 EVT ExtendeeVT = Extendee.getValueType();
5189 unsigned SizeDifference =
5190 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5191 if (SizeDifference <= MinShAmt) {
5192 Tmp = SizeDifference +
5193 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5194 if (MaxShAmt < Tmp)
5195 return Tmp - MaxShAmt;
5196 }
5197 }
5198 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5199 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5200 if (MaxShAmt < Tmp)
5201 return Tmp - MaxShAmt;
5202 }
5203 break;
5204 case ISD::AND:
5205 case ISD::OR:
5206 case ISD::XOR: // NOT is handled here.
5207 // Logical binary ops preserve the number of sign bits at the worst.
5208 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5209 if (Tmp != 1) {
5210 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5211 FirstAnswer = std::min(Tmp, Tmp2);
5212 // We computed what we know about the sign bits as our first
5213 // answer. Now proceed to the generic code that uses
5214 // computeKnownBits, and pick whichever answer is better.
5215 }
5216 break;
5217
5218 case ISD::SELECT:
5219 case ISD::VSELECT:
5220 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5221 if (Tmp == 1) return 1; // Early out.
5222 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5223 return std::min(Tmp, Tmp2);
5224 case ISD::SELECT_CC:
5225 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5226 if (Tmp == 1) return 1; // Early out.
5227 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5228 return std::min(Tmp, Tmp2);
5229
5230 case ISD::SMIN:
5231 case ISD::SMAX: {
5232 // If we have a clamp pattern, we know that the number of sign bits will be
5233 // the minimum of the clamp min/max range.
5234 bool IsMax = (Opcode == ISD::SMAX);
5235 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5236 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5237 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5238 CstHigh =
5239 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5240 if (CstLow && CstHigh) {
5241 if (!IsMax)
5242 std::swap(CstLow, CstHigh);
5243 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5244 Tmp = CstLow->getAPIntValue().getNumSignBits();
5245 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5246 return std::min(Tmp, Tmp2);
5247 }
5248 }
5249
5250 // Fallback - just get the minimum number of sign bits of the operands.
5251 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5252 if (Tmp == 1)
5253 return 1; // Early out.
5254 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5255 return std::min(Tmp, Tmp2);
5256 }
5257 case ISD::UMIN:
5258 case ISD::UMAX:
5259 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5260 if (Tmp == 1)
5261 return 1; // Early out.
5262 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5263 return std::min(Tmp, Tmp2);
5264 case ISD::SSUBO_CARRY:
5265 case ISD::USUBO_CARRY:
5266 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5267 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5268 return VTBits;
5269 [[fallthrough]];
5270 case ISD::SADDO:
5271 case ISD::UADDO:
5272 case ISD::SADDO_CARRY:
5273 case ISD::UADDO_CARRY:
5274 case ISD::SSUBO:
5275 case ISD::USUBO:
5276 case ISD::SMULO:
5277 case ISD::UMULO:
5278 if (Op.getResNo() != 1)
5279 break;
5280 // The boolean result conforms to getBooleanContents. Fall through.
5281 // If setcc returns 0/-1, all bits are sign bits.
5282 // We know that we have an integer-based boolean since these operations
5283 // are only available for integer.
5284 if (TLI->getBooleanContents(VT.isVector(), false) ==
5286 return VTBits;
5287 break;
5288 case ISD::SETCC:
5289 case ISD::SETCCCARRY:
5290 case ISD::STRICT_FSETCC:
5291 case ISD::STRICT_FSETCCS: {
5292 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5293 // If setcc returns 0/-1, all bits are sign bits.
5294 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5296 return VTBits;
5297 break;
5298 }
5301 // Semantically similar to icmp ult.
5302 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5304 return VTBits;
5305 break;
5306 case ISD::ROTL:
5307 case ISD::ROTR: {
5308 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5309 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5310 FirstAnswer = SignBitsOps::rot(
5311 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5312 Opcode == ISD::ROTR);
5313 break;
5314 }
5315 case ISD::ADD:
5316 case ISD::ADDC:
5317 // TODO: Move Operand 1 check before Operand 0 check
5318 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5319 if (Tmp == 1) return 1; // Early out.
5320
5321 // Special case decrementing a value (ADD X, -1):
5322 if (ConstantSDNode *CRHS =
5323 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5324 if (CRHS->isAllOnes()) {
5326 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5327
5328 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5329 // sign bits set.
5330 if ((Known.Zero | 1).isAllOnes())
5331 return VTBits;
5332
5333 // If we are subtracting one from a positive number, there is no carry
5334 // out of the result.
5335 if (Known.isNonNegative())
5336 return Tmp;
5337 }
5338
5339 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5340 if (Tmp2 == 1) return 1; // Early out.
5341
5342 // Add can have at most one carry bit. Thus we know that the output
5343 // is, at worst, one more bit than the inputs.
5344 return std::min(Tmp, Tmp2) - 1;
5345 case ISD::SUB:
5346 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5347 if (Tmp2 == 1) return 1; // Early out.
5348
5349 // Handle NEG.
5350 if (ConstantSDNode *CLHS =
5351 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5352 if (CLHS->isZero()) {
5354 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5355 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5356 // sign bits set.
5357 if ((Known.Zero | 1).isAllOnes())
5358 return VTBits;
5359
5360 // If the input is known to be positive (the sign bit is known clear),
5361 // the output of the NEG has the same number of sign bits as the input.
5362 if (Known.isNonNegative())
5363 return Tmp2;
5364
5365 // Otherwise, we treat this like a SUB.
5366 }
5367
5368 // Sub can have at most one carry bit. Thus we know that the output
5369 // is, at worst, one more bit than the inputs.
5370 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5371 if (Tmp == 1) return 1; // Early out.
5372 return std::min(Tmp, Tmp2) - 1;
5373 case ISD::MUL: {
5374 // The output of the Mul can be at most twice the valid bits in the inputs.
5375 unsigned SignBitsOp0 =
5376 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5377 if (SignBitsOp0 == 1)
5378 break;
5379 unsigned SignBitsOp1 =
5380 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5381 if (SignBitsOp1 == 1)
5382 break;
5383 unsigned OutValidBits =
5384 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5385 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5386 }
5387 case ISD::AVGCEILS:
5388 case ISD::AVGFLOORS:
5389 case ISD::AVGSUBFLOORS:
5390 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5391 if (Tmp == 1)
5392 return 1; // Early out.
5393 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5394 return std::min(Tmp, Tmp2);
5395 case ISD::SREM:
5396 // The sign bit is the LHS's sign bit, except when the result of the
5397 // remainder is zero. The magnitude of the result should be less than or
5398 // equal to the magnitude of the LHS. Therefore, the result should have
5399 // at least as many sign bits as the left hand side.
5400 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5401 case ISD::TRUNCATE: {
5402 // Check if the sign bits of source go down as far as the truncated value.
5403 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5404 unsigned NumSrcSignBits =
5405 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5406 if (NumSrcSignBits > (NumSrcBits - VTBits))
5407 return NumSrcSignBits - (NumSrcBits - VTBits);
5408 break;
5409 }
5410 case ISD::EXTRACT_ELEMENT: {
5411 if (VT.isScalableVector())
5412 break;
5413 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5414 const int BitWidth = Op.getValueSizeInBits();
5415 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5416
5417 // Get reverse index (starting from 1), Op1 value indexes elements from
5418 // little end. Sign starts at big end.
5419 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5420
5421 // If the sign portion ends in our element the subtraction gives correct
5422 // result. Otherwise it gives either negative or > bitwidth result
5423 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5424 }
5426 if (VT.isScalableVector())
5427 break;
5428 // If we know the element index, split the demand between the
5429 // source vector and the inserted element, otherwise assume we need
5430 // the original demanded vector elements and the value.
5431 SDValue InVec = Op.getOperand(0);
5432 SDValue InVal = Op.getOperand(1);
5433 SDValue EltNo = Op.getOperand(2);
5434 bool DemandedVal = true;
5435 APInt DemandedVecElts = DemandedElts;
5436 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5437 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5438 unsigned EltIdx = CEltNo->getZExtValue();
5439 DemandedVal = !!DemandedElts[EltIdx];
5440 DemandedVecElts.clearBit(EltIdx);
5441 }
5442 Tmp = std::numeric_limits<unsigned>::max();
5443 if (DemandedVal) {
5444 // TODO - handle implicit truncation of inserted elements.
5445 if (InVal.getScalarValueSizeInBits() != VTBits)
5446 break;
5447 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5448 Tmp = std::min(Tmp, Tmp2);
5449 }
5450 if (!!DemandedVecElts) {
5451 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5452 Tmp = std::min(Tmp, Tmp2);
5453 }
5454 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5455 return Tmp;
5456 }
5458 SDValue InVec = Op.getOperand(0);
5459 SDValue EltNo = Op.getOperand(1);
5460 EVT VecVT = InVec.getValueType();
5461 // ComputeNumSignBits not yet implemented for scalable vectors.
5462 if (VecVT.isScalableVector())
5463 break;
5464 const unsigned BitWidth = Op.getValueSizeInBits();
5465 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5466 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5467
5468 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5469 // anything about sign bits. But if the sizes match we can derive knowledge
5470 // about sign bits from the vector operand.
5471 if (BitWidth != EltBitWidth)
5472 break;
5473
5474 // If we know the element index, just demand that vector element, else for
5475 // an unknown element index, ignore DemandedElts and demand them all.
5476 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5477 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5478 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5479 DemandedSrcElts =
5480 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5481
5482 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5483 }
5485 // Offset the demanded elts by the subvector index.
5486 SDValue Src = Op.getOperand(0);
5487
5488 APInt DemandedSrcElts;
5489 if (Src.getValueType().isScalableVector())
5490 DemandedSrcElts = APInt(1, 1);
5491 else {
5492 uint64_t Idx = Op.getConstantOperandVal(1);
5493 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5494 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5495 }
5496 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5497 }
5498 case ISD::CONCAT_VECTORS: {
5499 if (VT.isScalableVector())
5500 break;
5501 // Determine the minimum number of sign bits across all demanded
5502 // elts of the input vectors. Early out if the result is already 1.
5503 Tmp = std::numeric_limits<unsigned>::max();
5504 EVT SubVectorVT = Op.getOperand(0).getValueType();
5505 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5506 unsigned NumSubVectors = Op.getNumOperands();
5507 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5508 APInt DemandedSub =
5509 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5510 if (!DemandedSub)
5511 continue;
5512 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5513 Tmp = std::min(Tmp, Tmp2);
5514 }
5515 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5516 return Tmp;
5517 }
5518 case ISD::INSERT_SUBVECTOR: {
5519 SDValue Src = Op.getOperand(0);
5520 SDValue Sub = Op.getOperand(1);
5521 if (VT.isScalableVector()) {
5522 Tmp = ComputeNumSignBits(Sub, Depth + 1);
5523 Tmp = std::min(Tmp, ComputeNumSignBits(Src, Depth + 1));
5524 return Tmp;
5525 }
5526 // Demand any elements from the subvector and the remainder from the src its
5527 // inserted into.
5528 uint64_t Idx = Op.getConstantOperandVal(2);
5529 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5530 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5531 APInt DemandedSrcElts = DemandedElts;
5532 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5533
5534 Tmp = std::numeric_limits<unsigned>::max();
5535 if (!!DemandedSubElts) {
5536 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5537 if (Tmp == 1)
5538 return 1; // early-out
5539 }
5540 if (!!DemandedSrcElts) {
5541 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5542 Tmp = std::min(Tmp, Tmp2);
5543 }
5544 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5545 return Tmp;
5546 }
5547 case ISD::LOAD: {
5548 // If we are looking at the loaded value of the SDNode.
5549 if (Op.getResNo() != 0)
5550 break;
5551
5553 if (const MDNode *Ranges = LD->getRanges()) {
5554 if (DemandedElts != 1)
5555 break;
5556
5558 if (VTBits > CR.getBitWidth()) {
5559 switch (LD->getExtensionType()) {
5560 case ISD::SEXTLOAD:
5561 CR = CR.signExtend(VTBits);
5562 break;
5563 case ISD::ZEXTLOAD:
5564 CR = CR.zeroExtend(VTBits);
5565 break;
5566 default:
5567 break;
5568 }
5569 }
5570
5571 if (VTBits != CR.getBitWidth())
5572 break;
5573 return std::min(CR.getSignedMin().getNumSignBits(),
5575 }
5576
5577 unsigned ExtType = LD->getExtensionType();
5578 switch (ExtType) {
5579 default:
5580 break;
5581 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5582 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5583 return VTBits - Tmp + 1;
5584 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5585 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5586 return VTBits - Tmp;
5587 case ISD::NON_EXTLOAD:
5588 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5589 // We only need to handle vectors - computeKnownBits should handle
5590 // scalar cases.
5591 Type *CstTy = Cst->getType();
5592 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5593 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5594 VTBits == CstTy->getScalarSizeInBits()) {
5595 Tmp = VTBits;
5596 for (unsigned i = 0; i != NumElts; ++i) {
5597 if (!DemandedElts[i])
5598 continue;
5599 if (Constant *Elt = Cst->getAggregateElement(i)) {
5600 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5601 const APInt &Value = CInt->getValue();
5602 Tmp = std::min(Tmp, Value.getNumSignBits());
5603 continue;
5604 }
5605 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5606 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5607 Tmp = std::min(Tmp, Value.getNumSignBits());
5608 continue;
5609 }
5610 }
5611 // Unknown type. Conservatively assume no bits match sign bit.
5612 return 1;
5613 }
5614 return Tmp;
5615 }
5616 }
5617 break;
5618 }
5619
5620 break;
5621 }
5624 case ISD::ATOMIC_SWAP:
5636 case ISD::ATOMIC_LOAD: {
5637 auto *AT = cast<AtomicSDNode>(Op);
5638 // If we are looking at the loaded value.
5639 if (Op.getResNo() == 0) {
5640 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5641 if (Tmp == VTBits)
5642 return 1; // early-out
5643
5644 // For atomic_load, prefer to use the extension type.
5645 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5646 switch (AT->getExtensionType()) {
5647 default:
5648 break;
5649 case ISD::SEXTLOAD:
5650 return VTBits - Tmp + 1;
5651 case ISD::ZEXTLOAD:
5652 return VTBits - Tmp;
5653 }
5654 }
5655
5656 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5657 return VTBits - Tmp + 1;
5658 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5659 return VTBits - Tmp;
5660 }
5661 break;
5662 }
5663 }
5664
5665 // Allow the target to implement this method for its nodes.
5666 if (Opcode >= ISD::BUILTIN_OP_END ||
5667 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5668 Opcode == ISD::INTRINSIC_W_CHAIN ||
5669 Opcode == ISD::INTRINSIC_VOID) {
5670 // TODO: This can probably be removed once target code is audited. This
5671 // is here purely to reduce patch size and review complexity.
5672 if (!VT.isScalableVector()) {
5673 unsigned NumBits =
5674 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5675 if (NumBits > 1)
5676 FirstAnswer = std::max(FirstAnswer, NumBits);
5677 }
5678 }
5679
5680 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5681 // use this information.
5682 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5683 return std::max(FirstAnswer, Known.countMinSignBits());
5684}
5685
5687 unsigned Depth) const {
5688 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5689 return Op.getScalarValueSizeInBits() - SignBits + 1;
5690}
5691
5693 const APInt &DemandedElts,
5694 unsigned Depth) const {
5695 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5696 return Op.getScalarValueSizeInBits() - SignBits + 1;
5697}
5698
5700 UndefPoisonKind Kind,
5701 unsigned Depth) const {
5702 // Early out for FREEZE.
5703 if (Op.getOpcode() == ISD::FREEZE)
5704 return true;
5705
5706 APInt DemandedElts = getDemandAllEltsMask(Op);
5707 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5708}
5709
5711 const APInt &DemandedElts,
5712 UndefPoisonKind Kind,
5713 unsigned Depth) const {
5714 unsigned Opcode = Op.getOpcode();
5715
5716 // Early out for FREEZE.
5717 if (Opcode == ISD::FREEZE)
5718 return true;
5719
5720 if (Depth >= MaxRecursionDepth)
5721 return false; // Limit search depth.
5722
5723 if (isIntOrFPConstant(Op))
5724 return true;
5725
5726 switch (Opcode) {
5727 case ISD::CONDCODE:
5728 case ISD::VALUETYPE:
5729 case ISD::FrameIndex:
5731 case ISD::CopyFromReg:
5732 return true;
5733
5734 case ISD::POISON:
5735 return !includesPoison(Kind);
5736
5737 case ISD::UNDEF:
5738 return !includesUndef(Kind);
5739
5740 case ISD::BITCAST: {
5741 SDValue Src = Op.getOperand(0);
5742 EVT SrcVT = Src.getValueType();
5743 EVT DstVT = Op.getValueType();
5744
5745 if (!SrcVT.isVector() || !DstVT.isVector())
5746 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5747
5748 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5749 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5750 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5751 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5752
5753 if (SrcEltBits == DstEltBits)
5754 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5755 Depth + 1);
5756
5757 if (SrcEltBits < DstEltBits) {
5758 if (DstEltBits % SrcEltBits != 0)
5759 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5760
5761 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5762 "Unexpected vector bitcast");
5763 APInt DemandedSrcElts =
5764 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5765 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5766 Depth + 1);
5767 }
5768
5769 if (SrcEltBits % DstEltBits != 0)
5770 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5771
5772 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5773 "Unexpected vector bitcast");
5774 APInt DemandedSrcElts =
5775 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5776 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5777 Depth + 1);
5778 }
5779
5780 case ISD::BUILD_VECTOR:
5781 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5782 // this shouldn't affect the result.
5783 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5784 if (!DemandedElts[i])
5785 continue;
5786 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5787 return false;
5788 }
5789 return true;
5790
5791 case ISD::CONCAT_VECTORS: {
5792 EVT VT = Op.getValueType();
5793 if (!VT.isFixedLengthVector())
5794 break;
5795
5796 EVT SubVT = Op.getOperand(0).getValueType();
5797 unsigned NumSubElts = SubVT.getVectorNumElements();
5798 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5799 APInt DemandedSubElts =
5800 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5801 if (!!DemandedSubElts &&
5802 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5803 Kind, Depth + 1))
5804 return false;
5805 }
5806 return true;
5807 }
5808
5810 SDValue Src = Op.getOperand(0);
5811 if (Src.getValueType().isScalableVector())
5812 break;
5813 uint64_t Idx = Op.getConstantOperandVal(1);
5814 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5815 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5816 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5817 Depth + 1);
5818 }
5819
5820 case ISD::INSERT_SUBVECTOR: {
5821 if (Op.getValueType().isScalableVector())
5822 break;
5823 SDValue Src = Op.getOperand(0);
5824 SDValue Sub = Op.getOperand(1);
5825 uint64_t Idx = Op.getConstantOperandVal(2);
5826 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5827 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5828 APInt DemandedSrcElts = DemandedElts;
5829 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5830
5831 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5832 Sub, DemandedSubElts, Kind, Depth + 1))
5833 return false;
5834 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5835 Src, DemandedSrcElts, Kind, Depth + 1))
5836 return false;
5837 return true;
5838 }
5839
5841 SDValue Src = Op.getOperand(0);
5842 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5843 EVT SrcVT = Src.getValueType();
5844 if (SrcVT.isFixedLengthVector() && IndexC &&
5845 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5846 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5847 IndexC->getZExtValue());
5848 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5849 Depth + 1);
5850 }
5851 break;
5852 }
5853
5855 SDValue InVec = Op.getOperand(0);
5856 SDValue InVal = Op.getOperand(1);
5857 SDValue EltNo = Op.getOperand(2);
5858 EVT VT = InVec.getValueType();
5859 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5860 if (IndexC && VT.isFixedLengthVector() &&
5861 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5862 if (DemandedElts[IndexC->getZExtValue()] &&
5863 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5864 return false;
5865 APInt InVecDemandedElts = DemandedElts;
5866 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5867 if (!!InVecDemandedElts &&
5869 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5870 InVecDemandedElts, Kind, Depth + 1))
5871 return false;
5872 return true;
5873 }
5874 break;
5875 }
5876
5878 // Check upper (known poison) elements.
5879 if (DemandedElts.ugt(1) && includesPoison(Kind))
5880 return false;
5881 // Check element zero.
5882 if (DemandedElts[0] &&
5883 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5884 return false;
5885 return true;
5886
5887 case ISD::SPLAT_VECTOR:
5888 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5889
5890 case ISD::SELECT: {
5891 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5892 /*ConsiderFlags*/ true, Depth) &&
5893 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5894 Depth + 1) &&
5895 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5896 Kind, Depth + 1) &&
5897 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5898 Kind, Depth + 1);
5899 }
5900
5901 case ISD::VECTOR_SHUFFLE: {
5902 APInt DemandedLHS, DemandedRHS;
5903 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5904 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5905 DemandedElts, DemandedLHS, DemandedRHS,
5906 /*AllowUndefElts=*/false))
5907 return false;
5908 if (!DemandedLHS.isZero() &&
5909 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5910 Depth + 1))
5911 return false;
5912 if (!DemandedRHS.isZero() &&
5913 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5914 Depth + 1))
5915 return false;
5916 return true;
5917 }
5918
5919 case ISD::SHL:
5920 case ISD::SRL:
5921 case ISD::SRA:
5922 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5923 // enough to check operand 0 if Op can't create undef/poison.
5924 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5925 /*ConsiderFlags*/ true, Depth) &&
5926 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5927 Kind, Depth + 1);
5928
5929 case ISD::BSWAP:
5930 case ISD::CTPOP:
5931 case ISD::BITREVERSE:
5932 case ISD::AND:
5933 case ISD::OR:
5934 case ISD::XOR:
5935 case ISD::ADD:
5936 case ISD::SUB:
5937 case ISD::MUL:
5938 case ISD::SADDSAT:
5939 case ISD::UADDSAT:
5940 case ISD::SSUBSAT:
5941 case ISD::USUBSAT:
5942 case ISD::SSHLSAT:
5943 case ISD::USHLSAT:
5944 case ISD::SMIN:
5945 case ISD::SMAX:
5946 case ISD::UMIN:
5947 case ISD::UMAX:
5948 case ISD::ZERO_EXTEND:
5949 case ISD::SIGN_EXTEND:
5950 case ISD::ANY_EXTEND:
5951 case ISD::TRUNCATE:
5952 case ISD::VSELECT: {
5953 // If Op can't create undef/poison and none of its operands are undef/poison
5954 // then Op is never undef/poison. A difference from the more common check
5955 // below, outside the switch, is that we handle elementwise operations for
5956 // which the DemandedElts mask is valid for all operands here.
5957 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5958 /*ConsiderFlags*/ true, Depth) &&
5959 all_of(Op->ops(), [&](SDValue V) {
5960 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5961 Depth + 1);
5962 });
5963 }
5964
5965 // TODO: Search for noundef attributes from library functions.
5966
5967 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5968
5969 default:
5970 // Allow the target to implement this method for its nodes.
5971 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5972 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5973 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5974 Op, DemandedElts, *this, Kind, Depth);
5975 break;
5976 }
5977
5978 // If Op can't create undef/poison and none of its operands are undef/poison
5979 // then Op is never undef/poison.
5980 // NOTE: TargetNodes can handle this in themselves in
5981 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5982 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5983 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5984 all_of(Op->ops(), [&](SDValue V) {
5985 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5986 });
5987}
5988
5990 bool ConsiderFlags,
5991 unsigned Depth) const {
5992 APInt DemandedElts = getDemandAllEltsMask(Op);
5993 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5994}
5995
5997 UndefPoisonKind Kind,
5998 bool ConsiderFlags,
5999 unsigned Depth) const {
6000 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
6001 return true;
6002
6003 unsigned Opcode = Op.getOpcode();
6004 switch (Opcode) {
6005 case ISD::AssertSext:
6006 case ISD::AssertZext:
6007 case ISD::AssertAlign:
6009 // Assertion nodes can create poison if the assertion fails.
6010 return includesPoison(Kind);
6011
6012 case ISD::FREEZE:
6016 case ISD::SADDSAT:
6017 case ISD::UADDSAT:
6018 case ISD::SSUBSAT:
6019 case ISD::USUBSAT:
6020 case ISD::MULHU:
6021 case ISD::MULHS:
6022 case ISD::AVGFLOORS:
6023 case ISD::AVGFLOORU:
6024 case ISD::AVGCEILS:
6025 case ISD::AVGCEILU:
6026 case ISD::AVGSUBFLOORS:
6027 case ISD::AVGSUBFLOORU:
6028 case ISD::ABDU:
6029 case ISD::ABDS:
6030 case ISD::SMIN:
6031 case ISD::SMAX:
6032 case ISD::SCMP:
6033 case ISD::UMIN:
6034 case ISD::UMAX:
6035 case ISD::UCMP:
6036 case ISD::AND:
6037 case ISD::XOR:
6038 case ISD::ROTL:
6039 case ISD::ROTR:
6040 case ISD::FSHL:
6041 case ISD::FSHR:
6042 case ISD::BSWAP:
6043 case ISD::CTTZ:
6044 case ISD::CTLZ:
6045 case ISD::CTLS:
6046 case ISD::CTPOP:
6047 case ISD::BITREVERSE:
6048 case ISD::PARITY:
6049 case ISD::SIGN_EXTEND:
6050 case ISD::TRUNCATE:
6054 case ISD::BITCAST:
6055 case ISD::BUILD_VECTOR:
6056 case ISD::BUILD_PAIR:
6057 case ISD::SPLAT_VECTOR:
6058 case ISD::FABS:
6059 case ISD::FCEIL:
6060 case ISD::FFLOOR:
6061 case ISD::FTRUNC:
6062 case ISD::FRINT:
6063 case ISD::FNEARBYINT:
6064 case ISD::FROUND:
6065 case ISD::FROUNDEVEN:
6066 return false;
6067
6068 case ISD::ABS:
6069 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6070 // Different to Intrinsic::abs.
6071 return false;
6073 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6074 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6075
6076 case ISD::ADDC:
6077 case ISD::SUBC:
6078 case ISD::ADDE:
6079 case ISD::SUBE:
6080 case ISD::SADDO:
6081 case ISD::SSUBO:
6082 case ISD::SMULO:
6083 case ISD::SADDO_CARRY:
6084 case ISD::SSUBO_CARRY:
6085 case ISD::UADDO:
6086 case ISD::USUBO:
6087 case ISD::UMULO:
6088 case ISD::UADDO_CARRY:
6089 case ISD::USUBO_CARRY:
6090 // No poison on result or overflow flags.
6091 return false;
6092
6093 case ISD::SELECT_CC:
6094 case ISD::SETCC: {
6095 // Integer setcc cannot create undef or poison.
6096 if (Op.getOperand(0).getValueType().isInteger())
6097 return false;
6098
6099 // FP compares are more complicated. They can create poison for nan/infinity
6100 // based on options and flags. The options and flags also cause special
6101 // nonan condition codes to be used. Those condition codes may be preserved
6102 // even if the nonan flag is dropped somewhere.
6103 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6104 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6105 return (unsigned)CCCode & 0x10U;
6106 }
6107
6108 case ISD::OR:
6109 case ISD::ZERO_EXTEND:
6110 case ISD::SELECT:
6111 case ISD::VSELECT:
6112 case ISD::ADD:
6113 case ISD::SUB:
6114 case ISD::MUL:
6115 case ISD::FNEG:
6116 case ISD::FADD:
6117 case ISD::FSUB:
6118 case ISD::FMUL:
6119 case ISD::FDIV:
6120 case ISD::FREM:
6121 case ISD::FCOPYSIGN:
6122 case ISD::FMA:
6123 case ISD::FMAD:
6124 case ISD::FMULADD:
6125 case ISD::FP_EXTEND:
6126 case ISD::FMINNUM:
6127 case ISD::FMAXNUM:
6128 case ISD::FMINNUM_IEEE:
6129 case ISD::FMAXNUM_IEEE:
6130 case ISD::FMINIMUM:
6131 case ISD::FMAXIMUM:
6132 case ISD::FMINIMUMNUM:
6133 case ISD::FMAXIMUMNUM:
6139 // No poison except from flags (which is handled above)
6140 return false;
6141
6142 case ISD::SHL:
6143 case ISD::SRL:
6144 case ISD::SRA:
6145 // If the max shift amount isn't in range, then the shift can
6146 // create poison.
6147 return includesPoison(Kind) &&
6148 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6149
6152 // If the amount is zero then the result will be poison.
6153 // TODO: Add isKnownNeverZero DemandedElts handling.
6154 return includesPoison(Kind) &&
6155 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6156
6158 // Check if we demand any upper (poison) elements.
6159 return includesPoison(Kind) && DemandedElts.ugt(1);
6160
6163 // Ensure that the element index is in bounds.
6164 if (includesPoison(Kind)) {
6165 EVT VecVT = Op.getOperand(0).getValueType();
6166 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6167 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6168 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6169 }
6170 return false;
6171 }
6172
6173 case ISD::VECTOR_SHUFFLE: {
6174 // Check for any demanded shuffle element that is undef.
6175 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6176 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6177 if (Elt < 0 && DemandedElts[Idx])
6178 return true;
6179 return false;
6180 }
6181
6183 return false;
6184
6185 default:
6186 // Allow the target to implement this method for its nodes.
6187 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6188 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6189 return TLI->canCreateUndefOrPoisonForTargetNode(
6190 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6191 break;
6192 }
6193
6194 // Be conservative and return true.
6195 return true;
6196}
6197
6198bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6199 unsigned Opcode = Op.getOpcode();
6200 if (Opcode == ISD::OR)
6201 return Op->getFlags().hasDisjoint() ||
6202 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6203 if (Opcode == ISD::XOR)
6204 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6205 return false;
6206}
6207
6209 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6210 (Op.isAnyAdd() || isADDLike(Op));
6211}
6212
6214 FPClassTest InterestedClasses,
6215 unsigned Depth) const {
6216 APInt DemandedElts = getDemandAllEltsMask(Op);
6217 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6218}
6219
6221 const APInt &DemandedElts,
6222 FPClassTest InterestedClasses,
6223 unsigned Depth) const {
6225
6226 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6227 return KnownFPClass(CFP->getValueAPF());
6228
6229 if (Depth >= MaxRecursionDepth)
6230 return Known;
6231
6232 if (Op.getOpcode() == ISD::UNDEF)
6233 return Known;
6234
6235 EVT VT = Op.getValueType();
6236 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6237 assert((!VT.isFixedLengthVector() ||
6238 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6239 "Unexpected vector size");
6240
6241 if (!DemandedElts)
6242 return Known;
6243
6244 unsigned Opcode = Op.getOpcode();
6245 switch (Opcode) {
6246 case ISD::POISON: {
6248 break;
6249 }
6250 case ISD::FNEG: {
6251 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6252 InterestedClasses, Depth + 1);
6253 Known.fneg();
6254 break;
6255 }
6256 case ISD::BUILD_VECTOR: {
6257 assert(!VT.isScalableVector());
6258 bool First = true;
6259 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6260 if (!DemandedElts[I])
6261 continue;
6262
6263 if (First) {
6264 Known =
6265 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6266 First = false;
6267 } else {
6268 Known |=
6269 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6270 }
6271
6272 if (Known.isUnknown())
6273 break;
6274 }
6275 break;
6276 }
6278 SDValue Src = Op.getOperand(0);
6279 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6280 EVT SrcVT = Src.getValueType();
6281 if (SrcVT.isFixedLengthVector() && CIdx) {
6282 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6283 APInt DemandedSrcElts = APInt::getOneBitSet(
6284 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6285 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6286 Depth + 1);
6287 } else {
6288 // Out of bounds index is poison.
6290 }
6291 } else {
6292 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6293 }
6294 break;
6295 }
6296 case ISD::SPLAT_VECTOR: {
6297 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6298 break;
6299 }
6300 case ISD::BITCAST: {
6301 // FIXME: It should not be necessary to check for an elementwise bitcast.
6302 // If a bitcast is not elementwise between vector / scalar types,
6303 // computeKnownBits already splices the known bits of the source elements
6304 // appropriately so as to line up with the bits of the result's demanded
6305 // elements.
6306 EVT SrcVT = Op.getOperand(0).getValueType();
6307 if (VT.isScalableVector() || SrcVT.isScalableVector())
6308 break;
6309 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6310 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6311 if (VTNumElts != SrcVTNumElts)
6312 break;
6313
6314 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6316 break;
6317 }
6318 case ISD::FABS: {
6319 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6320 InterestedClasses, Depth + 1);
6321 Known.fabs();
6322 break;
6323 }
6324 case ISD::FCOPYSIGN: {
6325 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6326 InterestedClasses, Depth + 1);
6327 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6328 InterestedClasses, Depth + 1);
6329 Known.copysign(KnownSign);
6330 break;
6331 }
6332 case ISD::AssertNoFPClass: {
6333 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6334 InterestedClasses, Depth + 1);
6335 FPClassTest AssertedClasses =
6336 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6337 Known.setKnownFPClasses(Known.getKnownFPClasses() & ~AssertedClasses);
6338 break;
6339 }
6341 SDValue Src = Op.getOperand(0);
6342 EVT SrcVT = Src.getValueType();
6343 if (SrcVT.isFixedLengthVector()) {
6344 unsigned Idx = Op.getConstantOperandVal(1);
6345 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6346
6347 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6348 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6349 Depth + 1);
6350 } else {
6351 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6352 }
6353 break;
6354 }
6355 case ISD::INSERT_SUBVECTOR: {
6356 SDValue BaseVector = Op.getOperand(0);
6357 SDValue SubVector = Op.getOperand(1);
6358 EVT BaseVT = BaseVector.getValueType();
6359 if (BaseVT.isFixedLengthVector()) {
6360 unsigned Idx = Op.getConstantOperandVal(2);
6361 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6362 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6363
6364 APInt DemandedMask =
6365 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6366 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6367 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6368
6369 if (!DemandedSrcElts.isZero())
6370 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6371 InterestedClasses, Depth + 1);
6372 if (!DemandedSubElts.isZero()) {
6374 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6375 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6376 }
6377 } else {
6378 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6379 if (!Known.isUnknown())
6380 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6381 }
6382 break;
6383 }
6384 case ISD::SELECT:
6385 case ISD::VSELECT: {
6386 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6387 // IR-level ValueTracking.
6388 KnownFPClass KnownFalseClass = computeKnownFPClass(
6389 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6390 if (KnownFalseClass.isUnknown())
6391 break;
6392 KnownFPClass KnownTrueClass = computeKnownFPClass(
6393 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6394 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6395 break;
6396 }
6397 default:
6398 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6399 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6400 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6401 Depth);
6402 }
6403 break;
6404 }
6405
6406 return Known;
6407}
6408
6410 unsigned Depth) const {
6411 APInt DemandedElts = getDemandAllEltsMask(Op);
6412 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6413}
6414
6416 bool SNaN, unsigned Depth) const {
6417 assert(!DemandedElts.isZero() && "No demanded elements");
6418
6419 // If we're told that NaNs won't happen, assume they won't.
6420 if (Op->getFlags().hasNoNaNs())
6421 return true;
6422
6423 if (Depth >= MaxRecursionDepth)
6424 return false; // Limit search depth.
6425
6426 unsigned Opcode = Op.getOpcode();
6427 switch (Opcode) {
6428 case ISD::FADD:
6429 case ISD::FSUB:
6430 case ISD::FMUL:
6431 case ISD::FDIV:
6432 case ISD::FREM:
6433 case ISD::FSIN:
6434 case ISD::FCOS:
6435 case ISD::FTAN:
6436 case ISD::FASIN:
6437 case ISD::FACOS:
6438 case ISD::FATAN:
6439 case ISD::FATAN2:
6440 case ISD::FSINH:
6441 case ISD::FCOSH:
6442 case ISD::FTANH:
6443 case ISD::FMA:
6444 case ISD::FMULADD:
6445 case ISD::FMAD: {
6446 if (SNaN)
6447 return true;
6448 // TODO: Need isKnownNeverInfinity
6449 return false;
6450 }
6451 case ISD::FCANONICALIZE:
6452 case ISD::FEXP:
6453 case ISD::FEXP2:
6454 case ISD::FEXP10:
6455 case ISD::FTRUNC:
6456 case ISD::FFLOOR:
6457 case ISD::FCEIL:
6458 case ISD::FROUND:
6459 case ISD::FROUNDEVEN:
6460 case ISD::LROUND:
6461 case ISD::LLROUND:
6462 case ISD::FRINT:
6463 case ISD::LRINT:
6464 case ISD::LLRINT:
6465 case ISD::FNEARBYINT:
6466 case ISD::FLDEXP: {
6467 if (SNaN)
6468 return true;
6469 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6470 }
6471 case ISD::FABS:
6472 case ISD::FNEG:
6473 case ISD::FCOPYSIGN: {
6474 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6475 }
6476 case ISD::SELECT:
6477 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6478 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6479 case ISD::FP_EXTEND:
6480 case ISD::FP_ROUND: {
6481 if (SNaN)
6482 return true;
6483 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6484 }
6485 case ISD::SINT_TO_FP:
6486 case ISD::UINT_TO_FP:
6487 return true;
6488 case ISD::FSQRT: // Need is known positive
6489 case ISD::FLOG:
6490 case ISD::FLOG2:
6491 case ISD::FLOG10:
6492 case ISD::FPOWI:
6493 case ISD::FPOW: {
6494 if (SNaN)
6495 return true;
6496 // TODO: Refine on operand
6497 return false;
6498 }
6499 case ISD::FMINNUM:
6500 case ISD::FMAXNUM:
6501 case ISD::FMINIMUMNUM:
6502 case ISD::FMAXIMUMNUM: {
6503 // Only one needs to be known not-nan, since it will be returned if the
6504 // other ends up being one.
6505 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6506 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6507 }
6508 case ISD::FMINNUM_IEEE:
6509 case ISD::FMAXNUM_IEEE: {
6510 if (SNaN)
6511 return true;
6512 // This can return a NaN if either operand is an sNaN, or if both operands
6513 // are NaN.
6514 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6515 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6516 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6517 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6518 }
6519 case ISD::FMINIMUM:
6520 case ISD::FMAXIMUM: {
6521 // TODO: Does this quiet or return the origina NaN as-is?
6522 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6523 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6524 }
6526 SDValue Src = Op.getOperand(0);
6527 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6528 EVT SrcVT = Src.getValueType();
6529 if (SrcVT.isFixedLengthVector() && Idx &&
6530 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6531 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6532 Idx->getZExtValue());
6533 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6534 }
6535 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6536 }
6538 SDValue Src = Op.getOperand(0);
6539 if (Src.getValueType().isFixedLengthVector()) {
6540 unsigned Idx = Op.getConstantOperandVal(1);
6541 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6542 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6543 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6544 }
6545 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6546 }
6547 case ISD::INSERT_SUBVECTOR: {
6548 SDValue BaseVector = Op.getOperand(0);
6549 SDValue SubVector = Op.getOperand(1);
6550 EVT BaseVectorVT = BaseVector.getValueType();
6551 if (BaseVectorVT.isFixedLengthVector()) {
6552 unsigned Idx = Op.getConstantOperandVal(2);
6553 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6554 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6555
6556 // Clear/Extract the bits at the position where the subvector will be
6557 // inserted.
6558 APInt DemandedMask =
6559 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6560 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6561 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6562
6563 bool NeverNaN = true;
6564 if (!DemandedSrcElts.isZero())
6565 NeverNaN &=
6566 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6567 if (NeverNaN && !DemandedSubElts.isZero())
6568 NeverNaN &=
6569 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6570 return NeverNaN;
6571 }
6572 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6573 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6574 }
6575 case ISD::BUILD_VECTOR: {
6576 unsigned NumElts = Op.getNumOperands();
6577 for (unsigned I = 0; I != NumElts; ++I)
6578 if (DemandedElts[I] &&
6579 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6580 return false;
6581 return true;
6582 }
6583 case ISD::SPLAT_VECTOR:
6584 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6585 case ISD::AssertNoFPClass: {
6586 FPClassTest NoFPClass =
6587 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6588 if ((NoFPClass & fcNan) == fcNan)
6589 return true;
6590 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6591 return true;
6592 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6593 }
6594 default:
6595 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6596 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6597 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6598 Depth);
6599 }
6600 break;
6601 }
6602
6603 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6604 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6605 return Known.isKnownNever(NanMask);
6606}
6607
6609 APInt DemandedElts = getDemandAllEltsMask(Op);
6610 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6611}
6612
6614 const APInt &DemandedElts,
6615 unsigned Depth) const {
6616 assert(!DemandedElts.isZero() && "No demanded elements");
6617 EVT VT = Op.getValueType();
6619 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6620 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6621}
6622
6624 APInt DemandedElts = getDemandAllEltsMask(Op);
6625 return isKnownNeverZero(Op, DemandedElts, Depth);
6626}
6627
6629 unsigned Depth) const {
6630 if (Depth >= MaxRecursionDepth)
6631 return false; // Limit search depth.
6632
6633 EVT OpVT = Op.getValueType();
6634 unsigned BitWidth = OpVT.getScalarSizeInBits();
6635
6636 assert(!Op.getValueType().isFloatingPoint() &&
6637 "Floating point types unsupported - use isKnownNeverLogicalZero");
6638
6639 // If the value is a constant, we can obviously see if it is a zero or not.
6640 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6641 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6642 return !V.isZero();
6643 };
6644
6645 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6646 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6647 return true;
6648
6649 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6650 // some degree.
6651 switch (Op.getOpcode()) {
6652 default:
6653 break;
6654
6656 SDValue InVec = Op.getOperand(0);
6657 SDValue EltNo = Op.getOperand(1);
6658 EVT VecVT = InVec.getValueType();
6659
6660 // Skip scalable vectors or implicit extensions.
6661 if (VecVT.isScalableVector() ||
6662 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6663 break;
6664
6665 // If we know the element index, just demand that vector element, else for
6666 // an unknown element index, ignore DemandedElts and demand them all.
6667 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6668 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6669 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6670 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6671 DemandedSrcElts =
6672 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6673
6674 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6675 }
6676
6677 case ISD::OR:
6678 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6679 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6680
6681 case ISD::VSELECT:
6682 case ISD::SELECT:
6683 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6684 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6685
6686 case ISD::SHL: {
6687 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6688 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6689 KnownBits ValKnown =
6690 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6691 // 1 << X is never zero.
6692 if (ValKnown.One[0])
6693 return true;
6694 // If max shift cnt of known ones is non-zero, result is non-zero.
6695 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6696 .getMaxValue();
6697 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6698 !ValKnown.One.shl(MaxCnt).isZero())
6699 return true;
6700 break;
6701 }
6702
6703 case ISD::VECTOR_SHUFFLE: {
6704 if (Op.getValueType().isScalableVector())
6705 return false;
6706
6707 unsigned NumElts = DemandedElts.getBitWidth();
6708
6709 // All demanded elements from LHS and RHS must be known non-zero.
6710 // Demanded elements with undef shuffle mask elements are unknown.
6711
6712 APInt DemandedLHS, DemandedRHS;
6713 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6714 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6715 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6716 DemandedLHS, DemandedRHS))
6717 return false;
6718
6719 return (!DemandedLHS ||
6720 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6721 (!DemandedRHS ||
6722 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6723 }
6724
6725 case ISD::UADDSAT:
6726 case ISD::UMAX:
6727 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6728 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6729
6730 case ISD::UMIN:
6731 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6732 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6733
6734 // For smin/smax: If either operand is known negative/positive
6735 // respectively we don't need the other to be known at all.
6736 case ISD::SMAX: {
6737 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6738 if (Op1.isStrictlyPositive())
6739 return true;
6740
6741 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6742 if (Op0.isStrictlyPositive())
6743 return true;
6744
6745 if (Op1.isNonZero() && Op0.isNonZero())
6746 return true;
6747
6748 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6749 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6750 }
6751 case ISD::SMIN: {
6752 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6753 if (Op1.isNegative())
6754 return true;
6755
6756 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6757 if (Op0.isNegative())
6758 return true;
6759
6760 if (Op1.isNonZero() && Op0.isNonZero())
6761 return true;
6762
6763 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6764 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6765 }
6766
6767 case ISD::ROTL:
6768 case ISD::ROTR:
6769 case ISD::BITREVERSE:
6770 case ISD::BSWAP:
6771 case ISD::CTPOP:
6772 case ISD::ABS:
6774 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6775
6776 case ISD::SRA:
6777 case ISD::SRL: {
6778 if (Op->getFlags().hasExact())
6779 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6780 KnownBits ValKnown =
6781 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6782 if (ValKnown.isNegative())
6783 return true;
6784 // If max shift cnt of known ones is non-zero, result is non-zero.
6785 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6786 .getMaxValue();
6787 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6788 !ValKnown.One.lshr(MaxCnt).isZero())
6789 return true;
6790 break;
6791 }
6792 case ISD::UDIV:
6793 case ISD::SDIV:
6794 // div exact can only produce a zero if the dividend is zero.
6795 // TODO: For udiv this is also true if Op1 u<= Op0
6796 if (Op->getFlags().hasExact())
6797 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6798 break;
6799
6800 case ISD::ADD:
6801 if (Op->getFlags().hasNoUnsignedWrap())
6802 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6803 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6804 return true;
6805 // TODO: There are a lot more cases we can prove for add.
6806 break;
6807
6808 case ISD::SUB: {
6809 if (isNullConstant(Op.getOperand(0)))
6810 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6811
6812 std::optional<bool> ne = KnownBits::ne(
6813 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6814 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6815 return ne && *ne;
6816 }
6817
6818 case ISD::MUL:
6819 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6820 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6821 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6822 return true;
6823 break;
6824
6825 case ISD::ZERO_EXTEND:
6826 case ISD::SIGN_EXTEND:
6827 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6828 case ISD::VSCALE: {
6830 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6831 ConstantRange CR =
6832 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6833 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6834 return true;
6835 break;
6836 }
6837 }
6838
6839 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6840}
6841
6844 return !C1->isNegative();
6845
6846 switch (Op.getOpcode()) {
6847 case ISD::FABS:
6848 case ISD::FEXP:
6849 case ISD::FEXP2:
6850 case ISD::FEXP10:
6851 return true;
6852 default:
6853 return false;
6854 }
6855
6856 llvm_unreachable("covered opcode switch");
6857}
6858
6859/// Return true if the standard nsz semantics may not apply for this opcode.
6860/// Opcode is assumed to take float inputs.
6861/// FIXME: Target min/max nodes (e.g. X86ISD::FMINC) aren't included.
6862static bool hasSpecialNszSemantics(unsigned Opcode) {
6863 switch (Opcode) {
6864 case ISD::FMINNUM:
6865 case ISD::FMAXNUM:
6866 case ISD::FMINNUM_IEEE:
6867 case ISD::FMAXNUM_IEEE:
6868 case ISD::FMINIMUM:
6869 case ISD::FMAXIMUM:
6870 case ISD::FMINIMUMNUM:
6871 case ISD::FMAXIMUMNUM:
6876 case ISD::PSEUDO_FMIN:
6877 case ISD::PSEUDO_FMAX:
6886 case ISD::VP_REDUCE_FMIN:
6887 case ISD::VP_REDUCE_FMAX:
6888 case ISD::VP_REDUCE_FMINIMUM:
6889 case ISD::VP_REDUCE_FMAXIMUM:
6890 return true;
6891 default:
6892 return false;
6893 }
6894}
6895
6897 assert(Use.getValueType().isFloatingPoint());
6898 const SDNode *User = Use.getUser();
6899 unsigned Opcode = User->getOpcode();
6900 if (User->getFlags().hasNoSignedZeros() && !hasSpecialNszSemantics(Opcode))
6901 return true;
6902
6903 unsigned OperandNo = Use.getOperandNo();
6904 // Check if this use is insensitive to the sign of zero
6905 switch (Opcode) {
6906 case ISD::SETCC:
6907 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6908 case ISD::FABS:
6909 // fabs always produces +0.0.
6910 return true;
6911 case ISD::FCOPYSIGN:
6912 // copysign overwrites the sign bit of the first operand.
6913 return OperandNo == 0;
6914 case ISD::FADD:
6915 case ISD::FSUB: {
6916 // Arithmetic with non-zero constants fixes the uncertainty around the
6917 // sign bit.
6918 SDValue Other = User->getOperand(1 - OperandNo);
6920 }
6921 case ISD::FP_TO_SINT:
6922 case ISD::FP_TO_UINT:
6923 // fp-to-int conversions normalize signed zeros.
6924 return true;
6925 case ISD::FMINNUM:
6926 case ISD::FMINNUM_IEEE:
6927 case ISD::FMINIMUM:
6928 case ISD::FMINIMUMNUM:
6929 case ISD::FMAXNUM:
6930 case ISD::FMAXNUM_IEEE:
6931 case ISD::FMAXIMUM:
6932 case ISD::FMAXIMUMNUM:
6933 case ISD::PSEUDO_FMIN:
6934 case ISD::PSEUDO_FMAX: {
6935 // If other value always beats zero, the zero can be ignored.
6936 bool IsMin = Opcode == ISD::FMINNUM || Opcode == ISD::FMINNUM_IEEE ||
6937 Opcode == ISD::FMINIMUM || Opcode == ISD::FMINIMUMNUM ||
6938 Opcode == ISD::PSEUDO_FMIN;
6939 FPClassTest AlwaysBeatsZero =
6941 SDValue Other = User->getOperand(1 - OperandNo);
6942 KnownFPClass Known = computeKnownFPClass(Other, ~AlwaysBeatsZero);
6943 return Known.isKnownNever(~AlwaysBeatsZero);
6944 }
6945 default:
6946 return false;
6947 }
6948}
6949
6951 assert(Op->getNumValues() == 1);
6952 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6953 // regression. Ideally, this should be implemented as a demanded-bits
6954 // optimization that stems from the users.
6955 if (Op->use_size() > 2)
6956 return false;
6957 return all_of(Op->uses(),
6958 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6959}
6960
6962 // Check the obvious case.
6963 if (A == B) return true;
6964
6965 // For negative and positive zero.
6968 if (CA->isZero() && CB->isZero()) return true;
6969
6970 // Otherwise they may not be equal.
6971 return false;
6972}
6973
6974// Only bits set in Mask must be negated, other bits may be arbitrary.
6976 if (isBitwiseNot(V, AllowUndefs))
6977 return V.getOperand(0);
6978
6979 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6980 // bits in the non-extended part.
6981 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6982 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6983 return SDValue();
6984 SDValue ExtArg = V.getOperand(0);
6985 if (ExtArg.getScalarValueSizeInBits() >=
6986 MaskC->getAPIntValue().getActiveBits() &&
6987 isBitwiseNot(ExtArg, AllowUndefs) &&
6988 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6989 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6990 return ExtArg.getOperand(0).getOperand(0);
6991 return SDValue();
6992}
6993
6995 // Match masked merge pattern (X & ~M) op (Y & M)
6996 // Including degenerate case (X & ~M) op M
6997 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6998 SDValue Other) {
6999 if (SDValue NotOperand =
7000 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
7001 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
7002 NotOperand->getOpcode() == ISD::TRUNCATE)
7003 NotOperand = NotOperand->getOperand(0);
7004
7005 if (Other == NotOperand)
7006 return true;
7007 if (Other->getOpcode() == ISD::AND)
7008 return NotOperand == Other->getOperand(0) ||
7009 NotOperand == Other->getOperand(1);
7010 }
7011 return false;
7012 };
7013
7014 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
7015 A = A->getOperand(0);
7016
7017 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
7018 B = B->getOperand(0);
7019
7020 if (A->getOpcode() == ISD::AND)
7021 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
7022 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
7023 return false;
7024}
7025
7026// FIXME: unify with llvm::haveNoCommonBitsSet.
7028 assert(A.getValueType() == B.getValueType() &&
7029 "Values must have the same type");
7032 return true;
7035}
7036
7037static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
7038 SelectionDAG &DAG) {
7039 if (cast<ConstantSDNode>(Step)->isZero())
7040 return DAG.getConstant(0, DL, VT);
7041
7042 return SDValue();
7043}
7044
7047 SelectionDAG &DAG) {
7048 int NumOps = Ops.size();
7049 assert(NumOps != 0 && "Can't build an empty vector!");
7050 assert(!VT.isScalableVector() &&
7051 "BUILD_VECTOR cannot be used with scalable types");
7052 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
7053 "Incorrect element count in BUILD_VECTOR!");
7054
7055 // BUILD_VECTOR of UNDEFs is UNDEF.
7056 bool AllPoison = true;
7057 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7058 AllPoison &= Op.getOpcode() == ISD::POISON;
7059 return Op.isUndef();
7060 }))
7061 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7062
7063 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
7064 SDValue IdentitySrc;
7065 bool IsIdentity = true;
7066 for (int i = 0; i != NumOps; ++i) {
7067 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7068 Ops[i].getOperand(0).getValueType() != VT ||
7069 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
7070 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
7071 Ops[i].getConstantOperandAPInt(1) != i) {
7072 IsIdentity = false;
7073 break;
7074 }
7075 IdentitySrc = Ops[i].getOperand(0);
7076 }
7077 if (IsIdentity)
7078 return IdentitySrc;
7079
7080 return SDValue();
7081}
7082
7083/// Try to simplify vector concatenation to an input value, undef, or build
7084/// vector.
7087 SelectionDAG &DAG) {
7088 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
7090 [Ops](SDValue Op) {
7091 return Ops[0].getValueType() == Op.getValueType();
7092 }) &&
7093 "Concatenation of vectors with inconsistent value types!");
7094 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
7095 VT.getVectorElementCount() &&
7096 "Incorrect element count in vector concatenation!");
7097
7098 if (Ops.size() == 1)
7099 return Ops[0];
7100
7101 // Concat of UNDEFs is UNDEF.
7102 bool AllPoison = true;
7103 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7104 AllPoison &= Op.getOpcode() == ISD::POISON;
7105 return Op.isUndef();
7106 }))
7107 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7108
7109 // Scan the operands and look for extract operations from a single source
7110 // that correspond to insertion at the same location via this concatenation:
7111 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7112 SDValue IdentitySrc;
7113 bool IsIdentity = true;
7114 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7115 SDValue Op = Ops[i];
7116 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7117 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7118 Op.getOperand(0).getValueType() != VT ||
7119 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7120 Op.getConstantOperandVal(1) != IdentityIndex) {
7121 IsIdentity = false;
7122 break;
7123 }
7124 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7125 "Unexpected identity source vector for concat of extracts");
7126 IdentitySrc = Op.getOperand(0);
7127 }
7128 if (IsIdentity) {
7129 assert(IdentitySrc && "Failed to set source vector of extracts");
7130 return IdentitySrc;
7131 }
7132
7133 // The code below this point is only designed to work for fixed width
7134 // vectors, so we bail out for now.
7135 if (VT.isScalableVector())
7136 return SDValue();
7137
7138 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7139 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7140 // BUILD_VECTOR.
7141 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7142 EVT SVT = VT.getScalarType();
7144 for (SDValue Op : Ops) {
7145 EVT OpVT = Op.getValueType();
7146 if (Op.getOpcode() == ISD::POISON)
7147 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7148 else if (Op.getOpcode() == ISD::UNDEF)
7149 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7150 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7151 Elts.append(Op->op_begin(), Op->op_end());
7152 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7153 OpVT.getVectorNumElements() == 1 &&
7154 isNullConstant(Op.getOperand(2)))
7155 Elts.push_back(Op.getOperand(1));
7156 else
7157 return SDValue();
7158 }
7159
7160 // BUILD_VECTOR requires all inputs to be of the same type, find the
7161 // maximum type and extend them all.
7162 for (SDValue Op : Elts)
7163 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7164
7165 if (SVT.bitsGT(VT.getScalarType())) {
7166 for (SDValue &Op : Elts) {
7167 if (Op.getOpcode() == ISD::POISON)
7168 Op = DAG.getPOISON(SVT);
7169 else if (Op.getOpcode() == ISD::UNDEF)
7170 Op = DAG.getUNDEF(SVT);
7171 else
7172 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7173 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7174 : DAG.getSExtOrTrunc(Op, DL, SVT);
7175 }
7176 }
7177
7178 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7179 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7180 return V;
7181}
7182
7183/// Gets or creates the specified node.
7184SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7185 SDVTList VTs = getVTList(VT);
7186 SDNodeKey ID(Opcode, VTs, {});
7187 FoldingSetInsertToken InsertToken;
7188 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7189 return SDValue(E, 0);
7190
7191 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7192 CSEMap.insert(N, InsertToken);
7193
7194 InsertNode(N);
7195 SDValue V = SDValue(N, 0);
7196 NewSDValueDbgMsg(V, "Creating new node: ", this);
7197 return V;
7198}
7199
7200SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7201 SDValue N1) {
7202 SDNodeFlags Flags;
7203 if (Inserter)
7204 Flags = Inserter->getFlags();
7205 return getNode(Opcode, DL, VT, N1, Flags);
7206}
7207
7208SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7209 SDValue N1, const SDNodeFlags Flags) {
7210 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7211
7212 // Constant fold unary operations with a vector integer or float operand.
7213 switch (Opcode) {
7214 default:
7215 // FIXME: Entirely reasonable to perform folding of other unary
7216 // operations here as the need arises.
7217 break;
7218 case ISD::FNEG:
7219 case ISD::FABS:
7220 case ISD::FCEIL:
7221 case ISD::FTRUNC:
7222 case ISD::FFLOOR:
7223 case ISD::FP_EXTEND:
7224 case ISD::FP_TO_SINT:
7225 case ISD::FP_TO_UINT:
7226 case ISD::FP_TO_FP16:
7227 case ISD::FP_TO_BF16:
7228 case ISD::TRUNCATE:
7229 case ISD::ANY_EXTEND:
7230 case ISD::ZERO_EXTEND:
7231 case ISD::SIGN_EXTEND:
7232 case ISD::UINT_TO_FP:
7233 case ISD::SINT_TO_FP:
7234 case ISD::FP16_TO_FP:
7235 case ISD::BF16_TO_FP:
7236 case ISD::BITCAST:
7237 case ISD::ABS:
7239 case ISD::BITREVERSE:
7240 case ISD::BSWAP:
7241 case ISD::CTLZ:
7243 case ISD::CTTZ:
7245 case ISD::CTPOP:
7246 case ISD::PARITY:
7247 case ISD::CTLS:
7248 case ISD::VECREDUCE_ADD:
7253 case ISD::VECREDUCE_MUL:
7254 case ISD::VECREDUCE_AND:
7255 case ISD::VECREDUCE_OR:
7256 case ISD::VECREDUCE_XOR:
7257 case ISD::STEP_VECTOR: {
7258 SDValue Ops = {N1};
7259 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7260 return Fold;
7261 }
7262 }
7263
7264 unsigned OpOpcode = N1.getNode()->getOpcode();
7265 switch (Opcode) {
7266 case ISD::STEP_VECTOR:
7267 assert(VT.isScalableVector() &&
7268 "STEP_VECTOR can only be used with scalable types");
7269 assert(OpOpcode == ISD::TargetConstant &&
7270 VT.getVectorElementType() == N1.getValueType() &&
7271 "Unexpected step operand");
7272 break;
7273 case ISD::FREEZE:
7274 assert(VT == N1.getValueType() && "Unexpected VT!");
7276 return N1;
7277 break;
7278 case ISD::TokenFactor:
7279 case ISD::MERGE_VALUES:
7281 return N1; // Factor, merge or concat of one node? No need.
7282 case ISD::BUILD_VECTOR: {
7283 // Attempt to simplify BUILD_VECTOR.
7284 SDValue Ops[] = {N1};
7285 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7286 return V;
7287 break;
7288 }
7289 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7290 case ISD::FP_EXTEND:
7292 "Invalid FP cast!");
7293 if (N1.getValueType() == VT) return N1; // noop conversion.
7294 assert((!VT.isVector() || VT.getVectorElementCount() ==
7296 "Vector element count mismatch!");
7297 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7298 if (N1.isUndef())
7299 return getUNDEF(VT);
7300 break;
7301 case ISD::FP_TO_SINT:
7302 case ISD::FP_TO_UINT:
7303 if (N1.isUndef())
7304 return getUNDEF(VT);
7305 break;
7306 case ISD::SINT_TO_FP:
7307 case ISD::UINT_TO_FP:
7308 // [us]itofp(undef) = 0, because the result value is bounded.
7309 if (N1.isUndef())
7310 return getConstantFP(0.0, DL, VT);
7311 break;
7312 case ISD::SIGN_EXTEND:
7313 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7314 "Invalid SIGN_EXTEND!");
7315 assert(VT.isVector() == N1.getValueType().isVector() &&
7316 "SIGN_EXTEND result type type should be vector iff the operand "
7317 "type is vector!");
7318 if (N1.getValueType() == VT) return N1; // noop extension
7319 assert((!VT.isVector() || VT.getVectorElementCount() ==
7321 "Vector element count mismatch!");
7322 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7323 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7324 SDNodeFlags Flags;
7325 if (OpOpcode == ISD::ZERO_EXTEND)
7326 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7327 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7328 transferDbgValues(N1, NewVal);
7329 return NewVal;
7330 }
7331
7332 if (OpOpcode == ISD::POISON)
7333 return getPOISON(VT);
7334
7335 if (N1.isUndef())
7336 // sext(undef) = 0, because the top bits will all be the same.
7337 return getConstant(0, DL, VT);
7338
7339 // Skip unnecessary sext_inreg pattern:
7340 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7341 if (OpOpcode == ISD::TRUNCATE) {
7342 SDValue OpOp = N1.getOperand(0);
7343 if (OpOp.getValueType() == VT) {
7344 unsigned NumSignExtBits =
7346 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7347 transferDbgValues(N1, OpOp);
7348 return OpOp;
7349 }
7350 }
7351 }
7352 break;
7353 case ISD::ZERO_EXTEND:
7354 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7355 "Invalid ZERO_EXTEND!");
7356 assert(VT.isVector() == N1.getValueType().isVector() &&
7357 "ZERO_EXTEND result type type should be vector iff the operand "
7358 "type is vector!");
7359 if (N1.getValueType() == VT) return N1; // noop extension
7360 assert((!VT.isVector() || VT.getVectorElementCount() ==
7362 "Vector element count mismatch!");
7363 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7364 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7365 SDNodeFlags Flags;
7366 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7367 SDValue NewVal =
7368 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7369 transferDbgValues(N1, NewVal);
7370 return NewVal;
7371 }
7372
7373 if (OpOpcode == ISD::POISON)
7374 return getPOISON(VT);
7375
7376 if (N1.isUndef())
7377 // zext(undef) = 0, because the top bits will be zero.
7378 return getConstant(0, DL, VT);
7379
7380 // Skip unnecessary zext_inreg pattern:
7381 // (zext (trunc x)) -> x iff the upper bits are known zero.
7382 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7383 // use to recognise zext_inreg patterns.
7384 if (OpOpcode == ISD::TRUNCATE) {
7385 SDValue OpOp = N1.getOperand(0);
7386 if (OpOp.getValueType() == VT) {
7387 if (OpOp.getOpcode() != ISD::AND) {
7390 if (MaskedValueIsZero(OpOp, HiBits)) {
7391 transferDbgValues(N1, OpOp);
7392 return OpOp;
7393 }
7394 }
7395 }
7396 }
7397 break;
7398 case ISD::ANY_EXTEND:
7399 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7400 "Invalid ANY_EXTEND!");
7401 assert(VT.isVector() == N1.getValueType().isVector() &&
7402 "ANY_EXTEND result type type should be vector iff the operand "
7403 "type is vector!");
7404 if (N1.getValueType() == VT) return N1; // noop extension
7405 assert((!VT.isVector() || VT.getVectorElementCount() ==
7407 "Vector element count mismatch!");
7408 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7409
7410 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7411 OpOpcode == ISD::ANY_EXTEND) {
7412 SDNodeFlags Flags;
7413 if (OpOpcode == ISD::ZERO_EXTEND)
7414 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7415 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7416 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7417 }
7418 if (N1.isUndef())
7419 return getUNDEF(VT);
7420
7421 // (ext (trunc x)) -> x
7422 if (OpOpcode == ISD::TRUNCATE) {
7423 SDValue OpOp = N1.getOperand(0);
7424 if (OpOp.getValueType() == VT) {
7425 transferDbgValues(N1, OpOp);
7426 return OpOp;
7427 }
7428 }
7429 break;
7430 case ISD::TRUNCATE:
7431 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7432 "Invalid TRUNCATE!");
7433 assert(VT.isVector() == N1.getValueType().isVector() &&
7434 "TRUNCATE result type type should be vector iff the operand "
7435 "type is vector!");
7436 if (N1.getValueType() == VT) return N1; // noop truncate
7437 assert((!VT.isVector() || VT.getVectorElementCount() ==
7439 "Vector element count mismatch!");
7440 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7441 if (OpOpcode == ISD::TRUNCATE)
7442 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7443 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7444 OpOpcode == ISD::ANY_EXTEND) {
7445 // If the source is smaller than the dest, we still need an extend.
7447 VT.getScalarType())) {
7448 SDNodeFlags Flags;
7449 if (OpOpcode == ISD::ZERO_EXTEND)
7450 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7451 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7452 }
7453 if (N1.getOperand(0).getValueType().bitsGT(VT))
7454 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7455 return N1.getOperand(0);
7456 }
7457 if (N1.isUndef())
7458 return getUNDEF(VT);
7459 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7460 return getVScale(DL, VT,
7462 break;
7466 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7467 assert(N1.getValueType().bitsLE(VT) &&
7468 "The input must be the same size or smaller than the result.");
7471 "The destination vector type must have fewer lanes than the input.");
7472 break;
7473 case ISD::ABS:
7474 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7475 if (N1.isUndef())
7476 return getConstant(0, DL, VT);
7477 break;
7479 assert(VT.isInteger() && VT == N1.getValueType() &&
7480 "Invalid ABS_MIN_POISON!");
7481 if (N1.isUndef())
7482 return getConstant(0, DL, VT);
7483 break;
7484 case ISD::BSWAP:
7485 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7486 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7487 "BSWAP types must be a multiple of 16 bits!");
7488 if (N1.isUndef())
7489 return getUNDEF(VT);
7490 // bswap(bswap(X)) -> X.
7491 if (OpOpcode == ISD::BSWAP)
7492 return N1.getOperand(0);
7493 break;
7494 case ISD::BITREVERSE:
7495 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7496 if (N1.isUndef())
7497 return getUNDEF(VT);
7498 break;
7499 case ISD::BITCAST:
7501 "Cannot BITCAST between types of different sizes!");
7502 if (VT == N1.getValueType()) return N1; // noop conversion.
7503 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7504 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7505 if (N1.isUndef())
7506 return getUNDEF(VT);
7507 break;
7509 assert(VT.isVector() && !N1.getValueType().isVector() &&
7510 (VT.getVectorElementType() == N1.getValueType() ||
7512 N1.getValueType().isInteger() &&
7514 "Illegal SCALAR_TO_VECTOR node!");
7515 if (N1.isUndef())
7516 return getUNDEF(VT);
7517 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7518 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7520 N1.getConstantOperandVal(1) == 0 &&
7521 N1.getOperand(0).getValueType() == VT)
7522 return N1.getOperand(0);
7523 break;
7524 case ISD::FNEG:
7525 // Negation of an unknown bag of bits is still completely undefined.
7526 if (N1.isUndef())
7527 return getUNDEF(VT);
7528
7529 if (OpOpcode == ISD::FNEG) // --X -> X
7530 return N1.getOperand(0);
7531 break;
7532 case ISD::FABS:
7533 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7534 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7535 break;
7536 case ISD::VSCALE:
7537 assert(VT == N1.getValueType() && "Unexpected VT!");
7538 break;
7539 case ISD::CTPOP:
7540 if (N1.getValueType().getScalarType() == MVT::i1)
7541 return N1;
7542 break;
7543 case ISD::CTLZ:
7544 case ISD::CTTZ:
7545 if (N1.getValueType().getScalarType() == MVT::i1)
7546 return getNOT(DL, N1, N1.getValueType());
7547 break;
7548 case ISD::CTLS:
7549 if (N1.getValueType().getScalarType() == MVT::i1)
7550 return getConstant(0, DL, VT);
7551 break;
7552 case ISD::VECREDUCE_ADD:
7553 if (N1.getValueType().getScalarType() == MVT::i1)
7554 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7555 break;
7558 if (N1.getValueType().getScalarType() == MVT::i1)
7559 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7560 break;
7563 if (N1.getValueType().getScalarType() == MVT::i1)
7564 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7565 break;
7567 // With a single lane, the result is true iff that lane is false.
7569 return getLogicalNOT(DL, N1, VT);
7570 break;
7571 case ISD::VECTOR_REPEAT:
7573 "VECTOR_REPEAT requires a fixed-length vector operand");
7574 assert(VT.isScalableVector() &&
7575 "VECTOR_REPEAT requires a scalable vector result");
7578 "VECTOR_REPEAT operand and result element counts must match");
7579 if (VT.getVectorMinNumElements() == 1)
7580 return getSplatVector(
7581 VT, DL, getExtractVectorElt(DL, VT.getVectorElementType(), N1, 0));
7582 break;
7583 case ISD::SPLAT_VECTOR:
7584 assert(VT.isVector() && "Wrong return type!");
7585 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7586 // that for now.
7588 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7590 N1.getValueType().isInteger() &&
7592 "Wrong operand type!");
7593 break;
7594 }
7595
7596 SDNode *N;
7597 SDVTList VTs = getVTList(VT);
7598 SDValue Ops[] = {N1};
7599 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7600 SDNodeKey ID(Opcode, VTs, Ops);
7601 FoldingSetInsertToken InsertToken;
7602 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7603 E->intersectFlagsWith(Flags);
7604 return SDValue(E, 0);
7605 }
7606
7607 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7608 N->setFlags(Flags);
7609 createOperands(N, Ops);
7610 CSEMap.insert(N, InsertToken);
7611 } else {
7612 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7613 createOperands(N, Ops);
7614 }
7615
7616 InsertNode(N);
7617 SDValue V = SDValue(N, 0);
7618 NewSDValueDbgMsg(V, "Creating new node: ", this);
7619 return V;
7620}
7621
7622static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7623 switch (Opcode) {
7624 default:
7625 llvm_unreachable("Unexpected integer identity opcode");
7626 case ISD::ADD:
7627 case ISD::OR:
7628 case ISD::XOR:
7629 case ISD::UMAX:
7630 return APInt::getZero(BitWidth);
7631 case ISD::MUL:
7632 return APInt(BitWidth, 1);
7633 case ISD::AND:
7634 case ISD::UMIN:
7636 case ISD::SMAX:
7638 case ISD::SMIN:
7640 }
7641}
7642
7643static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7644 const APInt &C2) {
7645 switch (Opcode) {
7646 case ISD::ADD: return C1 + C2;
7647 case ISD::SUB: return C1 - C2;
7648 case ISD::MUL: return C1 * C2;
7649 case ISD::AND: return C1 & C2;
7650 case ISD::OR: return C1 | C2;
7651 case ISD::XOR: return C1 ^ C2;
7652 case ISD::SHL: return C1 << C2;
7653 case ISD::SRL: return C1.lshr(C2);
7654 case ISD::SRA: return C1.ashr(C2);
7655 case ISD::ROTL: return C1.rotl(C2);
7656 case ISD::ROTR: return C1.rotr(C2);
7657 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7658 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7659 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7660 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7661 case ISD::SADDSAT: return C1.sadd_sat(C2);
7662 case ISD::UADDSAT: return C1.uadd_sat(C2);
7663 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7664 case ISD::USUBSAT: return C1.usub_sat(C2);
7665 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7666 case ISD::USHLSAT: return C1.ushl_sat(C2);
7667 case ISD::UDIV:
7668 if (!C2.getBoolValue())
7669 break;
7670 return C1.udiv(C2);
7671 case ISD::UREM:
7672 if (!C2.getBoolValue())
7673 break;
7674 return C1.urem(C2);
7675 case ISD::SDIV:
7676 if (!C2.getBoolValue())
7677 break;
7678 return C1.sdiv(C2);
7679 case ISD::SREM:
7680 if (!C2.getBoolValue())
7681 break;
7682 return C1.srem(C2);
7683 case ISD::AVGFLOORS:
7684 return APIntOps::avgFloorS(C1, C2);
7685 case ISD::AVGFLOORU:
7686 return APIntOps::avgFloorU(C1, C2);
7687 case ISD::AVGCEILS:
7688 return APIntOps::avgCeilS(C1, C2);
7689 case ISD::AVGCEILU:
7690 return APIntOps::avgCeilU(C1, C2);
7691 case ISD::AVGSUBFLOORS:
7692 return APIntOps::avgSubFloorS(C1, C2);
7693 case ISD::AVGSUBFLOORU:
7694 return APIntOps::avgSubFloorU(C1, C2);
7695 case ISD::ABDS:
7696 return APIntOps::abds(C1, C2);
7697 case ISD::ABDU:
7698 return APIntOps::abdu(C1, C2);
7699 case ISD::MULHS:
7700 return APIntOps::mulhs(C1, C2);
7701 case ISD::MULHU:
7702 return APIntOps::mulhu(C1, C2);
7703 case ISD::CLMUL:
7704 return APIntOps::clmul(C1, C2);
7705 case ISD::CLMULR:
7706 return APIntOps::clmulr(C1, C2);
7707 case ISD::CLMULH:
7708 return APIntOps::clmulh(C1, C2);
7709 case ISD::PEXT:
7710 return APIntOps::pext(C1, C2);
7711 case ISD::PDEP:
7712 return APIntOps::pdep(C1, C2);
7713 }
7714 return std::nullopt;
7715}
7716// Handle constant folding with UNDEF.
7717// TODO: Handle more cases.
7718static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7719 bool IsUndef1, const APInt &C2,
7720 bool IsUndef2) {
7721 if (!(IsUndef1 || IsUndef2))
7722 return FoldValue(Opcode, C1, C2);
7723
7724 // Fold and(x, undef) -> 0
7725 // Fold mul(x, undef) -> 0
7726 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7727 return APInt::getZero(C1.getBitWidth());
7728
7729 return std::nullopt;
7730}
7731
7733 const GlobalAddressSDNode *GA,
7734 const SDNode *N2) {
7735 if (GA->getOpcode() != ISD::GlobalAddress)
7736 return SDValue();
7737 if (!TLI->isOffsetFoldingLegal(GA))
7738 return SDValue();
7739 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7740 if (!C2)
7741 return SDValue();
7742 int64_t Offset = C2->getSExtValue();
7743 switch (Opcode) {
7744 case ISD::ADD:
7745 case ISD::PTRADD:
7746 break;
7747 case ISD::SUB: Offset = -uint64_t(Offset); break;
7748 default: return SDValue();
7749 }
7750 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7751 GA->getOffset() + uint64_t(Offset));
7752}
7753
7755 switch (Opcode) {
7756 case ISD::SDIV:
7757 case ISD::UDIV:
7758 case ISD::SREM:
7759 case ISD::UREM: {
7760 // If a divisor is zero/undef or any element of a divisor vector is
7761 // zero/undef, the whole op is undef.
7762 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7763 SDValue Divisor = Ops[1];
7764 if (Divisor.isUndef() || isNullConstant(Divisor))
7765 return true;
7766
7767 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7768 llvm::any_of(Divisor->op_values(),
7769 [](SDValue V) { return V.isUndef() ||
7770 isNullConstant(V); });
7771 // TODO: Handle signed overflow.
7772 }
7773 // TODO: Handle oversized shifts.
7774 default:
7775 return false;
7776 }
7777}
7778
7781 SDNodeFlags Flags) {
7782 // If the opcode is a target-specific ISD node, there's nothing we can
7783 // do here and the operand rules may not line up with the below, so
7784 // bail early.
7785 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7786 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7787 // foldCONCAT_VECTORS in getNode before this is called.
7788 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7789 return SDValue();
7790
7791 unsigned NumOps = Ops.size();
7792 if (NumOps == 0)
7793 return SDValue();
7794
7795 if (isUndef(Opcode, Ops))
7796 return getUNDEF(VT);
7797
7798 // Handle unary special cases.
7799 if (NumOps == 1) {
7800 SDValue N1 = Ops[0];
7801
7802 // Constant fold unary operations with an integer constant operand. Even
7803 // opaque constant will be folded, because the folding of unary operations
7804 // doesn't create new constants with different values. Nevertheless, the
7805 // opaque flag is preserved during folding to prevent future folding with
7806 // other constants.
7807 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7808 const APInt &Val = C->getAPIntValue();
7809 switch (Opcode) {
7810 case ISD::SIGN_EXTEND:
7811 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7812 C->isTargetOpcode(), C->isOpaque());
7813 case ISD::TRUNCATE:
7814 if (C->isOpaque())
7815 break;
7816 [[fallthrough]];
7817 case ISD::ZERO_EXTEND:
7818 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7819 C->isTargetOpcode(), C->isOpaque());
7820 case ISD::ANY_EXTEND:
7821 // Some targets like RISCV prefer to sign extend some types.
7822 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7823 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7824 C->isTargetOpcode(), C->isOpaque());
7825 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7826 C->isTargetOpcode(), C->isOpaque());
7827 case ISD::ABS:
7828 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7829 C->isOpaque());
7831 if (Val.isMinSignedValue())
7832 return getPOISON(VT);
7833 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7834 C->isOpaque());
7835 case ISD::BITREVERSE:
7836 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7837 C->isOpaque());
7838 case ISD::BSWAP:
7839 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7840 C->isOpaque());
7841 case ISD::CTPOP:
7842 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7843 C->isOpaque());
7844 case ISD::PARITY:
7845 return getConstant(Val.popcount() & 1, DL, VT, C->isTargetOpcode(),
7846 C->isOpaque());
7847 case ISD::CTLZ:
7849 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7850 C->isOpaque());
7851 case ISD::CTTZ:
7853 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7854 C->isOpaque());
7855 case ISD::CTLS:
7856 // CTLS returns the number of extra sign bits so subtract one.
7857 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7858 C->isTargetOpcode(), C->isOpaque());
7859 case ISD::UINT_TO_FP:
7860 case ISD::SINT_TO_FP: {
7862 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7864 return getConstantFP(FPV, DL, VT);
7865 }
7866 case ISD::FP16_TO_FP:
7867 case ISD::BF16_TO_FP: {
7868 bool Ignored;
7869 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7870 : APFloat::BFloat(),
7871 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7872
7873 // This can return overflow, underflow, or inexact; we don't care.
7874 // FIXME need to be more flexible about rounding mode.
7876 &Ignored);
7877 return getConstantFP(FPV, DL, VT);
7878 }
7879 case ISD::STEP_VECTOR:
7880 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7881 return V;
7882 break;
7883 case ISD::BITCAST:
7884 if (C->isOpaque())
7885 break;
7886 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7887 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7888 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7889 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7890 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7891 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7892 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7893 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7894 break;
7895 }
7896 }
7897
7898 // Constant fold unary operations with a floating point constant operand.
7899 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7900 APFloat V = C->getValueAPF(); // make copy
7901 switch (Opcode) {
7902 case ISD::FNEG:
7903 V.changeSign();
7904 return getConstantFP(V, DL, VT);
7905 case ISD::FABS:
7906 V.clearSign();
7907 return getConstantFP(V, DL, VT);
7908 case ISD::FCEIL: {
7909 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7911 return getConstantFP(V, DL, VT);
7912 return SDValue();
7913 }
7914 case ISD::FTRUNC: {
7915 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7917 return getConstantFP(V, DL, VT);
7918 return SDValue();
7919 }
7920 case ISD::FFLOOR: {
7921 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7923 return getConstantFP(V, DL, VT);
7924 return SDValue();
7925 }
7926 case ISD::FP_EXTEND: {
7927 bool ignored;
7928 // This can return overflow, underflow, or inexact; we don't care.
7929 // FIXME need to be more flexible about rounding mode.
7930 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7931 &ignored);
7932 return getConstantFP(V, DL, VT);
7933 }
7934 case ISD::FP_TO_SINT:
7935 case ISD::FP_TO_UINT: {
7936 bool ignored;
7937 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7938 // FIXME need to be more flexible about rounding mode.
7940 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7941 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7942 break;
7943 return getConstant(IntVal, DL, VT);
7944 }
7945 case ISD::FP_TO_FP16:
7946 case ISD::FP_TO_BF16: {
7947 bool Ignored;
7948 // This can return overflow, underflow, or inexact; we don't care.
7949 // FIXME need to be more flexible about rounding mode.
7950 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7951 : APFloat::BFloat(),
7953 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7954 }
7955 case ISD::BITCAST:
7956 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7957 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7958 VT);
7959 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7960 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7961 VT);
7962 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7963 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7964 VT);
7965 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7966 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7967 break;
7968 }
7969 }
7970
7971 // Early-out if we failed to constant fold a bitcast.
7972 if (Opcode == ISD::BITCAST)
7973 return SDValue();
7974
7975 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7976 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7977 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7978 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7979 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7980 Opcode == ISD::VECREDUCE_AND) &&
7982 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7983 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7984 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7985 for (SDValue Elt : N1->op_values()) {
7986 if (Elt.getOpcode() == ISD::POISON)
7987 return getPOISON(VT);
7988 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7989 return SDValue();
7990 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7991 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7992 assert(Folded &&
7993 "Expected vector reduction base opcode to be foldable");
7994 Acc = *Folded;
7995 }
7996 EVT EltVT = N1.getValueType().getScalarType();
7997 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7998 }
7999 }
8000
8001 // Handle binops special cases.
8002 if (NumOps == 2) {
8003 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
8004 return CFP;
8005
8006 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8007 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
8008 if (C1->isOpaque() || C2->isOpaque())
8009 return SDValue();
8010
8011 std::optional<APInt> FoldAttempt =
8012 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
8013 if (!FoldAttempt)
8014 return SDValue();
8015
8016 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
8017 assert((!Folded || !VT.isVector()) &&
8018 "Can't fold vectors ops with scalar operands");
8019 return Folded;
8020 }
8021 }
8022
8023 // fold (add Sym, c) -> Sym+c
8025 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
8026 if (TLI->isCommutativeBinOp(Opcode))
8028 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
8029
8030 // fold (sext_in_reg c1) -> c2
8031 if (Opcode == ISD::SIGN_EXTEND_INREG) {
8032 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
8033
8034 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
8035 unsigned FromBits = EVT.getScalarSizeInBits();
8036 Val <<= Val.getBitWidth() - FromBits;
8037 Val.ashrInPlace(Val.getBitWidth() - FromBits);
8038 return getConstant(Val, DL, ConstantVT);
8039 };
8040
8041 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8042 const APInt &Val = C1->getAPIntValue();
8043 return SignExtendInReg(Val, VT);
8044 }
8045
8047 SmallVector<SDValue, 8> ScalarOps;
8048 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
8049 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
8050 SDValue Op = Ops[0].getOperand(I);
8051 if (Op.isUndef()) {
8052 ScalarOps.push_back(getUNDEF(OpVT));
8053 continue;
8054 }
8055 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
8056 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
8057 }
8058 return getBuildVector(VT, DL, ScalarOps);
8059 }
8060
8061 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
8062 isa<ConstantSDNode>(Ops[0].getOperand(0)))
8063 return getNode(ISD::SPLAT_VECTOR, DL, VT,
8064 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
8065 Ops[0].getOperand(0).getValueType()));
8066 }
8067 }
8068
8069 // Handle fshl/fshr special cases.
8070 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
8071 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
8072 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
8073 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
8074
8075 if (C1 && C2 && C3) {
8076 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
8077 return SDValue();
8078 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
8079 &V3 = C3->getAPIntValue();
8080
8081 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
8082 : APIntOps::fshr(V1, V2, V3);
8083 return getConstant(FoldedVal, DL, VT);
8084 }
8085 }
8086
8087 // Handle fma/fmad special cases.
8088 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8089 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8090 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8091 Ops[2].getValueType() == VT && "FMA types must match!");
8095 if (C1 && C2 && C3) {
8096 APFloat V1 = C1->getValueAPF();
8097 const APFloat &V2 = C2->getValueAPF();
8098 const APFloat &V3 = C3->getValueAPF();
8099 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8100 V1.multiply(V2, APFloat::rmNearestTiesToEven);
8102 } else
8103 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
8104 return getConstantFP(V1, DL, VT);
8105 }
8106 }
8107
8108 // This is for vector folding only from here on.
8109 if (!VT.isVector())
8110 return SDValue();
8111
8112 // Constant fold integer partial reductions with constant BUILD_VECTOR
8113 // operands. The reduction order is deliberately unspecified. Use the same
8114 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
8115 // lane I contributes to accumulator lane I % NumAccElts.
8116 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
8117 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
8118 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
8119 // These nodes have no scalar form, so unsupported cases must not fall
8120 // through to generic per-lane vector folding.
8121 if (!llvm::all_of(Ops, [](SDValue Op) {
8122 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
8123 }))
8124 return SDValue();
8125
8126 unsigned AccEltBits = VT.getScalarSizeInBits();
8127 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8128 unsigned NumAccElts = VT.getVectorNumElements();
8129 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8130 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8131 BitVector PoisonElts(NumAccElts);
8132
8133 for (unsigned I = 0; I != NumAccElts; ++I) {
8134 SDValue Elt = Ops[0].getOperand(I);
8135 if (Elt.getOpcode() == ISD::POISON) {
8136 PoisonElts.set(I);
8137 continue;
8138 }
8139 auto *C = dyn_cast<ConstantSDNode>(Elt);
8140 if (!C || C->isOpaque())
8141 return SDValue();
8142 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8143 }
8144
8145 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8146 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8147 for (unsigned I = 0; I != NumInputElts; ++I) {
8148 const unsigned AccIdx = I % NumAccElts;
8149 SDValue LHSElt = Ops[1].getOperand(I);
8150 SDValue RHSElt = Ops[2].getOperand(I);
8151 if (LHSElt.getOpcode() == ISD::POISON ||
8152 RHSElt.getOpcode() == ISD::POISON) {
8153 PoisonElts.set(AccIdx);
8154 continue;
8155 }
8156
8157 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8158 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8159 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8160 return SDValue();
8161
8162 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8163 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8164 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8165 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8166 Results[AccIdx] += LHSVal * RHSVal;
8167 }
8168
8169 // After type legalization the vector element type may not be a legal
8170 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8171 // promoted legal scalar type instead, matching the generic per-lane path
8172 // below. Bail out if legalization would narrow the type, since the lane
8173 // value would not fit.
8174 EVT AccEltVT = VT.getVectorElementType();
8175 EVT LegalSVT = AccEltVT;
8176 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8177 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8178 if (LegalSVT.bitsLT(AccEltVT))
8179 return SDValue();
8180 }
8181
8182 SmallVector<SDValue, 8> ResultOps;
8183 for (unsigned I = 0; I != NumAccElts; ++I)
8184 ResultOps.push_back(
8185 PoisonElts[I] ? getPOISON(LegalSVT)
8186 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8187 DL, LegalSVT));
8188 return getBuildVector(VT, DL, ResultOps);
8189 }
8190
8191 ElementCount NumElts = VT.getVectorElementCount();
8192
8193 // See if we can fold through any bitcasted integer ops.
8194 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8195 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8196 (Ops[0].getOpcode() == ISD::BITCAST ||
8197 Ops[1].getOpcode() == ISD::BITCAST)) {
8200 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8201 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8202 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8203 N2.getValueType().isInteger()) {
8204 bool IsLE = getDataLayout().isLittleEndian();
8205 unsigned EltBits = VT.getScalarSizeInBits();
8206 SmallVector<APInt> RawBits1, RawBits2;
8207 BitVector UndefElts1, UndefElts2;
8208 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8209 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8210 SmallVector<APInt> RawBits;
8211 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8212 std::optional<APInt> Fold = FoldValueWithUndef(
8213 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8214 if (!Fold)
8215 break;
8216 RawBits.push_back(*Fold);
8217 }
8218 if (RawBits.size() == NumElts.getFixedValue()) {
8219 // We have constant folded, but we might need to cast this again back
8220 // to the original (possibly legalized) type.
8221 EVT BVVT, BVEltVT;
8222 if (N1.getValueType() == VT) {
8223 BVVT = N1.getValueType();
8224 BVEltVT = BV1->getOperand(0).getValueType();
8225 } else {
8226 BVVT = N2.getValueType();
8227 BVEltVT = BV2->getOperand(0).getValueType();
8228 }
8229 unsigned BVEltBits = BVEltVT.getSizeInBits();
8230 SmallVector<APInt> DstBits;
8231 BitVector DstUndefs;
8233 DstBits, RawBits, DstUndefs,
8234 BitVector(RawBits.size(), false));
8235 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8236 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8237 if (DstUndefs[I])
8238 continue;
8239 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8240 }
8241 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8242 }
8243 }
8244 }
8245 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8246 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8247 isa<ConstantSDNode>(N2)) {
8248 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8249 {N1, N2}, Flags))
8250 return getBitcast(VT, Res);
8251 }
8252 }
8253
8254 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8255 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8256 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8257 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8258 APInt RHSVal;
8259 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8260 APInt NewStep = Opcode == ISD::MUL
8261 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8262 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8263 return getStepVector(DL, VT, NewStep);
8264 }
8265 }
8266
8267 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8268 return !Op.getValueType().isVector() ||
8269 Op.getValueType().getVectorElementCount() == NumElts;
8270 };
8271
8272 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8273 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8274 Op.getOpcode() == ISD::BUILD_VECTOR ||
8275 Op.getOpcode() == ISD::SPLAT_VECTOR;
8276 };
8277
8278 // All operands must be vector types with the same number of elements as
8279 // the result type and must be either UNDEF or a build/splat vector
8280 // or UNDEF scalars.
8281 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8282 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8283 return SDValue();
8284
8285 // If we are comparing vectors, then the result needs to be a i1 boolean that
8286 // is then extended back to the legal result type depending on how booleans
8287 // are represented.
8288 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8289 ISD::NodeType ExtendCode =
8290 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8291 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8293
8294 // Find legal integer scalar type for constant promotion and
8295 // ensure that its scalar size is at least as large as source.
8296 EVT LegalSVT = VT.getScalarType();
8297 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8298 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8299 if (LegalSVT.bitsLT(VT.getScalarType()))
8300 return SDValue();
8301 }
8302
8303 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8304 // only have one operand to check. For fixed-length vector types we may have
8305 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8306 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8307
8308 // Constant fold each scalar lane separately.
8309 SmallVector<SDValue, 4> ScalarResults;
8310 for (unsigned I = 0; I != NumVectorElts; I++) {
8311 SmallVector<SDValue, 4> ScalarOps;
8312 for (SDValue Op : Ops) {
8313 EVT InSVT = Op.getValueType().getScalarType();
8314 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8315 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8316 if (Op.isUndef())
8317 ScalarOps.push_back(getUNDEF(InSVT));
8318 else
8319 ScalarOps.push_back(Op);
8320 continue;
8321 }
8322
8323 SDValue ScalarOp =
8324 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8325 EVT ScalarVT = ScalarOp.getValueType();
8326
8327 // Build vector (integer) scalar operands may need implicit
8328 // truncation - do this before constant folding.
8329 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8330 // Don't create illegally-typed nodes unless they're constants or undef
8331 // - if we fail to constant fold we can't guarantee the (dead) nodes
8332 // we're creating will be cleaned up before being visited for
8333 // legalization.
8334 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8335 !isa<ConstantSDNode>(ScalarOp) &&
8336 TLI->getTypeAction(*getContext(), InSVT) !=
8338 return SDValue();
8339 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8340 }
8341
8342 ScalarOps.push_back(ScalarOp);
8343 }
8344
8345 // Constant fold the scalar operands.
8346 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8347
8348 // Scalar folding only succeeded if the result is a constant or UNDEF.
8349 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8350 ScalarResult.getOpcode() != ISD::ConstantFP)
8351 return SDValue();
8352
8353 // Legalize the (integer) scalar constant if necessary. We only do
8354 // this once we know the folding succeeded, since otherwise we would
8355 // get a node with illegal type which has a user.
8356 if (LegalSVT != SVT)
8357 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8358
8359 ScalarResults.push_back(ScalarResult);
8360 }
8361
8362 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8363 : getBuildVector(VT, DL, ScalarResults);
8364 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8365 return V;
8366}
8367
8369 SDVTList VTList,
8371 SDNodeFlags Flags) {
8372 if (VTList.NumVTs == 1)
8373 return FoldConstantArithmetic(Opcode, DL, VTList.VTs[0], Ops, Flags);
8374
8375 switch (Opcode) {
8376 case ISD::SADDO:
8377 case ISD::UADDO:
8378 case ISD::SSUBO:
8379 case ISD::USUBO:
8380 case ISD::SMULO:
8381 case ISD::UMULO: {
8382 // TODO: Support non-splat vector constants.
8385 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8386 return SDValue();
8387
8388 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8389 bool Overflow;
8390 APInt Result;
8391 switch (Opcode) {
8392 default:
8393 llvm_unreachable("Unexpected overflow opcode");
8394 case ISD::SADDO:
8395 Result = V1.sadd_ov(V2, Overflow);
8396 break;
8397 case ISD::UADDO:
8398 Result = V1.uadd_ov(V2, Overflow);
8399 break;
8400 case ISD::SSUBO:
8401 Result = V1.ssub_ov(V2, Overflow);
8402 break;
8403 case ISD::USUBO:
8404 Result = V1.usub_ov(V2, Overflow);
8405 break;
8406 case ISD::SMULO:
8407 Result = V1.smul_ov(V2, Overflow);
8408 break;
8409 case ISD::UMULO:
8410 Result = V1.umul_ov(V2, Overflow);
8411 break;
8412 }
8413
8414 EVT VT = VTList.VTs[0];
8415 return getNode(ISD::MERGE_VALUES, DL, VTList,
8416 {getConstant(Result, DL, VT),
8417 getBoolConstant(Overflow, DL, VTList.VTs[1], VT)},
8418 Flags);
8419 }
8420 }
8421 return SDValue();
8422}
8423
8426 // TODO: Add support for unary/ternary fp opcodes.
8427 if (Ops.size() != 2)
8428 return SDValue();
8429
8430 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8431 // should. That will require dealing with a potentially non-default
8432 // rounding mode, checking the "opStatus" return value from the APFloat
8433 // math calculations, and possibly other variations.
8434 SDValue N1 = Ops[0];
8435 SDValue N2 = Ops[1];
8436 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8437 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8438 if (N1CFP && N2CFP) {
8439 APFloat C1 = N1CFP->getValueAPF(); // make copy
8440 const APFloat &C2 = N2CFP->getValueAPF();
8441 switch (Opcode) {
8442 case ISD::FADD:
8444 return getConstantFP(C1, DL, VT);
8445 case ISD::FSUB:
8446 C1.subtract(C2, APFloat::rmNearestTiesToEven);
8447 return getConstantFP(C1, DL, VT);
8448 case ISD::FMUL:
8449 C1.multiply(C2, APFloat::rmNearestTiesToEven);
8450 return getConstantFP(C1, DL, VT);
8451 case ISD::FDIV:
8452 C1.divide(C2, APFloat::rmNearestTiesToEven);
8453 return getConstantFP(C1, DL, VT);
8454 case ISD::FREM:
8455 C1.mod(C2);
8456 return getConstantFP(C1, DL, VT);
8457 case ISD::FCOPYSIGN:
8458 C1.copySign(C2);
8459 return getConstantFP(C1, DL, VT);
8460 case ISD::FMINNUM:
8461 return getConstantFP(minnum(C1, C2), DL, VT);
8462 case ISD::FMAXNUM:
8463 return getConstantFP(maxnum(C1, C2), DL, VT);
8464 case ISD::FMINIMUM:
8465 return getConstantFP(minimum(C1, C2), DL, VT);
8466 case ISD::FMAXIMUM:
8467 return getConstantFP(maximum(C1, C2), DL, VT);
8468 case ISD::FMINIMUMNUM:
8469 return getConstantFP(minimumnum(C1, C2), DL, VT);
8470 case ISD::FMAXIMUMNUM:
8471 return getConstantFP(maximumnum(C1, C2), DL, VT);
8472 default: break;
8473 }
8474 }
8475 if (N1CFP && Opcode == ISD::FP_ROUND) {
8476 APFloat C1 = N1CFP->getValueAPF(); // make copy
8477 bool Unused;
8478 // This can return overflow, underflow, or inexact; we don't care.
8479 // FIXME need to be more flexible about rounding mode.
8481 &Unused);
8482 return getConstantFP(C1, DL, VT);
8483 }
8484
8485 switch (Opcode) {
8486 case ISD::FSUB:
8487 // -0.0 - undef --> undef (consistent with "fneg undef")
8488 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8489 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8490 return getUNDEF(VT);
8491 [[fallthrough]];
8492
8493 case ISD::FADD:
8494 case ISD::FMUL:
8495 case ISD::FDIV:
8496 case ISD::FREM:
8497 // If both operands are undef, the result is undef. If 1 operand is undef,
8498 // the result is NaN. This should match the behavior of the IR optimizer.
8499 if (N1.isUndef() && N2.isUndef())
8500 return getUNDEF(VT);
8501 if (N1.isUndef() || N2.isUndef())
8503 }
8504 return SDValue();
8505}
8506
8508 const SDLoc &DL, EVT DstEltVT) {
8509 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8510
8511 // If this is already the right type, we're done.
8512 if (SrcEltVT == DstEltVT)
8513 return SDValue(BV, 0);
8514
8515 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8516 unsigned DstBitSize = DstEltVT.getSizeInBits();
8517
8518 // If this is a conversion of N elements of one type to N elements of another
8519 // type, convert each element. This handles FP<->INT cases.
8520 if (SrcBitSize == DstBitSize) {
8522 for (SDValue Op : BV->op_values()) {
8523 // If the vector element type is not legal, the BUILD_VECTOR operands
8524 // are promoted and implicitly truncated. Make that explicit here.
8525 if (Op.getValueType() != SrcEltVT)
8526 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8527 Ops.push_back(getBitcast(DstEltVT, Op));
8528 }
8529 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8531 return getBuildVector(VT, DL, Ops);
8532 }
8533
8534 // Otherwise, we're growing or shrinking the elements. To avoid having to
8535 // handle annoying details of growing/shrinking FP values, we convert them to
8536 // int first.
8537 if (SrcEltVT.isFloatingPoint()) {
8538 // Convert the input float vector to a int vector where the elements are the
8539 // same sizes.
8540 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8541 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8543 DstEltVT);
8544 return SDValue();
8545 }
8546
8547 // Now we know the input is an integer vector. If the output is a FP type,
8548 // convert to integer first, then to FP of the right size.
8549 if (DstEltVT.isFloatingPoint()) {
8550 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8551 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8553 DstEltVT);
8554 return SDValue();
8555 }
8556
8557 // Okay, we know the src/dst types are both integers of differing types.
8558 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8559
8560 // Extract the constant raw bit data.
8561 BitVector UndefElements;
8562 SmallVector<APInt> RawBits;
8563 bool IsLE = getDataLayout().isLittleEndian();
8564 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8565 return SDValue();
8566
8568 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8569 if (UndefElements[I])
8570 Ops.push_back(getUNDEF(DstEltVT));
8571 else
8572 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8573 }
8574
8575 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8576 return getBuildVector(VT, DL, Ops);
8577}
8578
8580 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8581
8582 // There's no need to assert on a byte-aligned pointer. All pointers are at
8583 // least byte aligned.
8584 if (A == Align(1))
8585 return Val;
8586
8587 SDVTList VTs = getVTList(Val.getValueType());
8588 SDValue Ops[] = {Val};
8589 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8590 ID.AddInteger(A.value());
8591
8592 FoldingSetInsertToken InsertToken;
8593 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8594 return SDValue(E, 0);
8595
8596 auto *N =
8597 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8598 createOperands(N, {Val});
8599
8600 CSEMap.insert(N, InsertToken);
8601 InsertNode(N);
8602
8603 SDValue V(N, 0);
8604 NewSDValueDbgMsg(V, "Creating new node: ", this);
8605 return V;
8606}
8607
8608SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8609 SDValue N1, SDValue N2) {
8610 SDNodeFlags Flags;
8611 if (Inserter)
8612 Flags = Inserter->getFlags();
8613 return getNode(Opcode, DL, VT, N1, N2, Flags);
8614}
8615
8617 SDValue &N2) const {
8618 if (!TLI->isCommutativeBinOp(Opcode))
8619 return;
8620
8621 // Canonicalize:
8622 // binop(const, nonconst) -> binop(nonconst, const)
8625 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8626 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8627 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8628 std::swap(N1, N2);
8629
8630 // Canonicalize:
8631 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8632 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8634 std::swap(N1, N2);
8635}
8636
8637SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8638 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8640 N2.getOpcode() != ISD::DELETED_NODE &&
8641 "Operand is DELETED_NODE!");
8642
8643 canonicalizeCommutativeBinop(Opcode, N1, N2);
8644
8645 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8646 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8647
8648 // Don't allow undefs in vector splats - we might be returning N2 when folding
8649 // to zero etc.
8650 ConstantSDNode *N2CV =
8651 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8652
8653 switch (Opcode) {
8654 default: break;
8655 case ISD::TokenFactor:
8656 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8657 N2.getValueType() == MVT::Other && "Invalid token factor!");
8658 // Fold trivial token factors.
8659 if (N1.getOpcode() == ISD::EntryToken) return N2;
8660 if (N2.getOpcode() == ISD::EntryToken) return N1;
8661 if (N1 == N2) return N1;
8662 break;
8663 case ISD::BUILD_VECTOR: {
8664 // Attempt to simplify BUILD_VECTOR.
8665 SDValue Ops[] = {N1, N2};
8666 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8667 return V;
8668 break;
8669 }
8670 case ISD::CONCAT_VECTORS: {
8671 SDValue Ops[] = {N1, N2};
8672 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8673 return V;
8674 break;
8675 }
8676 case ISD::AND:
8677 assert(VT.isInteger() && "This operator does not apply to FP types!");
8678 assert(N1.getValueType() == N2.getValueType() &&
8679 N1.getValueType() == VT && "Binary operator types must match!");
8680 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8681 // worth handling here.
8682 if (N2CV && N2CV->isZero())
8683 return N2;
8684 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8685 return N1;
8686 break;
8687 case ISD::OR:
8688 case ISD::XOR:
8689 case ISD::ADD:
8690 case ISD::PTRADD:
8691 case ISD::SUB:
8692 assert(VT.isInteger() && "This operator does not apply to FP types!");
8693 assert(N1.getValueType() == N2.getValueType() &&
8694 N1.getValueType() == VT && "Binary operator types must match!");
8695 // The equal operand types requirement is unnecessarily strong for PTRADD.
8696 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8697 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8698 // logic everywhere where PTRADDs may be folded or combined to properly
8699 // support them. If/when we introduce pointer types to the SDAG, we will
8700 // need to relax this constraint.
8701
8702 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8703 // it's worth handling here.
8704 if (N2CV && N2CV->isZero())
8705 return N1;
8706 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8707 VT.getScalarType() == MVT::i1)
8708 return getNode(ISD::XOR, DL, VT, N1, N2);
8709 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8710 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8711 N2.getOpcode() == ISD::VSCALE) {
8712 const APInt &C1 = N1->getConstantOperandAPInt(0);
8713 const APInt &C2 = N2->getConstantOperandAPInt(0);
8714 return getVScale(DL, VT, C1 + C2);
8715 }
8716 break;
8717 case ISD::MUL:
8718 assert(VT.isInteger() && "This operator does not apply to FP types!");
8719 assert(N1.getValueType() == N2.getValueType() &&
8720 N1.getValueType() == VT && "Binary operator types must match!");
8721 if (VT.getScalarType() == MVT::i1)
8722 return getNode(ISD::AND, DL, VT, N1, N2);
8723 if (N2CV && N2CV->isZero())
8724 return N2;
8725 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8726 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8727 const APInt &N2CImm = N2C->getAPIntValue();
8728 return getVScale(DL, VT, MulImm * N2CImm);
8729 }
8730 break;
8731 case ISD::UDIV:
8732 case ISD::UREM:
8733 case ISD::MULHU:
8734 case ISD::MULHS:
8735 case ISD::SDIV:
8736 case ISD::SREM:
8737 case ISD::SADDSAT:
8738 case ISD::SSUBSAT:
8739 case ISD::UADDSAT:
8740 case ISD::USUBSAT:
8741 assert(VT.isInteger() && "This operator does not apply to FP types!");
8742 assert(N1.getValueType() == N2.getValueType() &&
8743 N1.getValueType() == VT && "Binary operator types must match!");
8744 if (VT.getScalarType() == MVT::i1) {
8745 // fold (add_sat x, y) -> (or x, y) for bool types.
8746 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8747 return getNode(ISD::OR, DL, VT, N1, N2);
8748 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8749 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8750 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8751 // mulhs/mulhu on i1 are always 0: the high bit of the 2-bit product of
8752 // two booleans is never set. The i1 constant 1 is also -1, so folding
8753 // (mulhs x, 1) to (sra x, 0) in DAGCombiner would be wrong here.
8754 if (Opcode == ISD::MULHS || Opcode == ISD::MULHU)
8755 return getConstant(0, DL, VT);
8756 }
8757 break;
8758 case ISD::SCMP:
8759 case ISD::UCMP:
8760 assert(N1.getValueType() == N2.getValueType() &&
8761 "Types of operands of UCMP/SCMP must match");
8762 assert(N1.getValueType().isVector() == VT.isVector() &&
8763 "Operands and return type of must both be scalars or vectors");
8764 if (VT.isVector())
8767 "Result and operands must have the same number of elements");
8768 break;
8769 case ISD::AVGFLOORS:
8770 case ISD::AVGFLOORU:
8771 case ISD::AVGCEILS:
8772 case ISD::AVGCEILU:
8773 case ISD::AVGSUBFLOORS:
8774 case ISD::AVGSUBFLOORU:
8775 assert(VT.isInteger() && "This operator does not apply to FP types!");
8776 assert(N1.getValueType() == N2.getValueType() &&
8777 N1.getValueType() == VT && "Binary operator types must match!");
8778 break;
8779 case ISD::ABDS:
8780 case ISD::ABDU:
8781 assert(VT.isInteger() && "This operator does not apply to FP types!");
8782 assert(N1.getValueType() == N2.getValueType() &&
8783 N1.getValueType() == VT && "Binary operator types must match!");
8784 if (VT.getScalarType() == MVT::i1)
8785 return getNode(ISD::XOR, DL, VT, N1, N2);
8786 break;
8787 case ISD::SMIN:
8788 case ISD::UMAX:
8789 assert(VT.isInteger() && "This operator does not apply to FP types!");
8790 assert(N1.getValueType() == N2.getValueType() &&
8791 N1.getValueType() == VT && "Binary operator types must match!");
8792 if (VT.getScalarType() == MVT::i1)
8793 return getNode(ISD::OR, DL, VT, N1, N2);
8794 break;
8795 case ISD::SMAX:
8796 case ISD::UMIN:
8797 assert(VT.isInteger() && "This operator does not apply to FP types!");
8798 assert(N1.getValueType() == N2.getValueType() &&
8799 N1.getValueType() == VT && "Binary operator types must match!");
8800 if (VT.getScalarType() == MVT::i1)
8801 return getNode(ISD::AND, DL, VT, N1, N2);
8802 break;
8803 case ISD::FADD:
8804 case ISD::FSUB:
8805 case ISD::FMUL:
8806 case ISD::FDIV:
8807 case ISD::FREM:
8808 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8809 assert(N1.getValueType() == N2.getValueType() &&
8810 N1.getValueType() == VT && "Binary operator types must match!");
8811 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8812 return V;
8813 break;
8814 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8815 assert(N1.getValueType() == VT &&
8818 "Invalid FCOPYSIGN!");
8819 break;
8820 case ISD::SHL:
8821 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8822 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8823 const APInt &ShiftImm = N2C->getAPIntValue();
8824 return getVScale(DL, VT, MulImm << ShiftImm);
8825 }
8826 [[fallthrough]];
8827 case ISD::SRA:
8828 case ISD::SRL:
8829 if (SDValue V = simplifyShift(N1, N2))
8830 return V;
8831 [[fallthrough]];
8832 case ISD::ROTL:
8833 case ISD::ROTR:
8834 case ISD::SSHLSAT:
8835 case ISD::USHLSAT:
8836 assert(VT == N1.getValueType() &&
8837 "Shift operators return type must be the same as their first arg");
8838 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8839 "Shifts only work on integers");
8840 assert((!VT.isVector() || VT == N2.getValueType()) &&
8841 "Vector shift amounts must be in the same as their first arg");
8842 // Verify that the shift amount VT is big enough to hold valid shift
8843 // amounts. This catches things like trying to shift an i1024 value by an
8844 // i8, which is easy to fall into in generic code that uses
8845 // TLI.getShiftAmount().
8848 "Invalid use of small shift amount with oversized value!");
8849
8850 // Always fold shifts of i1 values so the code generator doesn't need to
8851 // handle them. Since we know the size of the shift has to be less than the
8852 // size of the value, the shift/rotate count is guaranteed to be zero.
8853 if (VT == MVT::i1)
8854 return N1;
8855 if (N2CV && N2CV->isZero())
8856 return N1;
8857 break;
8858 case ISD::FP_ROUND:
8860 VT.bitsLE(N1.getValueType()) && N2C &&
8861 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8862 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8863 if (N1.getValueType() == VT) return N1; // noop conversion.
8864 break;
8865 case ISD::IS_FPCLASS: {
8867 "IS_FPCLASS is used for a non-floating type");
8868 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8869 // is.fpclass(poison, mask) -> poison
8870 if (N1.getOpcode() == ISD::POISON)
8871 return getPOISON(VT);
8872 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8873 // If all tests are made, it doesn't matter what the value is.
8874 if ((Mask & fcAllFlags) == fcAllFlags)
8875 return getBoolConstant(true, DL, VT, N1.getValueType());
8876 if ((Mask & fcAllFlags) == 0)
8877 return getBoolConstant(false, DL, VT, N1.getValueType());
8878 break;
8879 }
8880 case ISD::AssertNoFPClass: {
8882 "AssertNoFPClass is used for a non-floating type");
8883 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8884 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8885 assert(llvm::to_underlying(NoFPClass) <=
8887 "FPClassTest value too large");
8888 (void)NoFPClass;
8889 break;
8890 }
8891 case ISD::AssertSext:
8892 case ISD::AssertZext: {
8893 EVT EVT = cast<VTSDNode>(N2)->getVT();
8894 assert(VT == N1.getValueType() && "Not an inreg extend!");
8895 assert(VT.isInteger() && EVT.isInteger() &&
8896 "Cannot *_EXTEND_INREG FP types");
8897 assert(!EVT.isVector() &&
8898 "AssertSExt/AssertZExt type should be the vector element type "
8899 "rather than the vector type!");
8900 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8901 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8902 break;
8903 }
8905 EVT EVT = cast<VTSDNode>(N2)->getVT();
8906 assert(VT == N1.getValueType() && "Not an inreg extend!");
8907 assert(VT.isInteger() && EVT.isInteger() &&
8908 "Cannot *_EXTEND_INREG FP types");
8909 assert(EVT.isVector() == VT.isVector() &&
8910 "SIGN_EXTEND_INREG type should be vector iff the operand "
8911 "type is vector!");
8912 assert((!EVT.isVector() ||
8914 "Vector element counts must match in SIGN_EXTEND_INREG");
8915 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8916 if (EVT == VT) return N1; // Not actually extending
8917 break;
8918 }
8920 case ISD::FP_TO_UINT_SAT: {
8921 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8922 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8923 assert(N1.getValueType().isVector() == VT.isVector() &&
8924 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8925 "vector!");
8926 assert((!VT.isVector() || VT.getVectorElementCount() ==
8928 "Vector element counts must match in FP_TO_*INT_SAT");
8929 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8930 "Type to saturate to must be a scalar.");
8931 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8932 "Not extending!");
8933 break;
8934 }
8937 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8938 element type of the vector.");
8939
8940 // Extract from an undefined value or using an undefined index is undefined.
8941 if (N1.isUndef() || N2.isUndef())
8942 return getUNDEF(VT);
8943
8944 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8945 // vectors. For scalable vectors we will provide appropriate support for
8946 // dealing with arbitrary indices.
8947 if (N2C && N1.getValueType().isFixedLengthVector() &&
8948 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8949 return getPOISON(VT);
8950
8951 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8952 // expanding copies of large vectors from registers. This only works for
8953 // fixed length vectors, since we need to know the exact number of
8954 // elements.
8955 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8957 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8958 return getExtractVectorElt(DL, VT,
8959 N1.getOperand(N2C->getZExtValue() / Factor),
8960 N2C->getZExtValue() % Factor);
8961 }
8962
8963 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8964 // lowering is expanding large vector constants.
8965 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8966 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8969 "BUILD_VECTOR used for scalable vectors");
8970 unsigned Index =
8971 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8972 SDValue Elt = N1.getOperand(Index);
8973
8974 if (VT != Elt.getValueType())
8975 // If the vector element type is not legal, the BUILD_VECTOR operands
8976 // are promoted and implicitly truncated, and the result implicitly
8977 // extended. Make that explicit here.
8978 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8979
8980 return Elt;
8981 }
8982
8983 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8984 // operations are lowered to scalars.
8985 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8986 // If the indices are the same, return the inserted element else
8987 // if the indices are known different, extract the element from
8988 // the original vector.
8989 SDValue N1Op2 = N1.getOperand(2);
8991
8992 if (N1Op2C && N2C) {
8993 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8994 if (VT == N1.getOperand(1).getValueType())
8995 return N1.getOperand(1);
8996 if (VT.isFloatingPoint()) {
8998 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8999 }
9000 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
9001 }
9002 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
9003 }
9004 }
9005
9006 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
9007 // when vector types are scalarized and v1iX is legal.
9008 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
9009 // Here we are completely ignoring the extract element index (N2),
9010 // which is fine for fixed width vectors, since any index other than 0
9011 // is undefined anyway. However, this cannot be ignored for scalable
9012 // vectors - in theory we could support this, but we don't want to do this
9013 // without a profitability check.
9014 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9016 N1.getValueType().getVectorNumElements() == 1) {
9017 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
9018 N1.getOperand(1));
9019 }
9020 break;
9022 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
9023 assert(!N1.getValueType().isVector() && !VT.isVector() &&
9024 (N1.getValueType().isInteger() == VT.isInteger()) &&
9025 N1.getValueType() != VT &&
9026 "Wrong types for EXTRACT_ELEMENT!");
9027
9028 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
9029 // 64-bit integers into 32-bit parts. Instead of building the extract of
9030 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
9031 if (N1.getOpcode() == ISD::BUILD_PAIR)
9032 return N1.getOperand(N2C->getZExtValue());
9033
9034 // EXTRACT_ELEMENT of a constant int is also very common.
9035 if (N1C) {
9036 unsigned ElementSize = VT.getSizeInBits();
9037 unsigned Shift = ElementSize * N2C->getZExtValue();
9038 const APInt &Val = N1C->getAPIntValue();
9039 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
9040 }
9041 break;
9043 EVT N1VT = N1.getValueType();
9044 assert(VT.isVector() && N1VT.isVector() &&
9045 "Extract subvector VTs must be vectors!");
9047 "Extract subvector VTs must have the same element type!");
9048 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
9049 "Cannot extract a scalable vector from a fixed length vector!");
9050 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9052 "Extract subvector must be from larger vector to smaller vector!");
9053 assert(N2C && "Extract subvector index must be a constant");
9054 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9055 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
9056 N1VT.getVectorMinNumElements()) &&
9057 "Extract subvector overflow!");
9058 assert(N2C->getAPIntValue().getBitWidth() ==
9059 TLI->getVectorIdxWidth(getDataLayout()) &&
9060 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
9061 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
9062 "Extract index is not a multiple of the output vector length");
9063
9064 // Trivial extraction.
9065 if (VT == N1VT)
9066 return N1;
9067
9068 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
9069 if (N1.isUndef())
9070 return getUNDEF(VT);
9071
9072 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
9073 // the concat have the same type as the extract.
9074 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9075 VT == N1.getOperand(0).getValueType()) {
9076 unsigned Factor = VT.getVectorMinNumElements();
9077 return N1.getOperand(N2C->getZExtValue() / Factor);
9078 }
9079
9080 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
9081 // during shuffle legalization.
9082 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
9083 VT == N1.getOperand(1).getValueType())
9084 return N1.getOperand(1);
9085 break;
9086 }
9087 }
9088
9089 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
9090 switch (Opcode) {
9091 case ISD::XOR:
9092 case ISD::ADD:
9093 case ISD::PTRADD:
9094 case ISD::SUB:
9096 case ISD::UDIV:
9097 case ISD::SDIV:
9098 case ISD::UREM:
9099 case ISD::SREM:
9100 case ISD::MUL:
9101 case ISD::AND:
9102 case ISD::SSUBSAT:
9103 case ISD::USUBSAT:
9104 case ISD::UMIN:
9105 case ISD::OR:
9106 case ISD::SADDSAT:
9107 case ISD::UADDSAT:
9108 case ISD::UMAX:
9109 case ISD::SMAX:
9110 case ISD::SMIN:
9111 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9112 return N2.getOpcode() == ISD::POISON ? N2 : N1;
9113 }
9114 }
9115
9116 // Canonicalize an UNDEF to the RHS, even over a constant.
9117 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
9118 if (TLI->isCommutativeBinOp(Opcode)) {
9119 std::swap(N1, N2);
9120 } else {
9121 switch (Opcode) {
9122 case ISD::PTRADD:
9123 case ISD::SUB:
9124 // fold op(undef, non_undef_arg2) -> undef.
9125 return N1;
9127 case ISD::UDIV:
9128 case ISD::SDIV:
9129 case ISD::UREM:
9130 case ISD::SREM:
9131 case ISD::SSUBSAT:
9132 case ISD::USUBSAT:
9133 // fold op(undef, non_undef_arg2) -> 0.
9134 return getConstant(0, DL, VT);
9135 }
9136 }
9137 }
9138
9139 // Fold a bunch of operators when the RHS is undef.
9140 if (N2.getOpcode() == ISD::UNDEF) {
9141 switch (Opcode) {
9142 case ISD::XOR:
9143 if (N1.getOpcode() == ISD::UNDEF)
9144 // Handle undef ^ undef -> 0 special case. This is a common
9145 // idiom (misuse).
9146 return getConstant(0, DL, VT);
9147 [[fallthrough]];
9148 case ISD::ADD:
9149 case ISD::PTRADD:
9150 case ISD::SUB:
9151 // fold op(arg1, undef) -> undef.
9152 return N2;
9153 case ISD::UDIV:
9154 case ISD::SDIV:
9155 case ISD::UREM:
9156 case ISD::SREM:
9157 // fold op(arg1, undef) -> poison.
9158 return getPOISON(VT);
9159 case ISD::MUL:
9160 case ISD::AND:
9161 case ISD::SSUBSAT:
9162 case ISD::USUBSAT:
9163 case ISD::UMIN:
9164 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
9165 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
9166 case ISD::OR:
9167 case ISD::SADDSAT:
9168 case ISD::UADDSAT:
9169 case ISD::UMAX:
9170 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
9171 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
9172 case ISD::SMAX:
9173 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
9174 return N1.getOpcode() == ISD::UNDEF
9175 ? N2
9176 : getConstant(
9178 VT);
9179 case ISD::SMIN:
9180 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
9181 return N1.getOpcode() == ISD::UNDEF
9182 ? N2
9183 : getConstant(
9185 VT);
9186 }
9187 }
9188
9189 // Perform trivial constant folding.
9190 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9191 return SV;
9192
9193 // Memoize this node if possible.
9194 SDNode *N;
9195 SDVTList VTs = getVTList(VT);
9196 SDValue Ops[] = {N1, N2};
9197 if (VT != MVT::Glue) {
9198 SDNodeKey ID(Opcode, VTs, Ops);
9199 FoldingSetInsertToken InsertToken;
9200 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9201 E->intersectFlagsWith(Flags);
9202 return SDValue(E, 0);
9203 }
9204
9205 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9206 N->setFlags(Flags);
9207 createOperands(N, Ops);
9208 CSEMap.insert(N, InsertToken);
9209 } else {
9210 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9211 createOperands(N, Ops);
9212 }
9213
9214 InsertNode(N);
9215 SDValue V = SDValue(N, 0);
9216 NewSDValueDbgMsg(V, "Creating new node: ", this);
9217 return V;
9218}
9219
9220SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9221 SDValue N1, SDValue N2, SDValue N3) {
9222 SDNodeFlags Flags;
9223 if (Inserter)
9224 Flags = Inserter->getFlags();
9225 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9226}
9227
9228SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9229 SDValue N1, SDValue N2, SDValue N3,
9230 const SDNodeFlags Flags) {
9232 N2.getOpcode() != ISD::DELETED_NODE &&
9233 N3.getOpcode() != ISD::DELETED_NODE &&
9234 "Operand is DELETED_NODE!");
9235 // Perform various simplifications.
9236 switch (Opcode) {
9237 case ISD::BUILD_VECTOR: {
9238 // Attempt to simplify BUILD_VECTOR.
9239 SDValue Ops[] = {N1, N2, N3};
9240 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9241 return V;
9242 break;
9243 }
9244 case ISD::CONCAT_VECTORS: {
9245 SDValue Ops[] = {N1, N2, N3};
9246 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9247 return V;
9248 break;
9249 }
9250 case ISD::SETCC: {
9251 assert(VT.isInteger() && "SETCC result type must be an integer!");
9252 assert(N1.getValueType() == N2.getValueType() &&
9253 "SETCC operands must have the same type!");
9254 assert(VT.isVector() == N1.getValueType().isVector() &&
9255 "SETCC type should be vector iff the operand type is vector!");
9256 assert((!VT.isVector() || VT.getVectorElementCount() ==
9258 "SETCC vector element counts must match!");
9259 // Use FoldSetCC to simplify SETCC's.
9260 if (SDValue V =
9261 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9262 return V;
9263 break;
9264 }
9265 case ISD::SELECT:
9266 case ISD::VSELECT:
9267 if (SDValue V = simplifySelect(N1, N2, N3))
9268 return V;
9269 break;
9271 llvm_unreachable("should use getVectorShuffle constructor!");
9273 if (isNullConstant(N3))
9274 return N1;
9275 break;
9277 if (isNullConstant(N3))
9278 return N2;
9279 break;
9281 assert(VT.isVector() && VT == N1.getValueType() &&
9282 "INSERT_VECTOR_ELT vector type mismatch");
9284 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9285 assert((!VT.isFloatingPoint() ||
9286 VT.getVectorElementType() == N2.getValueType()) &&
9287 "INSERT_VECTOR_ELT fp scalar type mismatch");
9288 assert((!VT.isInteger() ||
9290 "INSERT_VECTOR_ELT int scalar size mismatch");
9291
9292 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9293 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9294 // for scalable vectors where we will generate appropriate code to
9295 // deal with out-of-bounds cases correctly.
9296 if (N3C && VT.isFixedLengthVector() &&
9297 N3C->getZExtValue() >= VT.getVectorNumElements())
9298 return getUNDEF(VT);
9299
9300 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9301 if (N3.isUndef())
9302 return getUNDEF(VT);
9303
9304 // If inserting poison, just use the input vector.
9305 if (N2.getOpcode() == ISD::POISON)
9306 return N1;
9307
9308 // Inserting undef into undef/poison is still undef.
9309 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9310 return getUNDEF(VT);
9311
9312 // If the inserted element is an UNDEF, just use the input vector.
9313 // But not if skipping the insert could make the result more poisonous.
9314 if (N2.isUndef()) {
9315 if (N3C && VT.isFixedLengthVector()) {
9316 APInt EltMask =
9317 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9318 if (isGuaranteedNotToBePoison(N1, EltMask))
9319 return N1;
9320 } else if (isGuaranteedNotToBePoison(N1))
9321 return N1;
9322 }
9323 break;
9324 }
9325 case ISD::INSERT_SUBVECTOR: {
9326 // If inserting poison, just use the input vector,
9327 if (N2.getOpcode() == ISD::POISON)
9328 return N1;
9329
9330 // Inserting undef into undef/poison is still undef.
9331 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9332 return getUNDEF(VT);
9333
9334 EVT N2VT = N2.getValueType();
9335 assert(VT == N1.getValueType() &&
9336 "Dest and insert subvector source types must match!");
9337 assert(VT.isVector() && N2VT.isVector() &&
9338 "Insert subvector VTs must be vectors!");
9340 "Insert subvector VTs must have the same element type!");
9341 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9342 "Cannot insert a scalable vector into a fixed length vector!");
9343 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9345 "Insert subvector must be from smaller vector to larger vector!");
9347 "Insert subvector index must be constant");
9348 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9349 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9351 "Insert subvector overflow!");
9353 TLI->getVectorIdxWidth(getDataLayout()) &&
9354 "Constant index for INSERT_SUBVECTOR has an invalid size");
9355
9356 // Trivial insertion.
9357 if (VT == N2VT)
9358 return N2;
9359
9360 // If this is an insert of an extracted vector into an undef/poison vector,
9361 // we can just use the input to the extract. But not if skipping the
9362 // extract+insert could make the result more poisonous.
9363 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9364 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9365 if (N1.getOpcode() == ISD::POISON)
9366 return N2.getOperand(0);
9367 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9368 unsigned LoBit = N3->getAsZExtVal();
9369 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9370 APInt EltMask =
9371 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9372 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9373 return N2.getOperand(0);
9374 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9375 return N2.getOperand(0);
9376 }
9377
9378 // If the inserted subvector is UNDEF, just use the input vector.
9379 // But not if skipping the insert could make the result more poisonous.
9380 if (N2.isUndef()) {
9381 if (VT.isFixedLengthVector()) {
9382 unsigned LoBit = N3->getAsZExtVal();
9383 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9384 APInt EltMask =
9385 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9386 if (isGuaranteedNotToBePoison(N1, EltMask))
9387 return N1;
9388 } else if (isGuaranteedNotToBePoison(N1))
9389 return N1;
9390 }
9391 break;
9392 }
9393 case ISD::BITCAST:
9394 // Fold bit_convert nodes from a type to themselves.
9395 if (N1.getValueType() == VT)
9396 return N1;
9397 break;
9398 case ISD::VECTOR_COMPRESS: {
9399 [[maybe_unused]] EVT VecVT = N1.getValueType();
9400 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9401 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9402 assert(VT == VecVT && "Vector and result type don't match.");
9403 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9404 "All inputs must be vectors.");
9405 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9407 "Vector and mask must have same number of elements.");
9408
9409 if (N1.isUndef() || N2.isUndef())
9410 return N3;
9411
9412 break;
9413 }
9418 [[maybe_unused]] EVT AccVT = N1.getValueType();
9419 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9420 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9421 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9422 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9423 "node to have the same type!");
9424 assert(VT.isVector() && VT == AccVT &&
9425 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9426 "the same type as its result!");
9428 AccVT.getVectorElementCount()) &&
9429 "Expected the element count of the second and third operands of the "
9430 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9431 "element count of the first operand and the result!");
9433 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9434 "node to have an element type which is the same as or smaller than "
9435 "the element type of the first operand and result!");
9436 break;
9437 }
9438 }
9439
9440 // Perform trivial constant folding for arithmetic operators.
9441 switch (Opcode) {
9445 case ISD::FMA:
9446 case ISD::FMAD:
9447 case ISD::SETCC:
9448 case ISD::FSHL:
9449 case ISD::FSHR:
9450 if (SDValue SV =
9451 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9452 return SV;
9453 break;
9454 }
9455
9456 // Memoize node if it doesn't produce a glue result.
9457 SDNode *N;
9458 SDVTList VTs = getVTList(VT);
9459 SDValue Ops[] = {N1, N2, N3};
9460 if (VT != MVT::Glue) {
9461 SDNodeKey ID(Opcode, VTs, Ops);
9462 FoldingSetInsertToken InsertToken;
9463 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9464 E->intersectFlagsWith(Flags);
9465 return SDValue(E, 0);
9466 }
9467
9468 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9469 N->setFlags(Flags);
9470 createOperands(N, Ops);
9471 CSEMap.insert(N, InsertToken);
9472 } else {
9473 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9474 createOperands(N, Ops);
9475 }
9476
9477 InsertNode(N);
9478 SDValue V = SDValue(N, 0);
9479 NewSDValueDbgMsg(V, "Creating new node: ", this);
9480 return V;
9481}
9482
9483SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9484 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9485 const SDNodeFlags Flags) {
9486 SDValue Ops[] = { N1, N2, N3, N4 };
9487 return getNode(Opcode, DL, VT, Ops, Flags);
9488}
9489
9490SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9491 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9492 SDNodeFlags Flags;
9493 if (Inserter)
9494 Flags = Inserter->getFlags();
9495 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9496}
9497
9498SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9499 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9500 SDValue N5, const SDNodeFlags Flags) {
9501 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9502 return getNode(Opcode, DL, VT, Ops, Flags);
9503}
9504
9505SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9506 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9507 SDValue N5) {
9508 SDNodeFlags Flags;
9509 if (Inserter)
9510 Flags = Inserter->getFlags();
9511 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9512}
9513
9514/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9515/// the incoming stack arguments to be loaded from the stack.
9517 SmallVector<SDValue, 8> ArgChains;
9518
9519 // Include the original chain at the beginning of the list. When this is
9520 // used by target LowerCall hooks, this helps legalize find the
9521 // CALLSEQ_BEGIN node.
9522 ArgChains.push_back(Chain);
9523
9524 // Add a chain value for each stack argument.
9525 for (SDNode *U : getEntryNode().getNode()->users())
9526 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9527 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9528 if (FI->getIndex() < 0)
9529 ArgChains.push_back(SDValue(L, 1));
9530
9531 // Build a tokenfactor for all the chains.
9532 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9533}
9534
9535/// getMemsetValue - Vectorized representation of the memset value
9536/// operand.
9538 const SDLoc &dl) {
9539 assert(!Value.isUndef());
9540
9541 unsigned NumBits = VT.getScalarSizeInBits();
9543 assert(C->getAPIntValue().getBitWidth() == 8);
9544 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9545 if (VT.isInteger()) {
9546 bool IsOpaque = VT.getSizeInBits() > 64 ||
9547 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9548 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9549 }
9550 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9551 }
9552
9553 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9554 EVT IntVT = VT.getScalarType();
9555 if (!IntVT.isInteger())
9556 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9557
9558 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9559 if (NumBits > 8) {
9560 // Use a multiplication with 0x010101... to extend the input to the
9561 // required length.
9562 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9563 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9564 DAG.getConstant(Magic, dl, IntVT));
9565 }
9566
9567 if (VT != Value.getValueType() && !VT.isInteger())
9568 Value = DAG.getBitcast(VT.getScalarType(), Value);
9569 if (VT != Value.getValueType())
9570 Value = DAG.getSplatBuildVector(VT, dl, Value);
9571
9572 return Value;
9573}
9574
9575/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9576/// used when a memcpy is turned into a memset when the source is a constant
9577/// string ptr.
9579 const TargetLowering &TLI,
9580 const ConstantDataArraySlice &Slice) {
9581 // Handle vector with all elements zero.
9582 if (Slice.Array == nullptr) {
9583 if (VT.isInteger())
9584 return DAG.getConstant(0, dl, VT);
9585 return DAG.getNode(ISD::BITCAST, dl, VT,
9586 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9587 }
9588
9589 assert(!VT.isVector() && "Can't handle vector type here!");
9590 unsigned NumVTBits = VT.getSizeInBits();
9591 unsigned NumVTBytes = NumVTBits / 8;
9592 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9593
9594 APInt Val(NumVTBits, 0);
9595 if (DAG.getDataLayout().isLittleEndian()) {
9596 for (unsigned i = 0; i != NumBytes; ++i)
9597 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9598 } else {
9599 for (unsigned i = 0; i != NumBytes; ++i)
9600 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9601 }
9602
9603 // If the "cost" of materializing the integer immediate is less than the cost
9604 // of a load, then it is cost effective to turn the load into the immediate.
9605 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9606 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9607 return DAG.getConstant(Val, dl, VT);
9608 return SDValue();
9609}
9610
9612 const SDLoc &DL,
9613 const SDNodeFlags Flags) {
9614 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9615 return getMemBasePlusOffset(Base, Index, DL, Flags);
9616}
9617
9619 const SDLoc &DL,
9620 const SDNodeFlags Flags) {
9621 assert(Offset.getValueType().isInteger());
9622 EVT BasePtrVT = Ptr.getValueType();
9623 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9624 BasePtrVT))
9625 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9626 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9627 SDNodeFlags AddFlags = Flags;
9628 AddFlags.setInBounds(false);
9629 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9630}
9631
9632/// Returns true if memcpy source is constant data.
9634 uint64_t SrcDelta = 0;
9635 GlobalAddressSDNode *G = nullptr;
9636 if (Src.getOpcode() == ISD::GlobalAddress)
9638 else if (Src->isAnyAdd() &&
9639 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9640 Src.getOperand(1).getOpcode() == ISD::Constant) {
9641 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9642 SrcDelta = Src.getConstantOperandVal(1);
9643 }
9644 if (!G)
9645 return false;
9646
9647 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9648 SrcDelta + G->getOffset());
9649}
9650
9652 SelectionDAG &DAG) {
9653 // On Darwin, -Os means optimize for size without hurting performance, so
9654 // only really optimize for size when -Oz (MinSize) is used.
9656 return MF.getFunction().hasMinSize();
9657 return DAG.shouldOptForSize();
9658}
9659
9661 SmallVector<SDValue, 32> &OutChains, unsigned From,
9662 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9663 SmallVector<SDValue, 16> &OutStoreChains) {
9664 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9665 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9666 SmallVector<SDValue, 16> GluedLoadChains;
9667 for (unsigned i = From; i < To; ++i) {
9668 OutChains.push_back(OutLoadChains[i]);
9669 GluedLoadChains.push_back(OutLoadChains[i]);
9670 }
9671
9672 // Chain for all loads.
9673 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9674 GluedLoadChains);
9675
9676 for (unsigned i = From; i < To; ++i) {
9677 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9678 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9679 ST->getBasePtr(), ST->getMemoryVT(),
9680 ST->getMemOperand());
9681 OutChains.push_back(NewStore);
9682 }
9683}
9684
9685static SDValue
9687 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9688 Align SrcAlign, bool isVol, bool AlwaysInline,
9689 MachinePointerInfo DstPtrInfo,
9690 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9691 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9692 const MDNode *SrcMemCacheHint) {
9693 // Turn a memcpy of undef to nop.
9694 // FIXME: We need to honor volatile even is Src is undef.
9695 if (Src.isUndef())
9696 return Chain;
9697
9698 // Expand memcpy to a series of load and store ops if the size operand falls
9699 // below a certain threshold.
9700 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9701 // rather than maybe a humongous number of loads and stores.
9702 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9703 const DataLayout &DL = DAG.getDataLayout();
9704 LLVMContext &C = *DAG.getContext();
9705 std::vector<EVT> MemOps;
9706 bool DstAlignCanChange = false;
9708 MachineFrameInfo &MFI = MF.getFrameInfo();
9709 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9711 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9712 DstAlignCanChange = true;
9713 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9715 // If marked as volatile, perform a copy even when marked as constant.
9716 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9717 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9718 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9719 const MemOp Op = isZeroConstant
9720 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9721 /*IsZeroMemset*/ true, isVol)
9722 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9723 SrcAlign, isVol, CopyFromConstant);
9724 if (!TLI.findOptimalMemOpLowering(
9725 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9726 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9727 return SDValue();
9728
9729 if (DstAlignCanChange) {
9730 Type *Ty = MemOps[0].getTypeForEVT(C);
9731 Align NewDstAlign = DL.getABITypeAlign(Ty);
9732
9733 // Don't promote to an alignment that would require dynamic stack
9734 // realignment which may conflict with optimizations such as tail call
9735 // optimization.
9737 if (!TRI->hasStackRealignment(MF))
9738 if (MaybeAlign StackAlign = DL.getStackAlignment())
9739 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9740
9741 if (NewDstAlign > DstAlign) {
9742 // Give the stack frame object a larger alignment if needed.
9743 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9744 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9745 DstAlign = NewDstAlign;
9746 }
9747 }
9748
9749 // Prepare AAInfo for loads/stores after lowering this memcpy.
9750 AAMDNodes NewAAInfo = AAInfo;
9751 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9752
9753 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9754 bool isConstant =
9755 BatchAA && SrcVal &&
9756 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9757
9758 MachineMemOperand::Flags MMOFlags =
9760 SmallVector<SDValue, 16> OutLoadChains;
9761 SmallVector<SDValue, 16> OutStoreChains;
9762 SmallVector<SDValue, 32> OutChains;
9763 unsigned NumMemOps = MemOps.size();
9764 uint64_t SrcOff = 0, DstOff = 0;
9765 for (unsigned i = 0; i != NumMemOps; ++i) {
9766 EVT VT = MemOps[i];
9767 unsigned VTSize = VT.getSizeInBits() / 8;
9769
9770 if (VTSize > Size) {
9771 // Issuing an unaligned load / store pair that overlaps with the previous
9772 // pair. Adjust the offset accordingly.
9773 assert(i == NumMemOps-1 && i != 0);
9774 SrcOff -= VTSize - Size;
9775 DstOff -= VTSize - Size;
9776 }
9777
9778 if (CopyFromConstant &&
9779 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9780 // It's unlikely a store of a vector immediate can be done in a single
9781 // instruction. It would require a load from a constantpool first.
9782 // We only handle zero vectors here.
9783 // FIXME: Handle other cases where store of vector immediate is done in
9784 // a single instruction.
9785 ConstantDataArraySlice SubSlice;
9786 if (SrcOff < Slice.Length) {
9787 SubSlice = Slice;
9788 SubSlice.move(SrcOff);
9789 } else {
9790 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9791 SubSlice.Array = nullptr;
9792 SubSlice.Offset = 0;
9793 SubSlice.Length = VTSize;
9794 }
9795 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9796 if (Value.getNode()) {
9797 Store = DAG.getStore(
9798 Chain, dl, Value,
9799 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9800 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9801 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9802 OutChains.push_back(Store);
9803 }
9804 }
9805
9806 if (!Store.getNode()) {
9807 // The type might not be legal for the target. This should only happen
9808 // if the type is smaller than a legal type, as on PPC, so the right
9809 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9810 // to Load/Store if NVT==VT.
9811 // FIXME does the case above also need this?
9812 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9813 assert(NVT.bitsGE(VT));
9814
9815 bool isDereferenceable =
9816 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9817 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9818 if (isDereferenceable)
9820 if (isConstant)
9821 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9822
9823 Value = DAG.getExtLoad(
9824 ISD::EXTLOAD, dl, NVT, Chain,
9825 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9826 SrcPtrInfo.getWithOffset(SrcOff), VT,
9827 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9828 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9829 OutLoadChains.push_back(Value.getValue(1));
9830
9831 Store = DAG.getTruncStore(
9832 Chain, dl, Value,
9833 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9834 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9835 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9836 OutStoreChains.push_back(Store);
9837 }
9838 SrcOff += VTSize;
9839 DstOff += VTSize;
9840 Size -= VTSize;
9841 }
9842
9843 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9845 unsigned NumLdStInMemcpy = OutStoreChains.size();
9846
9847 if (NumLdStInMemcpy) {
9848 // It may be that memcpy might be converted to memset if it's memcpy
9849 // of constants. In such a case, we won't have loads and stores, but
9850 // just stores. In the absence of loads, there is nothing to gang up.
9851 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9852 // If target does not care, just leave as it.
9853 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9854 OutChains.push_back(OutLoadChains[i]);
9855 OutChains.push_back(OutStoreChains[i]);
9856 }
9857 } else {
9858 // Ld/St less than/equal limit set by target.
9859 if (NumLdStInMemcpy <= GluedLdStLimit) {
9860 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9861 NumLdStInMemcpy, OutLoadChains,
9862 OutStoreChains);
9863 } else {
9864 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9865 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9866 unsigned GlueIter = 0;
9867
9868 // Residual ld/st.
9869 if (RemainingLdStInMemcpy) {
9871 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9872 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9873 }
9874
9875 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9876 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9877 GlueIter - GluedLdStLimit;
9878 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9879 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9880 OutLoadChains, OutStoreChains);
9881 GlueIter += GluedLdStLimit;
9882 }
9883 }
9884 }
9885 }
9886 return DAG.getTokenFactor(dl, OutChains);
9887}
9888
9890 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9891 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9892 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9893 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9894 // Turn a memmove of undef to nop.
9895 // FIXME: We need to honor volatile even is Src is undef.
9896 if (Src.isUndef())
9897 return Chain;
9898
9899 // Expand memmove to a series of load and store ops if the size operand falls
9900 // below a certain threshold.
9901 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9902 const DataLayout &DL = DAG.getDataLayout();
9903 LLVMContext &C = *DAG.getContext();
9904 std::vector<EVT> MemOps;
9905 bool DstAlignCanChange = false;
9907 MachineFrameInfo &MFI = MF.getFrameInfo();
9908 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9910 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9911 DstAlignCanChange = true;
9912 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9913 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9914 if (!TLI.findOptimalMemOpLowering(
9915 C, MemOps, Limit,
9916 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9917 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9918 MF.getFunction().getAttributes(), nullptr))
9919 return SDValue();
9920
9921 if (DstAlignCanChange) {
9922 Type *Ty = MemOps[0].getTypeForEVT(C);
9923 Align NewDstAlign = DL.getABITypeAlign(Ty);
9924
9925 // Don't promote to an alignment that would require dynamic stack
9926 // realignment which may conflict with optimizations such as tail call
9927 // optimization.
9929 if (!TRI->hasStackRealignment(MF))
9930 if (MaybeAlign StackAlign = DL.getStackAlignment())
9931 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9932
9933 if (NewDstAlign > DstAlign) {
9934 // Give the stack frame object a larger alignment if needed.
9935 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9936 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9937 DstAlign = NewDstAlign;
9938 }
9939 }
9940
9941 // Prepare AAInfo for loads/stores after lowering this memmove.
9942 AAMDNodes NewAAInfo = AAInfo;
9943 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9944
9945 MachineMemOperand::Flags MMOFlags =
9947 uint64_t SrcOff = 0;
9948 SmallVector<SDValue, 8> LoadValues;
9949 SmallVector<SDValue, 8> LoadChains;
9950 SmallVector<SDValue, 8> OutChains;
9951 unsigned NumMemOps = MemOps.size();
9952 for (unsigned i = 0; i < NumMemOps; i++) {
9953 EVT VT = MemOps[i];
9954 unsigned VTSize = VT.getSizeInBits() / 8;
9955 SDValue Value;
9956 bool IsOverlapping = false;
9957
9958 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9959 // Issuing an unaligned load / store pair that overlaps with the previous
9960 // pair. Adjust the offset accordingly.
9961 SrcOff = Size - VTSize;
9962 IsOverlapping = true;
9963 }
9964
9965 // Calculate the actual alignment at the current offset. The alignment at
9966 // SrcOff may be lower than the base alignment, especially when using
9967 // overlapping loads.
9968 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9969 if (IsOverlapping) {
9970 // Verify that the target allows misaligned memory accesses at the
9971 // adjusted offset when using overlapping loads.
9972 unsigned Fast;
9973 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9974 SrcAlignAtOffset, MMOFlags,
9975 &Fast) ||
9976 !Fast) {
9977 // This should have been caught by findOptimalMemOpLowering, but verify
9978 // here for safety.
9979 return SDValue();
9980 }
9981 }
9982
9983 bool isDereferenceable =
9984 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9985 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9986 if (isDereferenceable)
9988 Value =
9989 DAG.getLoad(VT, dl, Chain,
9990 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9991 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9992 SrcMMOFlags, NewAAInfo);
9993 LoadValues.push_back(Value);
9994 LoadChains.push_back(Value.getValue(1));
9995 SrcOff += VTSize;
9996 }
9997 Chain = DAG.getTokenFactor(dl, LoadChains);
9998 OutChains.clear();
9999 uint64_t DstOff = 0;
10000 for (unsigned i = 0; i < NumMemOps; i++) {
10001 EVT VT = MemOps[i];
10002 unsigned VTSize = VT.getSizeInBits() / 8;
10003 SDValue Store;
10004 bool IsOverlapping = false;
10005
10006 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
10007 // Issuing an unaligned load / store pair that overlaps with the previous
10008 // pair. Adjust the offset accordingly.
10009 DstOff = Size - VTSize;
10010 IsOverlapping = true;
10011 }
10012
10013 // Calculate the actual alignment at the current offset. The alignment at
10014 // DstOff may be lower than the base alignment, especially when using
10015 // overlapping stores.
10016 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
10017 if (IsOverlapping) {
10018 // Verify that the target allows misaligned memory accesses at the
10019 // adjusted offset when using overlapping stores.
10020 unsigned Fast;
10021 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
10022 DstAlignAtOffset, MMOFlags,
10023 &Fast) ||
10024 !Fast) {
10025 // This should have been caught by findOptimalMemOpLowering, but verify
10026 // here for safety.
10027 return SDValue();
10028 }
10029 }
10030 Store = DAG.getStore(
10031 Chain, dl, LoadValues[i],
10032 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10033 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
10034 NewAAInfo);
10035 OutChains.push_back(Store);
10036 DstOff += VTSize;
10037 }
10038
10039 return DAG.getTokenFactor(dl, OutChains);
10040}
10041
10042/// Lower the call to 'memset' intrinsic function into a series of store
10043/// operations.
10044///
10045/// \param DAG Selection DAG where lowered code is placed.
10046/// \param dl Link to corresponding IR location.
10047/// \param Chain Control flow dependency.
10048/// \param Dst Pointer to destination memory location.
10049/// \param Src Value of byte to write into the memory.
10050/// \param Size Number of bytes to write.
10051/// \param Alignment Alignment of the destination in bytes.
10052/// \param isVol True if destination is volatile.
10053/// \param AlwaysInline Makes sure no function call is generated.
10054/// \param DstPtrInfo IR information on the memory pointer.
10055/// \returns New head in the control flow, if lowering was successful, empty
10056/// SDValue otherwise.
10057///
10058/// The function tries to replace 'llvm.memset' intrinsic with several store
10059/// operations and value calculation code. This is usually profitable for small
10060/// memory size or when the semantic requires inlining.
10062 SDValue Chain, SDValue Dst, SDValue Src,
10063 uint64_t Size, Align Alignment, bool isVol,
10064 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
10065 const AAMDNodes &AAInfo) {
10066 // Turn a memset of undef to nop.
10067 // FIXME: We need to honor volatile even is Src is undef.
10068 if (Src.isUndef())
10069 return Chain;
10070
10071 // Expand memset to a series of load/store ops if the size operand
10072 // falls below a certain threshold.
10073 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10074 std::vector<EVT> MemOps;
10075 bool DstAlignCanChange = false;
10076 LLVMContext &C = *DAG.getContext();
10078 MachineFrameInfo &MFI = MF.getFrameInfo();
10079 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10081 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10082 DstAlignCanChange = true;
10083 bool IsZeroVal = isNullConstant(Src);
10084 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
10085
10086 EVT LargestVT;
10087 if (!TLI.findOptimalMemOpLowering(
10088 C, MemOps, Limit,
10089 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
10090 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
10091 &LargestVT))
10092 return SDValue();
10093
10094 if (DstAlignCanChange) {
10095 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
10096 const DataLayout &DL = DAG.getDataLayout();
10097 Align NewAlign = DL.getABITypeAlign(Ty);
10098
10099 // Don't promote to an alignment that would require dynamic stack
10100 // realignment which may conflict with optimizations such as tail call
10101 // optimization.
10103 if (!TRI->hasStackRealignment(MF))
10104 if (MaybeAlign StackAlign = DL.getStackAlignment())
10105 NewAlign = std::min(NewAlign, *StackAlign);
10106
10107 if (NewAlign > Alignment) {
10108 // Give the stack frame object a larger alignment if needed.
10109 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
10110 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
10111 Alignment = NewAlign;
10112 }
10113 }
10114
10115 SmallVector<SDValue, 8> OutChains;
10116 uint64_t DstOff = 0;
10117 unsigned NumMemOps = MemOps.size();
10118
10119 // Find the largest store and generate the bit pattern for it.
10120 // If target didn't set LargestVT, compute it from MemOps.
10121 if (!LargestVT.isSimple()) {
10122 LargestVT = MemOps[0];
10123 for (unsigned i = 1; i < NumMemOps; i++)
10124 if (MemOps[i].bitsGT(LargestVT))
10125 LargestVT = MemOps[i];
10126 }
10127 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
10128
10129 // Prepare AAInfo for loads/stores after lowering this memset.
10130 AAMDNodes NewAAInfo = AAInfo;
10131 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10132
10133 for (unsigned i = 0; i < NumMemOps; i++) {
10134 EVT VT = MemOps[i];
10135 unsigned VTSize = VT.getSizeInBits() / 8;
10136 // The target should specify store types that exactly cover the memset size
10137 // (with the last store potentially being oversized for overlapping stores).
10138 assert(Size > 0 && "Target specified more stores than needed in "
10139 "findOptimalMemOpLowering");
10140 if (VTSize > Size) {
10141 // Issuing an unaligned load / store pair that overlaps with the previous
10142 // pair. Adjust the offset accordingly.
10143 assert(i == NumMemOps-1 && i != 0);
10144 DstOff -= VTSize - Size;
10145 }
10146
10147 // If this store is smaller than the largest store see whether we can get
10148 // the smaller value for free with a truncate or extract vector element and
10149 // then store.
10150 SDValue Value = MemSetValue;
10151 if (VT.bitsLT(LargestVT)) {
10152 unsigned Index;
10153 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
10154 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
10155 if (!LargestVT.isVector() && !VT.isVector() &&
10156 TLI.isTruncateFree(LargestVT, VT))
10157 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
10158 else if (LargestVT.isVector() && !VT.isVector() &&
10160 LargestVT.getTypeForEVT(*DAG.getContext()),
10161 VT.getSizeInBits(), Index) &&
10162 TLI.isTypeLegal(SVT) &&
10163 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
10164 // Target which can combine store(extractelement VectorTy, Idx) can get
10165 // the smaller value for free.
10166 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
10167 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
10168 } else
10169 Value = getMemsetValue(Src, VT, DAG, dl);
10170 }
10171 assert(Value.getValueType() == VT && "Value with wrong type.");
10172 SDValue Store = DAG.getStore(
10173 Chain, dl, Value,
10174 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10175 DstPtrInfo.getWithOffset(DstOff), Alignment,
10177 NewAAInfo);
10178 OutChains.push_back(Store);
10179 DstOff += VT.getSizeInBits() / 8;
10180 // For oversized overlapping stores, only subtract the remaining bytes.
10181 // For normal stores, subtract the full store size.
10182 if (VTSize > Size) {
10183 Size = 0;
10184 } else {
10185 Size -= VTSize;
10186 }
10187 }
10188
10189 // After processing all stores, Size should be exactly 0. Any remaining bytes
10190 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10191 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10192 "stores that exactly cover the memset size");
10193
10194 return DAG.getTokenFactor(dl, OutChains);
10195}
10196
10198 const DataLayout &DL, unsigned AS) {
10199 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10200 // pointer operands can be losslessly bitcasted to pointers of address space 0
10201 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(DL, AS, 0)) {
10202 report_fatal_error("cannot lower memory intrinsic in address space " +
10203 Twine(AS));
10204 }
10205}
10206
10207/// The length of a memory intrinsic (e.g. number of bytes to copy) is unsigned
10208/// and may have any integer type. We zero-extend or truncate it to the pointer
10209/// type of the narrower address space being accessed.
10211 SDValue Size, unsigned DstAS,
10212 unsigned SrcAS) {
10213 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10214 MVT DstVT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
10215 MVT SrcVT = TLI.getPointerTy(DAG.getDataLayout(), SrcAS);
10216 return DAG.getZExtOrTrunc(Size, dl, DstVT.bitsLT(SrcVT) ? DstVT : SrcVT);
10217}
10218
10220 const SelectionDAG *SelDAG,
10221 bool AllowReturnsFirstArg) {
10222 if (!CI || !CI->isTailCall())
10223 return false;
10224 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10225 // helper symbol we lower to.
10226 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10227 AllowReturnsFirstArg &&
10229}
10230
10231static std::pair<SDValue, SDValue>
10234 const CallInst *CI, RTLIB::Libcall Call,
10235 SelectionDAG *DAG, const TargetLowering *TLI) {
10236 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10237
10238 if (LCImpl == RTLIB::Unsupported)
10239 return {};
10240
10242 bool IsTailCall =
10243 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10244 // Lowering doesn't support tail calling inside a function with
10245 // a swifterror argument yet.
10246 !DAG->hasSwiftErrorArg();
10247 SDValue Callee =
10248 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10249
10250 CLI.setDebugLoc(dl)
10251 .setChain(Chain)
10253 CI->getType(), Callee, std::move(Args))
10254 .setTailCall(IsTailCall);
10255
10256 return TLI->LowerCallTo(CLI);
10257}
10258
10259std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10260 const SDLoc &dl, SDValue S1,
10261 SDValue S2,
10262 const CallInst *CI) {
10264 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10265 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10266 RTLIB::STRCMP, this, TLI);
10267}
10268
10269std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10270 const SDLoc &dl, SDValue S1,
10271 SDValue S2,
10272 const CallInst *CI) {
10274 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10275 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10276 RTLIB::STRSTR, this, TLI);
10277}
10278
10279std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10280 const SDLoc &dl,
10281 SDValue Dst, SDValue Src,
10283 const CallInst *CI) {
10285
10287 {Dst, PT},
10288 {Src, PT},
10291 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10292 RTLIB::MEMCCPY, this, TLI);
10293}
10294
10295std::pair<SDValue, SDValue>
10297 SDValue Mem1, SDValue Size, const CallInst *CI) {
10300 {Mem0, PT},
10301 {Mem1, PT},
10303 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10304 RTLIB::MEMCMP, this, TLI);
10305}
10306
10307std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10308 const SDLoc &dl,
10309 SDValue Dst, SDValue Src,
10310 const CallInst *CI) {
10312 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10313 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10314 RTLIB::STRCPY, this, TLI);
10315}
10316
10317std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10318 const SDLoc &dl,
10319 SDValue Src,
10320 const CallInst *CI) {
10321 // Emit a library call.
10324 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10325 RTLIB::STRLEN, this, TLI);
10326}
10327
10329 return TLI->supportSwiftError() &&
10330 MF->getFunction().getAttributes().hasAttrSomewhere(
10331 Attribute::SwiftError);
10332}
10333
10335 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10336 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10337 const CallInst *CI, std::optional<bool> OverrideTailCall,
10338 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10339 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10340 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10341 SrcPtrInfo.getAddrSpace());
10342 // Check to see if we should lower the memcpy to loads and stores first.
10343 // For cases within the target-specified limits, this is the best choice.
10344 const MDNode *DstMemCacheHint =
10345 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10346 const MDNode *SrcMemCacheHint =
10347 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10348
10350 if (ConstantSize) {
10351 // Memcpy with size zero? Just return the original chain.
10352 if (ConstantSize->isZero())
10353 return Chain;
10354
10356 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10357 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10358 DstMemCacheHint, SrcMemCacheHint);
10359 if (Result.getNode())
10360 return Result;
10361 }
10362
10363 // Then check to see if we should lower the memcpy with target-specific
10364 // code. If the target chooses to do this, this is the next best.
10365 if (TSI) {
10366 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10367 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10368 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10369 if (Result.getNode())
10370 return Result;
10371 }
10372
10373 // If we really need inline code and the target declined to provide it,
10374 // use a (potentially long) sequence of loads and stores.
10375 if (AlwaysInline) {
10376 assert(ConstantSize && "AlwaysInline requires a constant size!");
10378 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10379 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10380 DstMemCacheHint, SrcMemCacheHint);
10381 }
10382
10384 DstPtrInfo.getAddrSpace());
10386 SrcPtrInfo.getAddrSpace());
10387
10388 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10389 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10390 // respect volatile, so they may do things like read or write memory
10391 // beyond the given memory regions. But fixing this isn't easy, and most
10392 // people don't care.
10393
10394 // Emit a library call.
10397 Args.emplace_back(Dst, PtrTy);
10398 Args.emplace_back(Src, PtrTy);
10399 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10400 // FIXME: pass in SDLoc
10402 bool IsTailCall = false;
10403 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10404
10405 if (OverrideTailCall.has_value()) {
10406 IsTailCall = *OverrideTailCall;
10407 } else {
10408 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10409 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10410 }
10411 // Lowering doesn't support tail calling inside a function with a
10412 // swifterror argument yet.
10413 IsTailCall &= !hasSwiftErrorArg();
10414
10415 CLI.setDebugLoc(dl)
10416 .setChain(Chain)
10417 .setLibCallee(
10418 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10419 Dst.getValueType().getTypeForEVT(*getContext()),
10420 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10421 std::move(Args))
10423 .setTailCall(IsTailCall);
10424
10425 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10426 return CallResult.second;
10427}
10428
10431 const Module &M = *DAG->getMachineFunction().getFunction().getParent();
10432 Type *SizeTTy = DAG->getLibInfo().getSizeTType(M);
10434 DAG->getZExtOrTrunc(Size, dl, MVT::getVT(SizeTTy)), SizeTTy);
10435}
10436
10438 SDValue Dst, SDValue Src, SDValue Size,
10439 Type *SizeTy, unsigned ElemSz,
10440 bool isTailCall,
10441 MachinePointerInfo DstPtrInfo,
10442 MachinePointerInfo SrcPtrInfo) {
10443 // Lowering doesn't support tail calling inside a function with a
10444 // swifterror argument yet.
10445 isTailCall &= !hasSwiftErrorArg();
10446
10447 // Emit a library call.
10450 Args.emplace_back(Dst, ArgTy);
10451 Args.emplace_back(Src, ArgTy);
10452 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10453
10454 RTLIB::Libcall LibraryCall =
10456 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10457 if (LibcallImpl == RTLIB::Unsupported)
10458 report_fatal_error("Unsupported element size");
10459
10461 CLI.setDebugLoc(dl)
10462 .setChain(Chain)
10463 .setLibCallee(
10464 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10466 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10467 std::move(Args))
10469 .setTailCall(isTailCall);
10470
10471 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10472 return CallResult.second;
10473}
10474
10476 SDValue Src, SDValue Size, Align DstAlign,
10477 Align SrcAlign, bool isVol, const CallInst *CI,
10478 std::optional<bool> OverrideTailCall,
10479 MachinePointerInfo DstPtrInfo,
10480 MachinePointerInfo SrcPtrInfo,
10481 const AAMDNodes &AAInfo,
10482 BatchAAResults *BatchAA) {
10483 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10484 SrcPtrInfo.getAddrSpace());
10485 // Check to see if we should lower the memmove to loads and stores first.
10486 // For cases within the target-specified limits, this is the best choice.
10488 if (ConstantSize) {
10489 // Memmove with size zero? Just return the original chain.
10490 if (ConstantSize->isZero())
10491 return Chain;
10492
10494 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10495 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10496 if (Result.getNode())
10497 return Result;
10498 }
10499
10500 // Then check to see if we should lower the memmove with target-specific
10501 // code. If the target chooses to do this, this is the next best.
10502 if (TSI) {
10503 SDValue Result = TSI->EmitTargetCodeForMemmove(
10504 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10505 SrcPtrInfo);
10506 if (Result.getNode())
10507 return Result;
10508 }
10509
10511 DstPtrInfo.getAddrSpace());
10513 SrcPtrInfo.getAddrSpace());
10514
10515 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10516 // not be safe. See memcpy above for more details.
10517
10518 // Emit a library call.
10521 Args.emplace_back(Dst, PtrTy);
10522 Args.emplace_back(Src, PtrTy);
10523 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10524 // FIXME: pass in SDLoc
10526
10527 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10528
10529 bool IsTailCall = false;
10530 if (OverrideTailCall.has_value()) {
10531 IsTailCall = *OverrideTailCall;
10532 } else {
10533 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10534 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10535 }
10536 // Lowering doesn't support tail calling inside a function with a
10537 // swifterror argument yet.
10538 IsTailCall &= !hasSwiftErrorArg();
10539
10540 CLI.setDebugLoc(dl)
10541 .setChain(Chain)
10542 .setLibCallee(
10543 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10544 Dst.getValueType().getTypeForEVT(*getContext()),
10545 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10546 std::move(Args))
10548 .setTailCall(IsTailCall);
10549
10550 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10551 return CallResult.second;
10552}
10553
10555 SDValue Dst, SDValue Src, SDValue Size,
10556 Type *SizeTy, unsigned ElemSz,
10557 bool isTailCall,
10558 MachinePointerInfo DstPtrInfo,
10559 MachinePointerInfo SrcPtrInfo) {
10560 // Lowering doesn't support tail calling inside a function with a
10561 // swifterror argument yet.
10562 isTailCall &= !hasSwiftErrorArg();
10563
10564 // Emit a library call.
10567 Args.emplace_back(Dst, IntPtrTy);
10568 Args.emplace_back(Src, IntPtrTy);
10569 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10570
10571 RTLIB::Libcall LibraryCall =
10573 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10574 if (LibcallImpl == RTLIB::Unsupported)
10575 report_fatal_error("Unsupported element size");
10576
10578 CLI.setDebugLoc(dl)
10579 .setChain(Chain)
10580 .setLibCallee(
10581 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10583 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10584 std::move(Args))
10586 .setTailCall(isTailCall);
10587
10588 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10589 return CallResult.second;
10590}
10591
10593 SDValue Src, SDValue Size, Align Alignment,
10594 bool isVol, bool AlwaysInline,
10595 const CallInst *CI,
10596 MachinePointerInfo DstPtrInfo,
10597 const AAMDNodes &AAInfo) {
10598 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10599 DstPtrInfo.getAddrSpace());
10600 // Check to see if we should lower the memset to stores first.
10601 // For cases within the target-specified limits, this is the best choice.
10603 if (ConstantSize) {
10604 // Memset with size zero? Just return the original chain.
10605 if (ConstantSize->isZero())
10606 return Chain;
10607
10608 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10609 ConstantSize->getZExtValue(), Alignment,
10610 isVol, false, DstPtrInfo, AAInfo);
10611
10612 if (Result.getNode())
10613 return Result;
10614 }
10615
10616 // Then check to see if we should lower the memset with target-specific
10617 // code. If the target chooses to do this, this is the next best.
10618 if (TSI) {
10619 SDValue Result = TSI->EmitTargetCodeForMemset(
10620 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10621 if (Result.getNode())
10622 return Result;
10623 }
10624
10625 // If we really need inline code and the target declined to provide it,
10626 // use a (potentially long) sequence of loads and stores.
10627 if (AlwaysInline) {
10628 assert(ConstantSize && "AlwaysInline requires a constant size!");
10629 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10630 ConstantSize->getZExtValue(), Alignment,
10631 isVol, true, DstPtrInfo, AAInfo);
10632 assert(Result &&
10633 "getMemsetStores must return a valid sequence when AlwaysInline");
10634 return Result;
10635 }
10636
10638 DstPtrInfo.getAddrSpace());
10639
10640 // Emit a library call.
10641 auto &Ctx = *getContext();
10642 const auto& DL = getDataLayout();
10643
10645 // FIXME: pass in SDLoc
10646 CLI.setDebugLoc(dl).setChain(Chain);
10647
10648 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10649 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10650
10651 // If zeroing out and bzero is present, use it.
10652 if (UseBZero) {
10654 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10655 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10656 CLI.setLibCallee(
10657 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10658 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10659 } else {
10660 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10661
10662 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10664 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10665 Args.emplace_back(getAnyExtOrTrunc(Src, dl, IntVT),
10666 Type::getIntNTy(Ctx, LibInfo->getIntSize()),
10667 LibInfo->getExtAttrForI32Param());
10668 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10669
10670 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10671 Dst.getValueType().getTypeForEVT(Ctx),
10672 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10673 std::move(Args));
10674 }
10675
10676 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10677 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10678
10679 // If we're going to use bzero, make sure not to tail call unless the
10680 // subsequent return doesn't need a value, as bzero doesn't return the first
10681 // arg unlike memset.
10682 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10683 bool IsTailCall = CI && CI->isTailCall() &&
10685 ReturnsFirstArg && LowersToMemset) &&
10686 // Lowering doesn't support tail calling inside a function
10687 // with a swifterror argument yet.
10689 CLI.setDiscardResult().setTailCall(IsTailCall);
10690
10691 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10692 return CallResult.second;
10693}
10694
10697 Type *SizeTy, unsigned ElemSz,
10698 bool isTailCall,
10699 MachinePointerInfo DstPtrInfo) {
10700 // Lowering doesn't support tail calling inside a function with a
10701 // swifterror argument yet.
10702 isTailCall &= !hasSwiftErrorArg();
10703
10704 // Emit a library call.
10705 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10707 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10708 Args.emplace_back(getAnyExtOrTrunc(Value, dl, IntVT),
10709 Type::getIntNTy(*getContext(), LibInfo->getIntSize()),
10710 LibInfo->getExtAttrForI32Param());
10711 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10712
10713 RTLIB::Libcall LibraryCall =
10715 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10716 if (LibcallImpl == RTLIB::Unsupported)
10717 report_fatal_error("Unsupported element size");
10718
10720 CLI.setDebugLoc(dl)
10721 .setChain(Chain)
10722 .setLibCallee(
10723 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10725 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10726 std::move(Args))
10728 .setTailCall(isTailCall);
10729
10730 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10731 return CallResult.second;
10732}
10733
10734SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10736 MachineMemOperand *MMO,
10737 ISD::LoadExtType ExtType) {
10738 SDNodeKey ID(Opcode, VTList, Ops);
10739 ID.AddInteger(MemVT.getRawBits());
10740 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10741 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10742 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10743 ID.AddInteger(MMO->getFlags());
10744 FoldingSetInsertToken InsertToken;
10745 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10746 E->refineAlignment(MMO);
10747 E->refineMMOMetadata(MMO);
10748 return SDValue(E, 0);
10749 }
10750
10751 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10752 VTList, MemVT, MMO, ExtType);
10753 createOperands(N, Ops);
10754
10755 CSEMap.insert(N, InsertToken);
10756 InsertNode(N);
10757 SDValue V(N, 0);
10758 NewSDValueDbgMsg(V, "Creating new node: ", this);
10759 return V;
10760}
10761
10763 EVT MemVT, SDVTList VTs, SDValue Chain,
10764 SDValue Ptr, SDValue Cmp, SDValue Swp,
10765 MachineMemOperand *MMO) {
10766 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10768 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10769
10770 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10771 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10772}
10773
10774SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10775 SDValue Chain, SDValue Ptr, SDValue Val,
10776 MachineMemOperand *MMO) {
10777 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10778 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10779 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10780 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10781 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10782 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10783 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10784 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10785 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10786 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10787 Opcode == ISD::ATOMIC_LOAD_FMINIMUMNUM ||
10788 Opcode == ISD::ATOMIC_LOAD_FMAXIMUMNUM ||
10789 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10790 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10791 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10792 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10793 Opcode == ISD::ATOMIC_STORE) &&
10794 "Invalid Atomic Op");
10795
10796 EVT VT = Val.getValueType();
10797
10798 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10799 getVTList(VT, MVT::Other);
10800 SDValue Ops[] = {Chain, Ptr, Val};
10801 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10802}
10803
10805 EVT MemVT, EVT VT, SDValue Chain,
10806 SDValue Ptr, MachineMemOperand *MMO) {
10807 SDVTList VTs = getVTList(VT, MVT::Other);
10808 SDValue Ops[] = {Chain, Ptr};
10809 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10810}
10811
10812/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10814 if (Ops.size() == 1)
10815 return Ops[0];
10816
10818 VTs.reserve(Ops.size());
10819 for (const SDValue &Op : Ops)
10820 VTs.push_back(Op.getValueType());
10821 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10822}
10823
10825 SDValue Chain, const SDLoc &dl) {
10826 SmallVector<SDValue, 4> RetValues;
10827 RetValues.reserve(ResultTypes.size());
10828 for (EVT VT : ResultTypes)
10829 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10830 return getMergeValues(RetValues, dl);
10831}
10832
10834 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10835 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10837 const AAMDNodes &AAInfo) {
10838 if (Size.hasValue() && !Size.getValue())
10840
10842 MachineMemOperand *MMO =
10843 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10844
10845 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10846}
10847
10849 SDVTList VTList,
10850 ArrayRef<SDValue> Ops, EVT MemVT,
10851 MachineMemOperand *MMO) {
10852 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10853}
10854
10856 SDVTList VTList,
10857 ArrayRef<SDValue> Ops, EVT MemVT,
10859 assert(!MMOs.empty() && "Must have at least one MMO");
10860 assert(
10861 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10862 Opcode == ISD::PREFETCH ||
10863 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10864 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10865 "Opcode is not a memory-accessing opcode!");
10866
10868 if (MMOs.size() == 1) {
10869 MemRefs = MMOs[0];
10870 } else {
10871 // Allocate: [size_t count][MMO*][MMO*]...
10872 size_t AllocSize =
10873 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10874 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10875 size_t *CountPtr = static_cast<size_t *>(Buffer);
10876 *CountPtr = MMOs.size();
10877 MachineMemOperand **Array =
10878 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10879 llvm::copy(MMOs, Array);
10880 MemRefs = Array;
10881 }
10882
10883 // Memoize the node unless it returns a glue result.
10885 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10886 SDNodeKey ID(Opcode, VTList, Ops);
10887 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10888 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10889 ID.AddInteger(MemVT.getRawBits());
10890 for (const MachineMemOperand *MMO : MMOs) {
10891 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10892 ID.AddInteger(MMO->getFlags());
10893 }
10894 FoldingSetInsertToken InsertToken;
10895 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10896 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10897 return SDValue(E, 0);
10898 }
10899
10900 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10901 VTList, MemVT, MemRefs);
10902 createOperands(N, Ops);
10903 CSEMap.insert(N, InsertToken);
10904 } else {
10905 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10906 VTList, MemVT, MemRefs);
10907 createOperands(N, Ops);
10908 }
10909 InsertNode(N);
10910 SDValue V(N, 0);
10911 NewSDValueDbgMsg(V, "Creating new node: ", this);
10912 return V;
10913}
10914
10916 SDValue Chain, int FrameIndex) {
10917 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10918 const auto VTs = getVTList(MVT::Other);
10919 SDValue Ops[2] = {
10920 Chain,
10921 getFrameIndex(FrameIndex,
10922 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10923 true)};
10924
10925 SDNodeKey ID(Opcode, VTs, Ops);
10926 FoldingSetInsertToken InsertToken;
10927 if (SDNode *E = lookupNode(ID, dl, InsertToken))
10928 return SDValue(E, 0);
10929
10930 LifetimeSDNode *N =
10931 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10932 createOperands(N, Ops);
10933 CSEMap.insert(N, InsertToken);
10934 InsertNode(N);
10935 SDValue V(N, 0);
10936 NewSDValueDbgMsg(V, "Creating new node: ", this);
10937 return V;
10938}
10939
10941 uint64_t Guid, uint64_t Index,
10942 uint32_t Attr) {
10943 const unsigned Opcode = ISD::PSEUDO_PROBE;
10944 const auto VTs = getVTList(MVT::Other);
10945 SDValue Ops[] = {Chain};
10946 SDNodeKey ID(Opcode, VTs, Ops);
10947 ID.AddInteger(Guid);
10948 ID.AddInteger(Index);
10949 ID.AddInteger(Attr);
10950 FoldingSetInsertToken InsertToken;
10951 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
10952 return SDValue(E, 0);
10953
10954 auto *N = newSDNode<PseudoProbeSDNode>(
10955 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10956 createOperands(N, Ops);
10957 CSEMap.insert(N, InsertToken);
10958 InsertNode(N);
10959 SDValue V(N, 0);
10960 NewSDValueDbgMsg(V, "Creating new node: ", this);
10961 return V;
10962}
10963
10964/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10965/// MachinePointerInfo record from it. This is particularly useful because the
10966/// code generator has many cases where it doesn't bother passing in a
10967/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10969 SelectionDAG &DAG, SDValue Ptr,
10970 int64_t Offset = 0) {
10971 // If this is FI+Offset, we can model it.
10972 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10974 FI->getIndex(), Offset);
10975
10976 // If this is (FI+Offset1)+Offset2, we can model it.
10977 if (Ptr.getOpcode() != ISD::ADD ||
10980 return Info;
10981
10982 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10984 DAG.getMachineFunction(), FI,
10985 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10986}
10987
10988/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10989/// MachinePointerInfo record from it. This is particularly useful because the
10990/// code generator has many cases where it doesn't bother passing in a
10991/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10993 SelectionDAG &DAG, SDValue Ptr,
10994 SDValue OffsetOp) {
10995 // If the 'Offset' value isn't a constant, we can't handle this.
10997 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10998 if (OffsetOp.isUndef())
10999 return InferPointerInfo(Info, DAG, Ptr);
11000 return Info;
11001}
11002
11004 EVT VT, const SDLoc &dl, SDValue Chain,
11005 SDValue Ptr, SDValue Offset,
11006 MachinePointerInfo PtrInfo, EVT MemVT,
11007 Align Alignment,
11008 MachineMemOperand::Flags MMOFlags,
11009 const MMOMetadata &Metadata) {
11010 assert(Chain.getValueType() == MVT::Other &&
11011 "Invalid chain type");
11012
11013 MMOFlags |= MachineMemOperand::MOLoad;
11014 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11015 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11016 // clients.
11017 if (PtrInfo.V.isNull())
11018 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11019
11020 TypeSize Size = MemVT.getStoreSize();
11022 MachineMemOperand *MMO =
11023 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11024 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
11025}
11026
11028 EVT VT, const SDLoc &dl, SDValue Chain,
11029 SDValue Ptr, SDValue Offset, EVT MemVT,
11030 MachineMemOperand *MMO) {
11031 if (VT == MemVT) {
11032 ExtType = ISD::NON_EXTLOAD;
11033 } else if (ExtType == ISD::NON_EXTLOAD) {
11034 assert(VT == MemVT && "Non-extending load from different memory type!");
11035 } else {
11036 // Extending load.
11037 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
11038 "Should only be an extending load, not truncating!");
11039 assert(VT.isInteger() == MemVT.isInteger() &&
11040 "Cannot convert from FP to Int or Int -> FP!");
11041 assert(VT.isVector() == MemVT.isVector() &&
11042 "Cannot use an ext load to convert to or from a vector!");
11043 assert((!VT.isVector() ||
11045 "Cannot use an ext load to change the number of vector elements!");
11046 }
11047
11048 assert((!MMO->getRanges() ||
11050 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
11051 MemVT.isInteger())) &&
11052 "Range metadata and load type must match!");
11053
11054 bool Indexed = AM != ISD::UNINDEXED;
11055 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11056 "Unindexed load with an offset!");
11057
11058 SDVTList VTs = Indexed ?
11059 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
11060 SDValue Ops[] = { Chain, Ptr, Offset };
11061 SDNodeKey ID(ISD::LOAD, VTs, Ops);
11062 ID.AddInteger(MemVT.getRawBits());
11063 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
11064 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
11065 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11066 ID.AddInteger(MMO->getFlags());
11067 FoldingSetInsertToken InsertToken;
11068 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11069 E->refineAlignment(MMO);
11070 E->refineMMOMetadata(MMO);
11071 return SDValue(E, 0);
11072 }
11073 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11074 ExtType, MemVT, MMO);
11075 createOperands(N, Ops);
11076
11077 CSEMap.insert(N, InsertToken);
11078 InsertNode(N);
11079 SDValue V(N, 0);
11080 NewSDValueDbgMsg(V, "Creating new node: ", this);
11081 return V;
11082}
11083
11085 SDValue Ptr, MachinePointerInfo PtrInfo,
11086 MaybeAlign Alignment,
11087 MachineMemOperand::Flags MMOFlags,
11088 const MMOMetadata &Metadata) {
11090 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11091 PtrInfo, VT, Alignment, MMOFlags, Metadata);
11092}
11093
11095 SDValue Ptr, MachineMemOperand *MMO) {
11097 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11098 VT, MMO);
11099}
11100
11102 EVT VT, SDValue Chain, SDValue Ptr,
11103 MachinePointerInfo PtrInfo, EVT MemVT,
11104 MaybeAlign Alignment,
11105 MachineMemOperand::Flags MMOFlags,
11106 const MMOMetadata &Metadata) {
11108 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
11109 MemVT, Alignment, MMOFlags, Metadata);
11110}
11111
11113 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
11114 MachineMemOperand *MMO) {
11116 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
11117 MemVT, MMO);
11118}
11119
11123 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
11124 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11125 "Load is already a indexed load!");
11126 // Don't propagate the invariant or dereferenceable flags.
11127 auto MMOFlags =
11128 LD->getMemOperand()->getFlags() &
11130 return getLoad(
11131 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
11132 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
11133 MMOFlags,
11134 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
11135}
11136
11138 SDValue Ptr, MachinePointerInfo PtrInfo,
11139 Align Alignment,
11140 MachineMemOperand::Flags MMOFlags,
11141 const MMOMetadata &Metadata) {
11142 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11143
11144 MMOFlags |= MachineMemOperand::MOStore;
11145 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11146 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11147
11148 if (PtrInfo.V.isNull())
11149 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11150
11153 MachineMemOperand *MMO =
11154 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11155 return getStore(Chain, dl, Val, Ptr, MMO);
11156}
11157
11159 SDValue Ptr, MachineMemOperand *MMO) {
11161 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
11163}
11164
11166 SDValue Ptr, SDValue Offset, EVT SVT,
11168 bool IsTruncating) {
11169 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11170 EVT VT = Val.getValueType();
11171 if (VT == SVT) {
11172 IsTruncating = false;
11173 } else if (!IsTruncating) {
11174 assert(VT == SVT && "No-truncating store from different memory type!");
11175 } else {
11177 "Should only be a truncating store, not extending!");
11178 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11179 assert(VT.isVector() == SVT.isVector() &&
11180 "Cannot use trunc store to convert to or from a vector!");
11181 assert((!VT.isVector() ||
11183 "Cannot use trunc store to change the number of vector elements!");
11184 }
11185
11186 bool Indexed = AM != ISD::UNINDEXED;
11187 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11188 "Unindexed store with an offset!");
11189 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11190 : getVTList(MVT::Other);
11191 SDValue Ops[] = {Chain, Val, Ptr, Offset};
11192 SDNodeKey ID(ISD::STORE, VTs, Ops);
11193 ID.AddInteger(SVT.getRawBits());
11194 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
11195 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
11196 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11197 ID.AddInteger(MMO->getFlags());
11198 FoldingSetInsertToken InsertToken;
11199 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11200 cast<StoreSDNode>(E)->refineAlignment(MMO);
11201 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
11202 return SDValue(E, 0);
11203 }
11204 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11205 IsTruncating, SVT, MMO);
11206 createOperands(N, Ops);
11207
11208 CSEMap.insert(N, InsertToken);
11209 InsertNode(N);
11210 SDValue V(N, 0);
11211 NewSDValueDbgMsg(V, "Creating new node: ", this);
11212 return V;
11213}
11214
11216 SDValue Ptr, SDValue Offset,
11217 MachinePointerInfo PtrInfo, EVT SVT,
11218 Align Alignment,
11219 MachineMemOperand::Flags MMOFlags,
11220 const MMOMetadata &Metadata) {
11221 assert(Chain.getValueType() == MVT::Other &&
11222 "Invalid chain type");
11223
11224 MMOFlags |= MachineMemOperand::MOStore;
11225 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11226 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11227
11228 if (PtrInfo.V.isNull())
11229 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11230
11232 MachineMemOperand *MMO = MF.getMachineMemOperand(
11233 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11234 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11235}
11236
11238 SDValue Ptr, MachinePointerInfo PtrInfo,
11239 EVT SVT, Align Alignment,
11240 MachineMemOperand::Flags MMOFlags,
11241 const MMOMetadata &Metadata) {
11242 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11243 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11244}
11245
11247 SDValue Ptr, SDValue Offset, EVT SVT,
11248 MachineMemOperand *MMO) {
11249 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11250}
11251
11253 SDValue Ptr, EVT SVT,
11254 MachineMemOperand *MMO) {
11255 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11256 ISD::UNINDEXED, true);
11257}
11258
11262 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11263 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11264 "Store is already a indexed store!");
11265 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11266 ST->getMemoryVT(), ST->getMemOperand(), AM,
11267 ST->isTruncatingStore());
11268}
11269
11271 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11272 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11273 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11274 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11275 const MDNode *Ranges, bool IsExpanding) {
11276 MMOFlags |= MachineMemOperand::MOLoad;
11277 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11278 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11279 // clients.
11280 if (PtrInfo.V.isNull())
11281 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11282
11283 TypeSize Size = MemVT.getStoreSize();
11285 MachineMemOperand *MMO = MF.getMachineMemOperand(
11286 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11287 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11288 MMO, IsExpanding);
11289}
11290
11292 ISD::LoadExtType ExtType, EVT VT,
11293 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11294 SDValue Offset, SDValue Mask, SDValue EVL,
11295 EVT MemVT, MachineMemOperand *MMO,
11296 bool IsExpanding) {
11297 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11298 assert(Mask.getValueType().getVectorElementCount() ==
11299 VT.getVectorElementCount() &&
11300 "Vector width mismatch between mask and data");
11301
11302 bool Indexed = AM != ISD::UNINDEXED;
11303 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11304 "Unindexed load with an offset!");
11305
11306 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11307 : getVTList(VT, MVT::Other);
11308 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11309 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11310 ID.AddInteger(MemVT.getRawBits());
11311 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11312 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11313 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11314 ID.AddInteger(MMO->getFlags());
11315 FoldingSetInsertToken InsertToken;
11316 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11317 E->refineAlignment(MMO);
11318 E->refineMMOMetadata(MMO);
11319 return SDValue(E, 0);
11320 }
11321 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11322 ExtType, IsExpanding, MemVT, MMO);
11323 createOperands(N, Ops);
11324
11325 CSEMap.insert(N, InsertToken);
11326 InsertNode(N);
11327 SDValue V(N, 0);
11328 NewSDValueDbgMsg(V, "Creating new node: ", this);
11329 return V;
11330}
11331
11333 SDValue Ptr, SDValue Mask, SDValue EVL,
11334 MachinePointerInfo PtrInfo,
11335 MaybeAlign Alignment,
11336 MachineMemOperand::Flags MMOFlags,
11337 const AAMDNodes &AAInfo, const MDNode *Ranges,
11338 bool IsExpanding) {
11340 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11341 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11342 IsExpanding);
11343}
11344
11346 SDValue Ptr, SDValue Mask, SDValue EVL,
11347 MachineMemOperand *MMO, bool IsExpanding) {
11349 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11350 Mask, EVL, VT, MMO, IsExpanding);
11351}
11352
11354 EVT VT, SDValue Chain, SDValue Ptr,
11355 SDValue Mask, SDValue EVL,
11356 MachinePointerInfo PtrInfo, EVT MemVT,
11357 MaybeAlign Alignment,
11358 MachineMemOperand::Flags MMOFlags,
11359 const AAMDNodes &AAInfo, bool IsExpanding) {
11361 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11362 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11363 IsExpanding);
11364}
11365
11367 EVT VT, SDValue Chain, SDValue Ptr,
11368 SDValue Mask, SDValue EVL, EVT MemVT,
11369 MachineMemOperand *MMO, bool IsExpanding) {
11371 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11372 EVL, MemVT, MMO, IsExpanding);
11373}
11374
11376 SDValue Ptr, SDValue Offset, SDValue Mask,
11377 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11378 ISD::MemIndexedMode AM, bool IsTruncating,
11379 bool IsCompressing) {
11380 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11381 assert(Mask.getValueType().getVectorElementCount() ==
11383 "Vector width mismatch between mask and data");
11384
11385 bool Indexed = AM != ISD::UNINDEXED;
11386 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11387 "Unindexed vp_store with an offset!");
11388 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11389 : getVTList(MVT::Other);
11390 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11391 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11392 ID.AddInteger(MemVT.getRawBits());
11393 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11394 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11395 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11396 ID.AddInteger(MMO->getFlags());
11397 FoldingSetInsertToken InsertToken;
11398 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11399 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11400 return SDValue(E, 0);
11401 }
11402 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11403 IsTruncating, IsCompressing, MemVT, MMO);
11404 createOperands(N, Ops);
11405
11406 CSEMap.insert(N, InsertToken);
11407 InsertNode(N);
11408 SDValue V(N, 0);
11409 NewSDValueDbgMsg(V, "Creating new node: ", this);
11410 return V;
11411}
11412
11414 SDValue Val, SDValue Ptr, SDValue Mask,
11415 SDValue EVL, MachinePointerInfo PtrInfo,
11416 EVT SVT, Align Alignment,
11417 MachineMemOperand::Flags MMOFlags,
11418 const AAMDNodes &AAInfo,
11419 bool IsCompressing) {
11420 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11421
11422 MMOFlags |= MachineMemOperand::MOStore;
11423 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11424
11425 if (PtrInfo.V.isNull())
11426 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11427
11429 MachineMemOperand *MMO = MF.getMachineMemOperand(
11430 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11431 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11432 IsCompressing);
11433}
11434
11436 SDValue Val, SDValue Ptr, SDValue Mask,
11437 SDValue EVL, EVT SVT,
11438 MachineMemOperand *MMO,
11439 bool IsCompressing) {
11440 EVT VT = Val.getValueType();
11441
11442 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11443 if (VT == SVT)
11444 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11445 EVL, VT, MMO, ISD::UNINDEXED,
11446 /*IsTruncating*/ false, IsCompressing);
11447
11449 "Should only be a truncating store, not extending!");
11450 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11451 assert(VT.isVector() == SVT.isVector() &&
11452 "Cannot use trunc store to convert to or from a vector!");
11453 assert((!VT.isVector() ||
11455 "Cannot use trunc store to change the number of vector elements!");
11456
11457 SDVTList VTs = getVTList(MVT::Other);
11459 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11460 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11461 ID.AddInteger(SVT.getRawBits());
11462 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11463 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11464 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11465 ID.AddInteger(MMO->getFlags());
11466 FoldingSetInsertToken InsertToken;
11467 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11468 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11469 return SDValue(E, 0);
11470 }
11471 auto *N =
11472 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11473 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11474 createOperands(N, Ops);
11475
11476 CSEMap.insert(N, InsertToken);
11477 InsertNode(N);
11478 SDValue V(N, 0);
11479 NewSDValueDbgMsg(V, "Creating new node: ", this);
11480 return V;
11481}
11482
11484 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11485 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11486 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11487 bool Indexed = AM != ISD::UNINDEXED;
11488 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11489 "Unindexed load with an offset!");
11490
11491 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11492 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11493 : getVTList(VT, MVT::Other);
11494 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11495 ID.AddInteger(MemVT.getRawBits());
11496 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11497 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11498 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11499
11500 FoldingSetInsertToken InsertToken;
11501 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11502 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11503 return SDValue(E, 0);
11504 }
11505
11506 auto *N =
11507 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11508 ExtType, IsExpanding, MemVT, MMO);
11509 createOperands(N, Ops);
11510 CSEMap.insert(N, InsertToken);
11511 InsertNode(N);
11512 SDValue V(N, 0);
11513 NewSDValueDbgMsg(V, "Creating new node: ", this);
11514 return V;
11515}
11516
11518 SDValue Ptr, SDValue Stride,
11519 SDValue Mask, SDValue EVL,
11520 MachineMemOperand *MMO,
11521 bool IsExpanding) {
11523 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11524 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11525}
11526
11528 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11529 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11530 MachineMemOperand *MMO, bool IsExpanding) {
11532 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11533 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11534}
11535
11537 SDValue Val, SDValue Ptr,
11538 SDValue Offset, SDValue Stride,
11539 SDValue Mask, SDValue EVL, EVT MemVT,
11540 MachineMemOperand *MMO,
11542 bool IsTruncating, bool IsCompressing) {
11543 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11544 bool Indexed = AM != ISD::UNINDEXED;
11545 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11546 "Unindexed vp_store with an offset!");
11547 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11548 : getVTList(MVT::Other);
11549 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11550 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11551 ID.AddInteger(MemVT.getRawBits());
11552 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11553 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11554 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11555 FoldingSetInsertToken InsertToken;
11556 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11557 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11558 return SDValue(E, 0);
11559 }
11560 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11561 VTs, AM, IsTruncating,
11562 IsCompressing, MemVT, MMO);
11563 createOperands(N, Ops);
11564
11565 CSEMap.insert(N, InsertToken);
11566 InsertNode(N);
11567 SDValue V(N, 0);
11568 NewSDValueDbgMsg(V, "Creating new node: ", this);
11569 return V;
11570}
11571
11574 ISD::MemIndexType IndexType) {
11575 assert(Ops.size() == 6 && "Incompatible number of operands");
11576
11577 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11578 ID.AddInteger(VT.getRawBits());
11579 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11580 dl.getIROrder(), VTs, VT, MMO, IndexType));
11581 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11582 ID.AddInteger(MMO->getFlags());
11583 FoldingSetInsertToken InsertToken;
11584 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11585 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11586 return SDValue(E, 0);
11587 }
11588
11589 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11590 VT, MMO, IndexType);
11591 createOperands(N, Ops);
11592
11593 assert(N->getMask().getValueType().getVectorElementCount() ==
11594 N->getValueType(0).getVectorElementCount() &&
11595 "Vector width mismatch between mask and data");
11596 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11597 N->getValueType(0).getVectorElementCount().isScalable() &&
11598 "Scalable flags of index and data do not match");
11600 N->getIndex().getValueType().getVectorElementCount(),
11601 N->getValueType(0).getVectorElementCount()) &&
11602 "Vector width mismatch between index and data");
11603 assert(isa<ConstantSDNode>(N->getScale()) &&
11604 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11605 "Scale should be a constant power of 2");
11606
11607 CSEMap.insert(N, InsertToken);
11608 InsertNode(N);
11609 SDValue V(N, 0);
11610 NewSDValueDbgMsg(V, "Creating new node: ", this);
11611 return V;
11612}
11613
11616 MachineMemOperand *MMO,
11617 ISD::MemIndexType IndexType) {
11618 assert(Ops.size() == 7 && "Incompatible number of operands");
11619
11620 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11621 ID.AddInteger(VT.getRawBits());
11622 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11623 dl.getIROrder(), VTs, VT, MMO, IndexType));
11624 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11625 ID.AddInteger(MMO->getFlags());
11626 FoldingSetInsertToken InsertToken;
11627 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11628 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11629 return SDValue(E, 0);
11630 }
11631 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11632 VT, MMO, IndexType);
11633 createOperands(N, Ops);
11634
11635 assert(N->getMask().getValueType().getVectorElementCount() ==
11636 N->getValue().getValueType().getVectorElementCount() &&
11637 "Vector width mismatch between mask and data");
11638 assert(
11639 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11640 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11641 "Scalable flags of index and data do not match");
11643 N->getIndex().getValueType().getVectorElementCount(),
11644 N->getValue().getValueType().getVectorElementCount()) &&
11645 "Vector width mismatch between index and data");
11646 assert(isa<ConstantSDNode>(N->getScale()) &&
11647 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11648 "Scale should be a constant power of 2");
11649
11650 CSEMap.insert(N, InsertToken);
11651 InsertNode(N);
11652 SDValue V(N, 0);
11653 NewSDValueDbgMsg(V, "Creating new node: ", this);
11654 return V;
11655}
11656
11659 SDValue PassThru, EVT MemVT,
11660 MachineMemOperand *MMO,
11662 ISD::LoadExtType ExtTy, bool isExpanding) {
11663 bool Indexed = AM != ISD::UNINDEXED;
11664 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11665 "Unindexed masked load with an offset!");
11666 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11667 : getVTList(VT, MVT::Other);
11668 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11669 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11670 ID.AddInteger(MemVT.getRawBits());
11671 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11672 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11673 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11674 ID.AddInteger(MMO->getFlags());
11675 FoldingSetInsertToken InsertToken;
11676 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11677 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11678 return SDValue(E, 0);
11679 }
11680 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11681 AM, ExtTy, isExpanding, MemVT, MMO);
11682 createOperands(N, Ops);
11683
11684 CSEMap.insert(N, InsertToken);
11685 InsertNode(N);
11686 SDValue V(N, 0);
11687 NewSDValueDbgMsg(V, "Creating new node: ", this);
11688 return V;
11689}
11690
11695 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11696 "Masked load is already a indexed load!");
11697 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11698 Offset, LD->getMask(), LD->getPassThru(),
11699 LD->getMemoryVT(), LD->getMemOperand(), AM,
11700 LD->getExtensionType(), LD->isExpandingLoad());
11701}
11702
11705 SDValue Mask, EVT MemVT,
11706 MachineMemOperand *MMO,
11707 ISD::MemIndexedMode AM, bool IsTruncating,
11708 bool IsCompressing) {
11709 assert(Chain.getValueType() == MVT::Other &&
11710 "Invalid chain type");
11711 bool Indexed = AM != ISD::UNINDEXED;
11712 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11713 "Unindexed masked store with an offset!");
11714 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11715 : getVTList(MVT::Other);
11716 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11717 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11718 ID.AddInteger(MemVT.getRawBits());
11719 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11720 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11721 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11722 ID.AddInteger(MMO->getFlags());
11723 FoldingSetInsertToken InsertToken;
11724 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11725 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11726 return SDValue(E, 0);
11727 }
11728 auto *N =
11729 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11730 IsTruncating, IsCompressing, MemVT, MMO);
11731 createOperands(N, Ops);
11732
11733 CSEMap.insert(N, InsertToken);
11734 InsertNode(N);
11735 SDValue V(N, 0);
11736 NewSDValueDbgMsg(V, "Creating new node: ", this);
11737 return V;
11738}
11739
11744 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11745 "Masked store is already a indexed store!");
11746 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11747 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11748 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11749}
11750
11753 MachineMemOperand *MMO,
11754 ISD::MemIndexType IndexType,
11755 ISD::LoadExtType ExtTy) {
11756 assert(Ops.size() == 6 && "Incompatible number of operands");
11757
11758 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11759 ID.AddInteger(MemVT.getRawBits());
11760 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11761 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11762 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11763 ID.AddInteger(MMO->getFlags());
11764 FoldingSetInsertToken InsertToken;
11765 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11766 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11767 return SDValue(E, 0);
11768 }
11769
11770 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11771 VTs, MemVT, MMO, IndexType, ExtTy);
11772 createOperands(N, Ops);
11773
11774 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11775 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11776 assert(N->getMask().getValueType().getVectorElementCount() ==
11777 N->getValueType(0).getVectorElementCount() &&
11778 "Vector width mismatch between mask and data");
11779 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11780 N->getValueType(0).getVectorElementCount().isScalable() &&
11781 "Scalable flags of index and data do not match");
11783 N->getIndex().getValueType().getVectorElementCount(),
11784 N->getValueType(0).getVectorElementCount()) &&
11785 "Vector width mismatch between index and data");
11786 assert(isa<ConstantSDNode>(N->getScale()) &&
11787 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11788 "Scale should be a constant power of 2");
11789
11790 CSEMap.insert(N, InsertToken);
11791 InsertNode(N);
11792 SDValue V(N, 0);
11793 NewSDValueDbgMsg(V, "Creating new node: ", this);
11794 return V;
11795}
11796
11799 MachineMemOperand *MMO,
11800 ISD::MemIndexType IndexType,
11801 bool IsTrunc) {
11802 assert(Ops.size() == 6 && "Incompatible number of operands");
11803
11804 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11805 ID.AddInteger(MemVT.getRawBits());
11806 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11807 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11808 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11809 ID.AddInteger(MMO->getFlags());
11810 FoldingSetInsertToken InsertToken;
11811 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11812 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11813 return SDValue(E, 0);
11814 }
11815
11816 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11817 VTs, MemVT, MMO, IndexType, IsTrunc);
11818 createOperands(N, Ops);
11819
11820 assert(N->getMask().getValueType().getVectorElementCount() ==
11821 N->getValue().getValueType().getVectorElementCount() &&
11822 "Vector width mismatch between mask and data");
11823 assert(
11824 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11825 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11826 "Scalable flags of index and data do not match");
11828 N->getIndex().getValueType().getVectorElementCount(),
11829 N->getValue().getValueType().getVectorElementCount()) &&
11830 "Vector width mismatch between index and data");
11831 assert(isa<ConstantSDNode>(N->getScale()) &&
11832 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11833 "Scale should be a constant power of 2");
11834
11835 CSEMap.insert(N, InsertToken);
11836 InsertNode(N);
11837 SDValue V(N, 0);
11838 NewSDValueDbgMsg(V, "Creating new node: ", this);
11839 return V;
11840}
11841
11843 const SDLoc &dl, ArrayRef<SDValue> Ops,
11844 MachineMemOperand *MMO,
11845 ISD::MemIndexType IndexType) {
11846 assert(Ops.size() == 7 && "Incompatible number of operands");
11847
11849 ID.AddInteger(MemVT.getRawBits());
11850 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11851 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11852 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11853 ID.AddInteger(MMO->getFlags());
11854 FoldingSetInsertToken InsertToken;
11855 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11856 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11857 return SDValue(E, 0);
11858 }
11859
11860 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11861 VTs, MemVT, MMO, IndexType);
11862 createOperands(N, Ops);
11863
11864 assert(N->getMask().getValueType().getVectorElementCount() ==
11865 N->getIndex().getValueType().getVectorElementCount() &&
11866 "Vector width mismatch between mask and data");
11867 assert(isa<ConstantSDNode>(N->getScale()) &&
11868 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11869 "Scale should be a constant power of 2");
11870 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11871
11872 CSEMap.insert(N, InsertToken);
11873 InsertNode(N);
11874 SDValue V(N, 0);
11875 NewSDValueDbgMsg(V, "Creating new node: ", this);
11876 return V;
11877}
11878
11880 SDValue Ptr, SDValue Mask, SDValue EVL,
11881 MachineMemOperand *MMO) {
11882 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11883 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11884 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11885 ID.AddInteger(VT.getRawBits());
11886 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11887 VTs, VT, MMO));
11888 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11889 ID.AddInteger(MMO->getFlags());
11890 FoldingSetInsertToken InsertToken;
11891 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11892 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11893 return SDValue(E, 0);
11894 }
11895 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11896 VT, MMO);
11897 createOperands(N, Ops);
11898
11899 CSEMap.insert(N, InsertToken);
11900 InsertNode(N);
11901 SDValue V(N, 0);
11902 NewSDValueDbgMsg(V, "Creating new node: ", this);
11903 return V;
11904}
11905
11907 EVT MemVT, MachineMemOperand *MMO) {
11908 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11909 SDVTList VTs = getVTList(MVT::Other);
11910 SDValue Ops[] = {Chain, Ptr};
11912 ID.AddInteger(MemVT.getRawBits());
11913 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11914 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11915 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11916 ID.AddInteger(MMO->getFlags());
11917 FoldingSetInsertToken InsertToken;
11918 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11919 return SDValue(E, 0);
11920
11921 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11922 dl.getDebugLoc(), VTs, MemVT, MMO);
11923 createOperands(N, Ops);
11924
11925 CSEMap.insert(N, InsertToken);
11926 InsertNode(N);
11927 SDValue V(N, 0);
11928 NewSDValueDbgMsg(V, "Creating new node: ", this);
11929 return V;
11930}
11931
11933 EVT MemVT, MachineMemOperand *MMO) {
11934 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11935 SDVTList VTs = getVTList(MVT::Other);
11936 SDValue Ops[] = {Chain, Ptr};
11938 ID.AddInteger(MemVT.getRawBits());
11939 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11940 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11941 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11942 ID.AddInteger(MMO->getFlags());
11943 FoldingSetInsertToken InsertToken;
11944 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11945 return SDValue(E, 0);
11946
11947 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11948 dl.getDebugLoc(), VTs, MemVT, MMO);
11949 createOperands(N, Ops);
11950
11951 CSEMap.insert(N, InsertToken);
11952 InsertNode(N);
11953 SDValue V(N, 0);
11954 NewSDValueDbgMsg(V, "Creating new node: ", this);
11955 return V;
11956}
11957
11959 // select undef, T, F --> T (if T is a constant), otherwise F
11960 // select, ?, undef, F --> F
11961 // select, ?, T, undef --> T
11962 if (Cond.isUndef())
11963 return isConstantValueOfAnyType(T) ? T : F;
11964 if (T.isUndef())
11966 if (F.isUndef())
11968
11969 // select true, T, F --> T
11970 // select false, T, F --> F
11971 if (auto C = isBoolConstant(Cond))
11972 return *C ? T : F;
11973
11974 // select ?, T, T --> T
11975 if (T == F)
11976 return T;
11977
11978 return SDValue();
11979}
11980
11982 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11983 if (X.isUndef())
11984 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11985 // shift X, undef --> undef (because it may shift by the bitwidth)
11986 if (Y.isUndef())
11987 return getUNDEF(X.getValueType());
11988
11989 // shift 0, Y --> 0
11990 // shift X, 0 --> X
11992 return X;
11993
11994 // shift X, C >= bitwidth(X) --> undef
11995 // All vector elements must be too big (or undef) to avoid partial undefs.
11996 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11997 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11998 };
11999 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
12000 return getUNDEF(X.getValueType());
12001
12002 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
12003 if (X.getValueType().getScalarType() == MVT::i1)
12004 return X;
12005
12006 return SDValue();
12007}
12008
12010 SDNodeFlags Flags) {
12011 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
12012 // (an undef operand can be chosen to be Nan/Inf), then the result of this
12013 // operation is poison. That result can be relaxed to undef.
12014 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
12015 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
12016 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
12017 (YC && YC->getValueAPF().isNaN());
12018 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
12019 (YC && YC->getValueAPF().isInfinity());
12020
12021 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
12022 return getUNDEF(X.getValueType());
12023
12024 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
12025 return getUNDEF(X.getValueType());
12026
12027 if (!YC)
12028 return SDValue();
12029
12030 // X + -0.0 --> X
12031 if (Opcode == ISD::FADD)
12032 if (YC->getValueAPF().isNegZero())
12033 return X;
12034
12035 // X - +0.0 --> X
12036 if (Opcode == ISD::FSUB)
12037 if (YC->getValueAPF().isPosZero())
12038 return X;
12039
12040 // X * 1.0 --> X
12041 // X / 1.0 --> X
12042 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
12043 if (YC->getValueAPF().isOne())
12044 return X;
12045
12046 // X * 0.0 --> 0.0
12047 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
12048 if (YC->getValueAPF().isZero())
12049 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
12050
12051 return SDValue();
12052}
12053
12055 SDValue Ptr, SDValue SV, unsigned Align) {
12056 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
12057 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
12058}
12059
12060SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12062 switch (Ops.size()) {
12063 case 0: return getNode(Opcode, DL, VT);
12064 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
12065 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
12066 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
12067 default: break;
12068 }
12069
12070 // Copy from an SDUse array into an SDValue array for use with
12071 // the regular getNode logic.
12073 return getNode(Opcode, DL, VT, NewOps);
12074}
12075
12076SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12078 SDNodeFlags Flags;
12079 if (Inserter)
12080 Flags = Inserter->getFlags();
12081 return getNode(Opcode, DL, VT, Ops, Flags);
12082}
12083
12084SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12085 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12086 unsigned NumOps = Ops.size();
12087 switch (NumOps) {
12088 case 0: return getNode(Opcode, DL, VT);
12089 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
12090 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
12091 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
12092 default: break;
12093 }
12094
12095#ifndef NDEBUG
12096 for (const auto &Op : Ops)
12097 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12098 "Operand is DELETED_NODE!");
12099#endif
12100
12101 switch (Opcode) {
12102 default: break;
12103 case ISD::BUILD_VECTOR:
12104 // Attempt to simplify BUILD_VECTOR.
12105 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12106 return V;
12107 break;
12109 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12110 return V;
12111 break;
12112 case ISD::SELECT_CC:
12113 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12114 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12115 "LHS and RHS of condition must have same type!");
12116 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12117 "True and False arms of SelectCC must have same type!");
12118 assert(Ops[2].getValueType() == VT &&
12119 "select_cc node must be of same type as true and false value!");
12120 assert((!Ops[0].getValueType().isVector() ||
12121 Ops[0].getValueType().getVectorElementCount() ==
12122 VT.getVectorElementCount()) &&
12123 "Expected select_cc with vector result to have the same sized "
12124 "comparison type!");
12125 break;
12126 case ISD::BR_CC:
12127 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12128 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12129 "LHS/RHS of comparison should match types!");
12130 break;
12131 case ISD::VP_REDUCE_MUL:
12132 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12133 if (VT == MVT::i1)
12134 Opcode = ISD::VP_REDUCE_AND;
12135 break;
12136 case ISD::VP_REDUCE_ADD:
12137 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12138 if (VT == MVT::i1)
12139 Opcode = ISD::VP_REDUCE_XOR;
12140 break;
12141 case ISD::VP_REDUCE_SMAX:
12142 case ISD::VP_REDUCE_UMIN:
12143 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12144 // VP_REDUCE_AND.
12145 if (VT == MVT::i1)
12146 Opcode = ISD::VP_REDUCE_AND;
12147 break;
12148 case ISD::VP_REDUCE_SMIN:
12149 case ISD::VP_REDUCE_UMAX:
12150 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12151 // VP_REDUCE_OR.
12152 if (VT == MVT::i1)
12153 Opcode = ISD::VP_REDUCE_OR;
12154 break;
12155 }
12156
12157 // Memoize nodes.
12158 SDNode *N;
12159 SDVTList VTs = getVTList(VT);
12160
12161 if (VT != MVT::Glue) {
12162 SDNodeKey ID(Opcode, VTs, Ops);
12163 FoldingSetInsertToken InsertToken;
12164
12165 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12166 E->intersectFlagsWith(Flags);
12167 return SDValue(E, 0);
12168 }
12169
12170 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12171 createOperands(N, Ops);
12172
12173 CSEMap.insert(N, InsertToken);
12174 } else {
12175 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12176 createOperands(N, Ops);
12177 }
12178
12179 N->setFlags(Flags);
12180 InsertNode(N);
12181 SDValue V(N, 0);
12182 NewSDValueDbgMsg(V, "Creating new node: ", this);
12183 return V;
12184}
12185
12186SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12187 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12188 SDNodeFlags Flags;
12189 if (Inserter)
12190 Flags = Inserter->getFlags();
12191 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12192}
12193
12194SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12196 const SDNodeFlags Flags) {
12197 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12198}
12199
12200SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12202 SDNodeFlags Flags;
12203 if (Inserter)
12204 Flags = Inserter->getFlags();
12205 return getNode(Opcode, DL, VTList, Ops, Flags);
12206}
12207
12208SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12209 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12210 if (VTList.NumVTs == 1)
12211 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12212
12213#ifndef NDEBUG
12214 for (const auto &Op : Ops)
12215 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12216 "Operand is DELETED_NODE!");
12217#endif
12218
12219 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VTList, Ops, Flags))
12220 return V;
12221
12222 switch (Opcode) {
12223 case ISD::SADDO:
12224 case ISD::UADDO:
12225 case ISD::SSUBO:
12226 case ISD::USUBO: {
12227 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12228 "Invalid add/sub overflow op!");
12229 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12230 Ops[0].getValueType() == Ops[1].getValueType() &&
12231 Ops[0].getValueType() == VTList.VTs[0] &&
12232 "Binary operator types must match!");
12233 SDValue N1 = Ops[0], N2 = Ops[1];
12234 canonicalizeCommutativeBinop(Opcode, N1, N2);
12235
12236 // (X +- 0) -> X with zero-overflow.
12237 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12238 /*AllowTruncation*/ true);
12239 if (N2CV && N2CV->isZero()) {
12240 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12241 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12242 }
12243
12244 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12245 VTList.VTs[1].getScalarType() == MVT::i1) {
12246 SDValue F1 = getFreeze(N1);
12247 SDValue F2 = getFreeze(N2);
12248 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12249 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12250 return getNode(ISD::MERGE_VALUES, DL, VTList,
12251 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12252 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12253 Flags);
12254 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12255 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12256 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12257 return getNode(ISD::MERGE_VALUES, DL, VTList,
12258 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12259 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12260 Flags);
12261 }
12262 }
12263 break;
12264 }
12265 case ISD::SADDO_CARRY:
12266 case ISD::UADDO_CARRY:
12267 case ISD::SSUBO_CARRY:
12268 case ISD::USUBO_CARRY:
12269 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12270 "Invalid add/sub overflow op!");
12271 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12272 Ops[0].getValueType() == Ops[1].getValueType() &&
12273 Ops[0].getValueType() == VTList.VTs[0] &&
12274 Ops[2].getValueType() == VTList.VTs[1] &&
12275 "Binary operator types must match!");
12276 break;
12277 case ISD::SMUL_LOHI:
12278 case ISD::UMUL_LOHI: {
12279 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12280 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12281 VTList.VTs[0] == Ops[0].getValueType() &&
12282 VTList.VTs[0] == Ops[1].getValueType() &&
12283 "Binary operator types must match!");
12284 // Constant fold.
12287 if (LHS && RHS) {
12288 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12289 unsigned OutWidth = Width * 2;
12290 APInt Val = LHS->getAPIntValue();
12291 APInt Mul = RHS->getAPIntValue();
12292 if (Opcode == ISD::SMUL_LOHI) {
12293 Val = Val.sext(OutWidth);
12294 Mul = Mul.sext(OutWidth);
12295 } else {
12296 Val = Val.zext(OutWidth);
12297 Mul = Mul.zext(OutWidth);
12298 }
12299 Val *= Mul;
12300
12301 SDValue Hi =
12302 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12303 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12304 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12305 }
12306 break;
12307 }
12308 case ISD::FFREXP: {
12309 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12310 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12311 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12312
12314 int FrexpExp;
12315 APFloat FrexpMant =
12316 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12317 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12318 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12319 DL, VTList.VTs[1]);
12320 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12321 }
12322
12323 break;
12324 }
12326 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12327 "Invalid STRICT_FP_EXTEND!");
12328 assert(VTList.VTs[0].isFloatingPoint() &&
12329 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12330 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12331 "STRICT_FP_EXTEND result type should be vector iff the operand "
12332 "type is vector!");
12333 assert((!VTList.VTs[0].isVector() ||
12334 VTList.VTs[0].getVectorElementCount() ==
12335 Ops[1].getValueType().getVectorElementCount()) &&
12336 "Vector element count mismatch!");
12337 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12338 "Invalid fpext node, dst <= src!");
12339 break;
12341 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12342 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12343 "STRICT_FP_ROUND result type should be vector iff the operand "
12344 "type is vector!");
12345 assert((!VTList.VTs[0].isVector() ||
12346 VTList.VTs[0].getVectorElementCount() ==
12347 Ops[1].getValueType().getVectorElementCount()) &&
12348 "Vector element count mismatch!");
12349 assert(VTList.VTs[0].isFloatingPoint() &&
12350 Ops[1].getValueType().isFloatingPoint() &&
12351 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12352 Ops[2].getOpcode() == ISD::TargetConstant &&
12353 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12354 "Invalid STRICT_FP_ROUND!");
12355 break;
12356 }
12357
12358 // Memoize the node unless it returns a glue result.
12359 SDNode *N;
12360 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12361 SDNodeKey ID(Opcode, VTList, Ops);
12362 FoldingSetInsertToken InsertToken;
12363 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12364 E->intersectFlagsWith(Flags);
12365 return SDValue(E, 0);
12366 }
12367
12368 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12369 createOperands(N, Ops);
12370 CSEMap.insert(N, InsertToken);
12371 } else {
12372 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12373 createOperands(N, Ops);
12374 }
12375
12376 N->setFlags(Flags);
12377 InsertNode(N);
12378 SDValue V(N, 0);
12379 NewSDValueDbgMsg(V, "Creating new node: ", this);
12380 return V;
12381}
12382
12383SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12384 SDVTList VTList) {
12385 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12386}
12387
12388SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12389 SDValue N1) {
12390 SDValue Ops[] = { N1 };
12391 return getNode(Opcode, DL, VTList, Ops);
12392}
12393
12394SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12395 SDValue N1, SDValue N2) {
12396 SDValue Ops[] = { N1, N2 };
12397 return getNode(Opcode, DL, VTList, Ops);
12398}
12399
12400SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12401 SDValue N1, SDValue N2, SDValue N3) {
12402 SDValue Ops[] = { N1, N2, N3 };
12403 return getNode(Opcode, DL, VTList, Ops);
12404}
12405
12406SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12407 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12408 SDValue Ops[] = { N1, N2, N3, N4 };
12409 return getNode(Opcode, DL, VTList, Ops);
12410}
12411
12412SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12413 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12414 SDValue N5) {
12415 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12416 return getNode(Opcode, DL, VTList, Ops);
12417}
12418
12420 if (!VT.isExtended())
12421 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12422
12423 EVT VTs[] = {VT};
12424 return getVTList(VTs);
12425}
12426
12428 EVT VTs[] = {VT1, VT2};
12429 return getVTList(VTs);
12430}
12431
12433 EVT VTs[] = {VT1, VT2, VT3};
12434 return getVTList(VTs);
12435}
12436
12438 EVT VTs[] = {VT1, VT2, VT3, VT4};
12439 return getVTList(VTs);
12440}
12441
12443 auto It = VTLists.find(VTs);
12444 if (It == VTLists.end()) {
12445 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12446 llvm::copy(VTs, Array);
12447 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12448 }
12449 return makeVTList(It->data(), It->size());
12450}
12451
12452/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12453/// specified operands. If the resultant node already exists in the DAG,
12454/// this does not modify the specified node, instead it returns the node that
12455/// already exists. If the resultant node does not exist in the DAG, the
12456/// input node is returned. As a degenerate case, if you specify the same
12457/// input operands as the node already has, the input node is returned.
12459 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12460
12461 // Check to see if there is no change.
12462 if (Op == N->getOperand(0)) return N;
12463
12464 // See if the modified node already exists.
12465 FoldingSetInsertToken InsertToken;
12466 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken))
12467 return Existing;
12468
12469 // Nope it doesn't. Remove the node from its current place in the maps.
12470 if (InsertToken)
12471 if (!RemoveNodeFromCSEMaps(N))
12472 InsertToken = {};
12473
12474 // Now we update the operands.
12475 N->OperandList[0].set(Op);
12476
12478 // If this gets put into a CSE map, add it.
12479 if (InsertToken)
12480 CSEMap.insert(N, InsertToken);
12481 return N;
12482}
12483
12485 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12486
12487 // Check to see if there is no change.
12488 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12489 return N; // No operands changed, just return the input node.
12490
12491 // See if the modified node already exists.
12492 FoldingSetInsertToken InsertToken;
12493 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken))
12494 return Existing;
12495
12496 // Nope it doesn't. Remove the node from its current place in the maps.
12497 if (InsertToken)
12498 if (!RemoveNodeFromCSEMaps(N))
12499 InsertToken = {};
12500
12501 // Now we update the operands.
12502 if (N->OperandList[0] != Op1)
12503 N->OperandList[0].set(Op1);
12504 if (N->OperandList[1] != Op2)
12505 N->OperandList[1].set(Op2);
12506
12508 // If this gets put into a CSE map, add it.
12509 if (InsertToken)
12510 CSEMap.insert(N, InsertToken);
12511 return N;
12512}
12513
12516 SDValue Ops[] = { Op1, Op2, Op3 };
12517 return UpdateNodeOperands(N, Ops);
12518}
12519
12522 SDValue Op3, SDValue Op4) {
12523 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12524 return UpdateNodeOperands(N, Ops);
12525}
12526
12529 SDValue Op3, SDValue Op4, SDValue Op5) {
12530 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12531 return UpdateNodeOperands(N, Ops);
12532}
12533
12536 unsigned NumOps = Ops.size();
12537 assert(N->getNumOperands() == NumOps &&
12538 "Update with wrong number of operands");
12539
12540 // If no operands changed just return the input node.
12541 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12542 return N;
12543
12544 // See if the modified node already exists.
12545 FoldingSetInsertToken InsertToken;
12546 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken))
12547 return Existing;
12548
12549 // Nope it doesn't. Remove the node from its current place in the maps.
12550 if (InsertToken)
12551 if (!RemoveNodeFromCSEMaps(N))
12552 InsertToken = {};
12553
12554 // Now we update the operands.
12555 for (unsigned i = 0; i != NumOps; ++i)
12556 if (N->OperandList[i] != Ops[i])
12557 N->OperandList[i].set(Ops[i]);
12558
12560 // If this gets put into a CSE map, add it.
12561 if (InsertToken)
12562 CSEMap.insert(N, InsertToken);
12563 return N;
12564}
12565
12566/// DropOperands - Release the operands and set this node to have
12567/// zero operands.
12569 // Unlike the code in MorphNodeTo that does this, we don't need to
12570 // watch for dead nodes here.
12571 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12572 SDUse &Use = *I++;
12573 Use.set(SDValue());
12574 }
12575}
12576
12578 ArrayRef<MachineMemOperand *> NewMemRefs) {
12579 if (NewMemRefs.empty()) {
12580 N->clearMemRefs();
12581 return;
12582 }
12583
12584 // Check if we can avoid allocating by storing a single reference directly.
12585 if (NewMemRefs.size() == 1) {
12586 N->MemRefs = NewMemRefs[0];
12587 N->NumMemRefs = 1;
12588 return;
12589 }
12590
12591 MachineMemOperand **MemRefsBuffer =
12592 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12593 llvm::copy(NewMemRefs, MemRefsBuffer);
12594 N->MemRefs = MemRefsBuffer;
12595 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12596}
12597
12598/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12599/// machine opcode.
12600///
12602 EVT VT) {
12603 SDVTList VTs = getVTList(VT);
12604 return SelectNodeTo(N, MachineOpc, VTs, {});
12605}
12606
12608 EVT VT, SDValue Op1) {
12609 SDVTList VTs = getVTList(VT);
12610 SDValue Ops[] = { Op1 };
12611 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12612}
12613
12615 EVT VT, SDValue Op1,
12616 SDValue Op2) {
12617 SDVTList VTs = getVTList(VT);
12618 SDValue Ops[] = { Op1, Op2 };
12619 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12620}
12621
12623 EVT VT, SDValue Op1,
12624 SDValue Op2, SDValue Op3) {
12625 SDVTList VTs = getVTList(VT);
12626 SDValue Ops[] = { Op1, Op2, Op3 };
12627 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12628}
12629
12632 SDVTList VTs = getVTList(VT);
12633 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12634}
12635
12637 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12638 SDVTList VTs = getVTList(VT1, VT2);
12639 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12640}
12641
12643 EVT VT1, EVT VT2) {
12644 SDVTList VTs = getVTList(VT1, VT2);
12645 return SelectNodeTo(N, MachineOpc, VTs, {});
12646}
12647
12649 EVT VT1, EVT VT2, EVT VT3,
12651 SDVTList VTs = getVTList(VT1, VT2, VT3);
12652 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12653}
12654
12656 EVT VT1, EVT VT2,
12657 SDValue Op1, SDValue Op2) {
12658 SDVTList VTs = getVTList(VT1, VT2);
12659 SDValue Ops[] = { Op1, Op2 };
12660 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12661}
12662
12665 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12666 // Reset the NodeID to -1.
12667 New->setNodeId(-1);
12668 if (New != N) {
12669 ReplaceAllUsesWith(N, New);
12671 }
12672 return New;
12673}
12674
12675/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12676/// the line number information on the merged node since it is not possible to
12677/// preserve the information that operation is associated with multiple lines.
12678/// This will make the debugger work better at -O0, where there is a higher
12679/// probability of having other instructions associated with that line.
12680///
12681/// For IROrder, we keep the smaller of the two
12682SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12683 DebugLoc NLoc = N->getDebugLoc();
12684 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12685 N->setDebugLoc(DebugLoc());
12686 }
12687 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12688 N->setIROrder(Order);
12689 return N;
12690}
12691
12692/// MorphNodeTo - This *mutates* the specified node to have the specified
12693/// return type, opcode, and operands.
12694///
12695/// Note that MorphNodeTo returns the resultant node. If there is already a
12696/// node of the specified opcode and operands, it returns that node instead of
12697/// the current one. Note that the SDLoc need not be the same.
12698///
12699/// Using MorphNodeTo is faster than creating a new node and swapping it in
12700/// with ReplaceAllUsesWith both because it often avoids allocating a new
12701/// node, and because it doesn't require CSE recalculation for any of
12702/// the node's users.
12703///
12704/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12705/// As a consequence it isn't appropriate to use from within the DAG combiner or
12706/// the legalizer which maintain worklists that would need to be updated when
12707/// deleting things.
12710 // If an identical node already exists, use it.
12711 FoldingSetInsertToken InsertToken;
12712 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12713 SDNodeKey ID(Opc, VTs, Ops);
12714 AddNodeIDCustom(ID.Tail, N, Opc);
12715 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12716 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12717 }
12718
12719 if (!RemoveNodeFromCSEMaps(N))
12720 InsertToken = {};
12721
12722 // Start the morphing.
12723 N->NodeType = Opc;
12724 N->ValueList = VTs.VTs;
12725 N->NumValues = VTs.NumVTs;
12726
12727 // Clear the operands list, updating used nodes to remove this from their
12728 // use list. Keep track of any operands that become dead as a result.
12729 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12730 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12731 SDUse &Use = *I++;
12732 SDNode *Used = Use.getNode();
12733 Use.set(SDValue());
12734 if (Used->use_empty())
12735 DeadNodeSet.insert(Used);
12736 }
12737
12738 // For MachineNode, initialize the memory references information.
12740 MN->clearMemRefs();
12741
12742 // Swap for an appropriately sized array from the recycler.
12743 removeOperands(N);
12744 createOperands(N, Ops);
12745
12746 // Delete any nodes that are still dead after adding the uses for the
12747 // new operands.
12748 if (!DeadNodeSet.empty()) {
12749 SmallVector<SDNode *, 16> DeadNodes;
12750 for (SDNode *N : DeadNodeSet)
12751 if (N->use_empty())
12752 DeadNodes.push_back(N);
12753 RemoveDeadNodes(DeadNodes);
12754 }
12755
12756 if (InsertToken)
12757 CSEMap.insert(N, InsertToken); // Memoize the new node.
12758 return N;
12759}
12760
12762 unsigned OrigOpc = Node->getOpcode();
12763 unsigned NewOpc;
12764 switch (OrigOpc) {
12765 default:
12766 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12767#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12768 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12769#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12770 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12771#include "llvm/IR/ConstrainedOps.def"
12772 }
12773
12774 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12775
12776 // We're taking this node out of the chain, so we need to re-link things.
12777 SDValue InputChain = Node->getOperand(0);
12778 SDValue OutputChain = SDValue(Node, 1);
12779 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12780
12782 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12783 Ops.push_back(Node->getOperand(i));
12784
12785 SDVTList VTs = getVTList(Node->getValueType(0));
12786 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12787
12788 // MorphNodeTo can operate in two ways: if an existing node with the
12789 // specified operands exists, it can just return it. Otherwise, it
12790 // updates the node in place to have the requested operands.
12791 if (Res == Node) {
12792 // If we updated the node in place, reset the node ID. To the isel,
12793 // this should be just like a newly allocated machine node.
12794 Res->setNodeId(-1);
12795 } else {
12798 }
12799
12800 return Res;
12801}
12802
12803/// getMachineNode - These are used for target selectors to create a new node
12804/// with specified return type(s), MachineInstr opcode, and operands.
12805///
12806/// Note that getMachineNode returns the resultant node. If there is already a
12807/// node of the specified opcode and operands, it returns that node instead of
12808/// the current one.
12810 EVT VT) {
12811 SDVTList VTs = getVTList(VT);
12812 return getMachineNode(Opcode, dl, VTs, {});
12813}
12814
12816 EVT VT, SDValue Op1) {
12817 SDVTList VTs = getVTList(VT);
12818 SDValue Ops[] = { Op1 };
12819 return getMachineNode(Opcode, dl, VTs, Ops);
12820}
12821
12823 EVT VT, SDValue Op1, SDValue Op2) {
12824 SDVTList VTs = getVTList(VT);
12825 SDValue Ops[] = { Op1, Op2 };
12826 return getMachineNode(Opcode, dl, VTs, Ops);
12827}
12828
12830 EVT VT, SDValue Op1, SDValue Op2,
12831 SDValue Op3) {
12832 SDVTList VTs = getVTList(VT);
12833 SDValue Ops[] = { Op1, Op2, Op3 };
12834 return getMachineNode(Opcode, dl, VTs, Ops);
12835}
12836
12839 SDVTList VTs = getVTList(VT);
12840 return getMachineNode(Opcode, dl, VTs, Ops);
12841}
12842
12844 EVT VT1, EVT VT2, SDValue Op1,
12845 SDValue Op2) {
12846 SDVTList VTs = getVTList(VT1, VT2);
12847 SDValue Ops[] = { Op1, Op2 };
12848 return getMachineNode(Opcode, dl, VTs, Ops);
12849}
12850
12852 EVT VT1, EVT VT2, SDValue Op1,
12853 SDValue Op2, SDValue Op3) {
12854 SDVTList VTs = getVTList(VT1, VT2);
12855 SDValue Ops[] = { Op1, Op2, Op3 };
12856 return getMachineNode(Opcode, dl, VTs, Ops);
12857}
12858
12860 EVT VT1, EVT VT2,
12862 SDVTList VTs = getVTList(VT1, VT2);
12863 return getMachineNode(Opcode, dl, VTs, Ops);
12864}
12865
12867 EVT VT1, EVT VT2, EVT VT3,
12868 SDValue Op1, SDValue Op2) {
12869 SDVTList VTs = getVTList(VT1, VT2, VT3);
12870 SDValue Ops[] = { Op1, Op2 };
12871 return getMachineNode(Opcode, dl, VTs, Ops);
12872}
12873
12875 EVT VT1, EVT VT2, EVT VT3,
12876 SDValue Op1, SDValue Op2,
12877 SDValue Op3) {
12878 SDVTList VTs = getVTList(VT1, VT2, VT3);
12879 SDValue Ops[] = { Op1, Op2, Op3 };
12880 return getMachineNode(Opcode, dl, VTs, Ops);
12881}
12882
12884 EVT VT1, EVT VT2, EVT VT3,
12886 SDVTList VTs = getVTList(VT1, VT2, VT3);
12887 return getMachineNode(Opcode, dl, VTs, Ops);
12888}
12889
12891 ArrayRef<EVT> ResultTys,
12893 SDVTList VTs = getVTList(ResultTys);
12894 return getMachineNode(Opcode, dl, VTs, Ops);
12895}
12896
12898 SDVTList VTs,
12900 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12902 FoldingSetInsertToken InsertToken;
12903
12904 if (DoCSE) {
12905 SDNodeKey ID(~Opcode, VTs, Ops);
12906 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12907 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12908 }
12909 }
12910
12911 // Allocate a new MachineSDNode.
12912 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12913 createOperands(N, Ops);
12914
12915 if (DoCSE)
12916 CSEMap.insert(N, InsertToken);
12917
12918 InsertNode(N);
12919 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12920 return N;
12921}
12922
12923/// getTargetExtractSubreg - A convenience function for creating
12924/// TargetOpcode::EXTRACT_SUBREG nodes.
12926 SDValue Operand) {
12927 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12928 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12929 VT, Operand, SRIdxVal);
12930 return SDValue(Subreg, 0);
12931}
12932
12933/// getTargetInsertSubreg - A convenience function for creating
12934/// TargetOpcode::INSERT_SUBREG nodes.
12936 SDValue Operand, SDValue Subreg) {
12937 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12938 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12939 VT, Operand, Subreg, SRIdxVal);
12940 return SDValue(Result, 0);
12941}
12942
12943/// getNodeIfExists - Get the specified node if it's already available, or
12944/// else return NULL.
12947 bool AllowCommute) {
12948 SDNodeFlags Flags;
12949 if (Inserter)
12950 Flags = Inserter->getFlags();
12951 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12952}
12953
12956 const SDNodeFlags Flags,
12957 bool AllowCommute) {
12958 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12959 return nullptr;
12960
12961 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12962 SDNodeKey ID(Opcode, VTList, LookupOps);
12963 FoldingSetInsertToken InsertToken;
12964 if (SDNode *E = lookupNode(ID, InsertToken)) {
12965 E->intersectFlagsWith(Flags);
12966 return E;
12967 }
12968 return nullptr;
12969 };
12970
12971 if (SDNode *Existing = Lookup(Ops))
12972 return Existing;
12973
12974 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12975 return Lookup({Ops[1], Ops[0]});
12976
12977 return nullptr;
12978}
12979
12980/// doesNodeExist - Check if a node exists without modifying its flags.
12981bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12983 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12984 SDNodeKey ID(Opcode, VTList, Ops);
12985 FoldingSetInsertToken InsertToken;
12986 if (lookupNode(ID, SDLoc(), InsertToken))
12987 return true;
12988 }
12989 return false;
12990}
12991
12992/// getDbgValue - Creates a SDDbgValue node.
12993///
12994/// SDNode
12996 SDNode *N, unsigned R, bool IsIndirect,
12997 const DebugLoc &DL, unsigned O) {
12998 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12999 "Expected inlined-at fields to agree");
13000 return new (DbgInfo->getAlloc())
13001 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
13002 {}, IsIndirect, DL, O,
13003 /*IsVariadic=*/false);
13004}
13005
13006/// Constant
13008 DIExpression *Expr,
13009 const Value *C,
13010 const DebugLoc &DL, unsigned O) {
13011 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13012 "Expected inlined-at fields to agree");
13013 return new (DbgInfo->getAlloc())
13014 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
13015 /*IsIndirect=*/false, DL, O,
13016 /*IsVariadic=*/false);
13017}
13018
13019/// FrameIndex
13021 DIExpression *Expr, unsigned FI,
13022 bool IsIndirect,
13023 const DebugLoc &DL,
13024 unsigned O) {
13025 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13026 "Expected inlined-at fields to agree");
13027 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
13028}
13029
13030/// FrameIndex with dependencies
13032 DIExpression *Expr, unsigned FI,
13033 ArrayRef<SDNode *> Dependencies,
13034 bool IsIndirect,
13035 const DebugLoc &DL,
13036 unsigned O) {
13037 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13038 "Expected inlined-at fields to agree");
13039 return new (DbgInfo->getAlloc())
13040 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
13041 Dependencies, IsIndirect, DL, O,
13042 /*IsVariadic=*/false);
13043}
13044
13045/// VReg
13047 Register VReg, bool IsIndirect,
13048 const DebugLoc &DL, unsigned O) {
13049 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13050 "Expected inlined-at fields to agree");
13051 return new (DbgInfo->getAlloc())
13052 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
13053 {}, IsIndirect, DL, O,
13054 /*IsVariadic=*/false);
13055}
13056
13059 ArrayRef<SDNode *> Dependencies,
13060 bool IsIndirect, const DebugLoc &DL,
13061 unsigned O, bool IsVariadic) {
13062 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13063 "Expected inlined-at fields to agree");
13064 return new (DbgInfo->getAlloc())
13065 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13066 DL, O, IsVariadic);
13067}
13068
13070 unsigned OffsetInBits, unsigned SizeInBits,
13071 bool InvalidateDbg) {
13072 SDNode *FromNode = From.getNode();
13073 SDNode *ToNode = To.getNode();
13074 assert(FromNode && ToNode && "Can't modify dbg values");
13075
13076 // PR35338
13077 // TODO: assert(From != To && "Redundant dbg value transfer");
13078 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13079 if (From == To || FromNode == ToNode)
13080 return;
13081
13082 if (!FromNode->getHasDebugValue())
13083 return;
13084
13085 SDDbgOperand FromLocOp =
13086 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13088
13090 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13091 if (Dbg->isInvalidated())
13092 continue;
13093
13094 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13095
13096 // Create a new location ops vector that is equal to the old vector, but
13097 // with each instance of FromLocOp replaced with ToLocOp.
13098 bool Changed = false;
13099 auto NewLocOps = Dbg->copyLocationOps();
13100 std::replace_if(
13101 NewLocOps.begin(), NewLocOps.end(),
13102 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13103 bool Match = Op == FromLocOp;
13104 Changed |= Match;
13105 return Match;
13106 },
13107 ToLocOp);
13108 // Ignore this SDDbgValue if we didn't find a matching location.
13109 if (!Changed)
13110 continue;
13111
13112 DIVariable *Var = Dbg->getVariable();
13113 auto *Expr = Dbg->getExpression();
13114 // If a fragment is requested, update the expression.
13115 if (SizeInBits) {
13116 // When splitting a larger (e.g., sign-extended) value whose
13117 // lower bits are described with an SDDbgValue, do not attempt
13118 // to transfer the SDDbgValue to the upper bits.
13119 if (auto FI = Expr->getFragmentInfo())
13120 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13121 continue;
13122 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13123 SizeInBits);
13124 if (!Fragment)
13125 continue;
13126 Expr = *Fragment;
13127 }
13128
13129 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13130 // Clone the SDDbgValue and move it to To.
13131 SDDbgValue *Clone = getDbgValueList(
13132 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13133 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13134 Dbg->isVariadic());
13135 ClonedDVs.push_back(Clone);
13136
13137 if (InvalidateDbg) {
13138 // Invalidate value and indicate the SDDbgValue should not be emitted.
13139 Dbg->setIsInvalidated();
13140 Dbg->setIsEmitted();
13141 }
13142 }
13143
13144 for (SDDbgValue *Dbg : ClonedDVs) {
13145 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13146 "Transferred DbgValues should depend on the new SDNode");
13147 AddDbgValue(Dbg, false);
13148 }
13149}
13150
13152 if (!N.getHasDebugValue())
13153 return;
13154
13155 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13156 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13157 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13158 return SDDbgOperand::fromNode(Node, ResNo);
13159 };
13160
13162 for (auto *DV : GetDbgValues(&N)) {
13163 if (DV->isInvalidated())
13164 continue;
13165 switch (N.getOpcode()) {
13166 default:
13167 break;
13168 case ISD::ADD: {
13169 SDValue N0 = N.getOperand(0);
13170 SDValue N1 = N.getOperand(1);
13171 if (!isa<ConstantSDNode>(N0)) {
13172 bool RHSConstant = isa<ConstantSDNode>(N1);
13173 uint64_t Offset;
13174 if (RHSConstant)
13175 Offset = N.getConstantOperandVal(1);
13176 // We are not allowed to turn indirect debug values variadic, so
13177 // don't salvage those.
13178 if (!RHSConstant && DV->isIndirect())
13179 continue;
13180
13181 // Rewrite an ADD constant node into a DIExpression. Since we are
13182 // performing arithmetic to compute the variable's *value* in the
13183 // DIExpression, we need to mark the expression with a
13184 // DW_OP_stack_value.
13185 auto *DIExpr = DV->getExpression();
13186 auto NewLocOps = DV->copyLocationOps();
13187 bool Changed = false;
13188 size_t OrigLocOpsSize = NewLocOps.size();
13189 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13190 // We're not given a ResNo to compare against because the whole
13191 // node is going away. We know that any ISD::ADD only has one
13192 // result, so we can assume any node match is using the result.
13193 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13194 NewLocOps[i].getSDNode() != &N)
13195 continue;
13196 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13197 if (RHSConstant) {
13200 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13201 } else {
13202 // Convert to a variadic expression (if not already).
13203 // convertToVariadicExpression() returns a const pointer, so we use
13204 // a temporary const variable here.
13205 const auto *TmpDIExpr =
13209 ExprOps.push_back(NewLocOps.size());
13210 ExprOps.push_back(dwarf::DW_OP_plus);
13211 SDDbgOperand RHS =
13213 NewLocOps.push_back(RHS);
13214 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13215 }
13216 Changed = true;
13217 }
13218 (void)Changed;
13219 assert(Changed && "Salvage target doesn't use N");
13220
13221 bool IsVariadic =
13222 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13223
13224 auto AdditionalDependencies = DV->getAdditionalDependencies();
13225 SDDbgValue *Clone = getDbgValueList(
13226 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13227 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13228 ClonedDVs.push_back(Clone);
13229 DV->setIsInvalidated();
13230 DV->setIsEmitted();
13231 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13232 N0.getNode()->dumprFull(this);
13233 dbgs() << " into " << *DIExpr << '\n');
13234 }
13235 break;
13236 }
13237 case ISD::TRUNCATE: {
13238 SDValue N0 = N.getOperand(0);
13239 TypeSize FromSize = N0.getValueSizeInBits();
13240 TypeSize ToSize = N.getValueSizeInBits(0);
13241
13242 DIExpression *DbgExpression = DV->getExpression();
13243 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13244 auto NewLocOps = DV->copyLocationOps();
13245 bool Changed = false;
13246 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13247 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13248 NewLocOps[i].getSDNode() != &N)
13249 continue;
13250
13251 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13252 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13253 Changed = true;
13254 }
13255 assert(Changed && "Salvage target doesn't use N");
13256 (void)Changed;
13257
13258 SDDbgValue *Clone =
13259 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13260 DV->getAdditionalDependencies(), DV->isIndirect(),
13261 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13262
13263 ClonedDVs.push_back(Clone);
13264 DV->setIsInvalidated();
13265 DV->setIsEmitted();
13266 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13267 dbgs() << " into " << *DbgExpression << '\n');
13268 break;
13269 }
13270 }
13271 }
13272
13273 for (SDDbgValue *Dbg : ClonedDVs) {
13274 assert((!Dbg->getSDNodes().empty() ||
13275 llvm::any_of(Dbg->getLocationOps(),
13276 [&](const SDDbgOperand &Op) {
13277 return Op.getKind() == SDDbgOperand::FRAMEIX;
13278 })) &&
13279 "Salvaged DbgValue should depend on a new SDNode");
13280 AddDbgValue(Dbg, false);
13281 }
13282}
13283
13284/// Creates a SDDbgLabel node.
13286 const DebugLoc &DL, unsigned O) {
13287 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13288 "Expected inlined-at fields to agree");
13289 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13290}
13291
13292namespace {
13293
13294/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13295/// pointed to by a use iterator is deleted, increment the use iterator
13296/// so that it doesn't dangle.
13297///
13298class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13301
13302 void NodeDeleted(SDNode *N, SDNode *E) override {
13303 // Increment the iterator as needed.
13304 while (UI != UE && N == UI->getUser())
13305 ++UI;
13306 }
13307
13308public:
13309 RAUWUpdateListener(SelectionDAG &d,
13312 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13313};
13314
13315} // end anonymous namespace
13316
13317/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13318/// This can cause recursive merging of nodes in the DAG.
13319///
13320/// This version assumes From has a single result value.
13321///
13323 SDNode *From = FromN.getNode();
13324 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13325 "Cannot replace with this method!");
13326 assert(From != To.getNode() && "Cannot replace uses of with self");
13327
13328 // Preserve Debug Values
13329 transferDbgValues(FromN, To);
13330 // Preserve extra info.
13331 copyExtraInfo(From, To.getNode());
13332
13333 // Iterate over all the existing uses of From. New uses will be added
13334 // to the beginning of the use list, which we avoid visiting.
13335 // This specifically avoids visiting uses of From that arise while the
13336 // replacement is happening, because any such uses would be the result
13337 // of CSE: If an existing node looks like From after one of its operands
13338 // is replaced by To, we don't want to replace of all its users with To
13339 // too. See PR3018 for more info.
13340 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13341 RAUWUpdateListener Listener(*this, UI, UE);
13342 while (UI != UE) {
13343 SDNode *User = UI->getUser();
13344
13345 // This node is about to morph, remove its old self from the CSE maps.
13346 RemoveNodeFromCSEMaps(User);
13347
13348 // A user can appear in a use list multiple times, and when this
13349 // happens the uses are usually next to each other in the list.
13350 // To help reduce the number of CSE recomputations, process all
13351 // the uses of this user that we can find this way.
13352 do {
13353 SDUse &Use = *UI;
13354 ++UI;
13355 Use.set(To);
13356 if (To->isDivergent() != From->isDivergent())
13358 } while (UI != UE && UI->getUser() == User);
13359 // Now that we have modified User, add it back to the CSE maps. If it
13360 // already exists there, recursively merge the results together.
13361 AddModifiedNodeToCSEMaps(User);
13362 }
13363
13364 // If we just RAUW'd the root, take note.
13365 if (FromN == getRoot())
13366 setRoot(To);
13367}
13368
13369/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13370/// This can cause recursive merging of nodes in the DAG.
13371///
13372/// This version assumes that for each value of From, there is a
13373/// corresponding value in To in the same position with the same type.
13374///
13376#ifndef NDEBUG
13377 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13378 assert((!From->hasAnyUseOfValue(i) ||
13379 From->getValueType(i) == To->getValueType(i)) &&
13380 "Cannot use this version of ReplaceAllUsesWith!");
13381#endif
13382
13383 // Handle the trivial case.
13384 if (From == To)
13385 return;
13386
13387 // Preserve Debug Info. Only do this if there's a use.
13388 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13389 if (From->hasAnyUseOfValue(i)) {
13390 assert((i < To->getNumValues()) && "Invalid To location");
13391 transferDbgValues(SDValue(From, i), SDValue(To, i));
13392 }
13393 // Preserve extra info.
13394 copyExtraInfo(From, To);
13395
13396 // Iterate over just the existing users of From. See the comments in
13397 // the ReplaceAllUsesWith above.
13398 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13399 RAUWUpdateListener Listener(*this, UI, UE);
13400 while (UI != UE) {
13401 SDNode *User = UI->getUser();
13402
13403 // This node is about to morph, remove its old self from the CSE maps.
13404 RemoveNodeFromCSEMaps(User);
13405
13406 // A user can appear in a use list multiple times, and when this
13407 // happens the uses are usually next to each other in the list.
13408 // To help reduce the number of CSE recomputations, process all
13409 // the uses of this user that we can find this way.
13410 do {
13411 SDUse &Use = *UI;
13412 ++UI;
13413 Use.setNode(To);
13414 if (To->isDivergent() != From->isDivergent())
13416 } while (UI != UE && UI->getUser() == User);
13417
13418 // Now that we have modified User, add it back to the CSE maps. If it
13419 // already exists there, recursively merge the results together.
13420 AddModifiedNodeToCSEMaps(User);
13421 }
13422
13423 // If we just RAUW'd the root, take note.
13424 if (From == getRoot().getNode())
13425 setRoot(SDValue(To, getRoot().getResNo()));
13426}
13427
13428/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13429/// This can cause recursive merging of nodes in the DAG.
13430///
13431/// This version can replace From with any result values. To must match the
13432/// number and types of values returned by From.
13434 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13435 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13436
13437 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13438 // Preserve Debug Info.
13439 transferDbgValues(SDValue(From, i), To[i]);
13440 // Preserve extra info.
13441 copyExtraInfo(From, To[i].getNode());
13442 }
13443
13444 // Iterate over just the existing users of From. See the comments in
13445 // the ReplaceAllUsesWith above.
13446 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13447 RAUWUpdateListener Listener(*this, UI, UE);
13448 while (UI != UE) {
13449 SDNode *User = UI->getUser();
13450
13451 // This node is about to morph, remove its old self from the CSE maps.
13452 RemoveNodeFromCSEMaps(User);
13453
13454 // A user can appear in a use list multiple times, and when this happens the
13455 // uses are usually next to each other in the list. To help reduce the
13456 // number of CSE and divergence recomputations, process all the uses of this
13457 // user that we can find this way.
13458 bool To_IsDivergent = false;
13459 do {
13460 SDUse &Use = *UI;
13461 const SDValue &ToOp = To[Use.getResNo()];
13462 ++UI;
13463 Use.set(ToOp);
13464 if (ToOp.getValueType() != MVT::Other)
13465 To_IsDivergent |= ToOp->isDivergent();
13466 } while (UI != UE && UI->getUser() == User);
13467
13468 if (To_IsDivergent != From->isDivergent())
13470
13471 // Now that we have modified User, add it back to the CSE maps. If it
13472 // already exists there, recursively merge the results together.
13473 AddModifiedNodeToCSEMaps(User);
13474 }
13475
13476 // If we just RAUW'd the root, take note.
13477 if (From == getRoot().getNode())
13478 setRoot(SDValue(To[getRoot().getResNo()]));
13479}
13480
13481/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13482/// uses of other values produced by From.getNode() alone. The Deleted
13483/// vector is handled the same way as for ReplaceAllUsesWith.
13485 // Handle the really simple, really trivial case efficiently.
13486 if (From == To) return;
13487
13488 // Handle the simple, trivial, case efficiently.
13489 if (From.getNode()->getNumValues() == 1) {
13490 ReplaceAllUsesWith(From, To);
13491 return;
13492 }
13493
13494 // Preserve Debug Info.
13495 transferDbgValues(From, To);
13496 copyExtraInfo(From.getNode(), To.getNode());
13497
13498 // Iterate over just the existing users of From. See the comments in
13499 // the ReplaceAllUsesWith above.
13500 SDNode::use_iterator UI = From.getNode()->use_begin(),
13501 UE = From.getNode()->use_end();
13502 RAUWUpdateListener Listener(*this, UI, UE);
13503 while (UI != UE) {
13504 SDNode *User = UI->getUser();
13505 bool UserRemovedFromCSEMaps = false;
13506
13507 // A user can appear in a use list multiple times, and when this
13508 // happens the uses are usually next to each other in the list.
13509 // To help reduce the number of CSE recomputations, process all
13510 // the uses of this user that we can find this way.
13511 do {
13512 SDUse &Use = *UI;
13513
13514 // Skip uses of different values from the same node.
13515 if (Use.getResNo() != From.getResNo()) {
13516 ++UI;
13517 continue;
13518 }
13519
13520 // If this node hasn't been modified yet, it's still in the CSE maps,
13521 // so remove its old self from the CSE maps.
13522 if (!UserRemovedFromCSEMaps) {
13523 RemoveNodeFromCSEMaps(User);
13524 UserRemovedFromCSEMaps = true;
13525 }
13526
13527 ++UI;
13528 Use.set(To);
13529 if (To->isDivergent() != From->isDivergent())
13531 } while (UI != UE && UI->getUser() == User);
13532 // We are iterating over all uses of the From node, so if a use
13533 // doesn't use the specific value, no changes are made.
13534 if (!UserRemovedFromCSEMaps)
13535 continue;
13536
13537 // Now that we have modified User, add it back to the CSE maps. If it
13538 // already exists there, recursively merge the results together.
13539 AddModifiedNodeToCSEMaps(User);
13540 }
13541
13542 // If we just RAUW'd the root, take note.
13543 if (From == getRoot())
13544 setRoot(To);
13545}
13546
13547namespace {
13548
13549/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13550/// to record information about a use.
13551struct UseMemo {
13552 SDNode *User;
13553 unsigned Index;
13554 SDUse *Use;
13555};
13556
13557/// operator< - Sort Memos by User.
13558bool operator<(const UseMemo &L, const UseMemo &R) {
13559 return (intptr_t)L.User < (intptr_t)R.User;
13560}
13561
13562/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13563/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13564/// the node already has been taken care of recursively.
13565class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13566 SmallVectorImpl<UseMemo> &Uses;
13567
13568 void NodeDeleted(SDNode *N, SDNode *E) override {
13569 for (UseMemo &Memo : Uses)
13570 if (Memo.User == N)
13571 Memo.User = nullptr;
13572 }
13573
13574public:
13575 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13576 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13577};
13578
13579} // end anonymous namespace
13580
13581/// Return true if a glue output should propagate divergence information.
13583 switch (Node->getOpcode()) {
13584 case ISD::CopyFromReg:
13585 case ISD::CopyToReg:
13586 return false;
13587 default:
13588 return true;
13589 }
13590
13591 llvm_unreachable("covered opcode switch");
13592}
13593
13595 if (TLI->isSDNodeAlwaysUniform(N)) {
13596 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13597 "Conflicting divergence information!");
13598 return false;
13599 }
13600 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13601 return true;
13602 for (const auto &Op : N->ops()) {
13603 EVT VT = Op.getValueType();
13604
13605 // Skip Chain. It does not carry divergence.
13606 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13607 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13608 return true;
13609 }
13610 return false;
13611}
13612
13614 SmallVector<SDNode *, 16> Worklist(1, N);
13615 do {
13616 N = Worklist.pop_back_val();
13617 bool IsDivergent = calculateDivergence(N);
13618 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13619 N->SDNodeBits.IsDivergent = IsDivergent;
13620 llvm::append_range(Worklist, N->users());
13621 }
13622 } while (!Worklist.empty());
13623}
13624
13625void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13627 Order.reserve(AllNodes.size());
13628 for (auto &N : allnodes()) {
13629 unsigned NOps = N.getNumOperands();
13630 Degree[&N] = NOps;
13631 if (0 == NOps)
13632 Order.push_back(&N);
13633 }
13634 for (size_t I = 0; I != Order.size(); ++I) {
13635 SDNode *N = Order[I];
13636 for (auto *U : N->users()) {
13637 unsigned &UnsortedOps = Degree[U];
13638 if (0 == --UnsortedOps)
13639 Order.push_back(U);
13640 }
13641 }
13642}
13643
13644#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13645void SelectionDAG::VerifyDAGDivergence() {
13646 std::vector<SDNode *> TopoOrder;
13647 CreateTopologicalOrder(TopoOrder);
13648 for (auto *N : TopoOrder) {
13649 assert(calculateDivergence(N) == N->isDivergent() &&
13650 "Divergence bit inconsistency detected");
13651 }
13652}
13653#endif
13654
13655/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13656/// uses of other values produced by From.getNode() alone. The same value
13657/// may appear in both the From and To list. The Deleted vector is
13658/// handled the same way as for ReplaceAllUsesWith.
13660 const SDValue *To,
13661 unsigned Num){
13662 // Handle the simple, trivial case efficiently.
13663 if (Num == 1)
13664 return ReplaceAllUsesOfValueWith(*From, *To);
13665
13666 transferDbgValues(*From, *To);
13667 copyExtraInfo(From->getNode(), To->getNode());
13668
13669 // Read up all the uses and make records of them. This helps
13670 // processing new uses that are introduced during the
13671 // replacement process.
13673 for (unsigned i = 0; i != Num; ++i) {
13674 unsigned FromResNo = From[i].getResNo();
13675 SDNode *FromNode = From[i].getNode();
13676 for (SDUse &Use : FromNode->uses()) {
13677 if (Use.getResNo() == FromResNo) {
13678 UseMemo Memo = {Use.getUser(), i, &Use};
13679 Uses.push_back(Memo);
13680 }
13681 }
13682 }
13683
13684 // Sort the uses, so that all the uses from a given User are together.
13686 RAUOVWUpdateListener Listener(*this, Uses);
13687
13688 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13689 UseIndex != UseIndexEnd; ) {
13690 // We know that this user uses some value of From. If it is the right
13691 // value, update it.
13692 SDNode *User = Uses[UseIndex].User;
13693 // If the node has been deleted by recursive CSE updates when updating
13694 // another node, then just skip this entry.
13695 if (User == nullptr) {
13696 ++UseIndex;
13697 continue;
13698 }
13699
13700 // This node is about to morph, remove its old self from the CSE maps.
13701 RemoveNodeFromCSEMaps(User);
13702
13703 // The Uses array is sorted, so all the uses for a given User
13704 // are next to each other in the list.
13705 // To help reduce the number of CSE recomputations, process all
13706 // the uses of this user that we can find this way.
13707 do {
13708 unsigned i = Uses[UseIndex].Index;
13709 SDUse &Use = *Uses[UseIndex].Use;
13710 ++UseIndex;
13711
13712 Use.set(To[i]);
13713 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13714
13715 // Now that we have modified User, add it back to the CSE maps. If it
13716 // already exists there, recursively merge the results together.
13717 AddModifiedNodeToCSEMaps(User);
13718 }
13719}
13720
13721/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13722/// based on their topological order. It returns the maximum id and a vector
13723/// of the SDNodes* in assigned order by reference.
13725 unsigned DAGSize = 0;
13726
13727 // SortedPos tracks the progress of the algorithm. Nodes before it are
13728 // sorted, nodes after it are unsorted. When the algorithm completes
13729 // it is at the end of the list.
13730 allnodes_iterator SortedPos = allnodes_begin();
13731
13732 // Visit all the nodes. Move nodes with no operands to the front of
13733 // the list immediately. Annotate nodes that do have operands with their
13734 // operand count. Before we do this, the Node Id fields of the nodes
13735 // may contain arbitrary values. After, the Node Id fields for nodes
13736 // before SortedPos will contain the topological sort index, and the
13737 // Node Id fields for nodes At SortedPos and after will contain the
13738 // count of outstanding operands.
13740 checkForCycles(&N, this);
13741 unsigned Degree = N.getNumOperands();
13742 if (Degree == 0) {
13743 // A node with no uses, add it to the result array immediately.
13744 N.setNodeId(DAGSize++);
13745 allnodes_iterator Q(&N);
13746 if (Q != SortedPos)
13747 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13748 assert(SortedPos != AllNodes.end() && "Overran node list");
13749 ++SortedPos;
13750 } else {
13751 // Temporarily use the Node Id as scratch space for the degree count.
13752 N.setNodeId(Degree);
13753 }
13754 }
13755
13756 // Visit all the nodes. As we iterate, move nodes into sorted order,
13757 // such that by the time the end is reached all nodes will be sorted.
13758 for (SDNode &Node : allnodes()) {
13759 SDNode *N = &Node;
13760 checkForCycles(N, this);
13761 // N is in sorted position, so all its uses have one less operand
13762 // that needs to be sorted.
13763 for (SDNode *P : N->users()) {
13764 unsigned Degree = P->getNodeId();
13765 assert(Degree != 0 && "Invalid node degree");
13766 --Degree;
13767 if (Degree == 0) {
13768 // All of P's operands are sorted, so P may sorted now.
13769 P->setNodeId(DAGSize++);
13770 if (P->getIterator() != SortedPos)
13771 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13772 assert(SortedPos != AllNodes.end() && "Overran node list");
13773 ++SortedPos;
13774 } else {
13775 // Update P's outstanding operand count.
13776 P->setNodeId(Degree);
13777 }
13778 }
13779 if (Node.getIterator() == SortedPos) {
13780#ifndef NDEBUG
13782 SDNode *S = &*++I;
13783 dbgs() << "Overran sorted position:\n";
13784 S->dumprFull(this); dbgs() << "\n";
13785 dbgs() << "Checking if this is due to cycles\n";
13786 checkForCycles(this, true);
13787#endif
13788 llvm_unreachable(nullptr);
13789 }
13790 }
13791
13792 assert(SortedPos == AllNodes.end() &&
13793 "Topological sort incomplete!");
13794 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13795 "First node in topological sort is not the entry token!");
13796 assert(AllNodes.front().getNodeId() == 0 &&
13797 "First node in topological sort has non-zero id!");
13798 assert(AllNodes.front().getNumOperands() == 0 &&
13799 "First node in topological sort has operands!");
13800 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13801 "Last node in topologic sort has unexpected id!");
13802 assert(AllNodes.back().use_empty() &&
13803 "Last node in topologic sort has users!");
13804 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13805 return DAGSize;
13806}
13807
13809 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13810 SortedNodes.clear();
13811 // Node -> remaining number of outstanding operands.
13812 DenseMap<const SDNode *, unsigned> RemainingOperands;
13813
13814 // Put nodes without any operands into SortedNodes first.
13815 for (const SDNode &N : allnodes()) {
13816 checkForCycles(&N, this);
13817 unsigned NumOperands = N.getNumOperands();
13818 if (NumOperands == 0)
13819 SortedNodes.push_back(&N);
13820 else
13821 // Record their total number of outstanding operands.
13822 RemainingOperands[&N] = NumOperands;
13823 }
13824
13825 // A node is pushed into SortedNodes when all of its operands (predecessors in
13826 // the graph) are also in SortedNodes.
13827 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13828 const SDNode *N = SortedNodes[i];
13829 for (const SDNode *U : N->users()) {
13830 // HandleSDNode is never part of a DAG and therefore has no entry in
13831 // RemainingOperands.
13832 if (U->getOpcode() == ISD::HANDLENODE)
13833 continue;
13834 unsigned &NumRemOperands = RemainingOperands[U];
13835 assert(NumRemOperands && "Invalid number of remaining operands");
13836 --NumRemOperands;
13837 if (!NumRemOperands)
13838 SortedNodes.push_back(U);
13839 }
13840 }
13841
13842 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13843 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13844 "First node in topological sort is not the entry token");
13845 assert(SortedNodes.front()->getNumOperands() == 0 &&
13846 "First node in topological sort has operands");
13847}
13848
13849/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13850/// value is produced by SD.
13851void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13852 for (SDNode *SD : DB->getSDNodes()) {
13853 if (!SD)
13854 continue;
13855 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13856 SD->setHasDebugValue(true);
13857 }
13858 DbgInfo->add(DB, isParameter);
13859}
13860
13861void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13862
13864 SDValue NewMemOpChain) {
13865 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13866 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13867 // The new memory operation must have the same position as the old load in
13868 // terms of memory dependency. Create a TokenFactor for the old load and new
13869 // memory operation and update uses of the old load's output chain to use that
13870 // TokenFactor.
13871 if (OldChain == NewMemOpChain || OldChain.use_empty())
13872 return NewMemOpChain;
13873
13874 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13875 OldChain, NewMemOpChain);
13876 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13877 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13878 return TokenFactor;
13879}
13880
13882 SDValue NewMemOp) {
13883 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13884 SDValue OldChain = SDValue(OldLoad, 1);
13885 SDValue NewMemOpChain = NewMemOp.getValue(1);
13886 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13887}
13888
13890 Function **OutFunction) {
13891 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13892
13893 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13894 auto *Module = MF->getFunction().getParent();
13895 auto *Function = Module->getFunction(Symbol);
13896
13897 if (OutFunction != nullptr)
13898 *OutFunction = Function;
13899
13900 if (Function != nullptr) {
13901 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13902 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13903 }
13904
13905 std::string ErrorStr;
13906 raw_string_ostream ErrorFormatter(ErrorStr);
13907 ErrorFormatter << "Undefined external symbol ";
13908 ErrorFormatter << '"' << Symbol << '"';
13909 report_fatal_error(Twine(ErrorStr));
13910}
13911
13912//===----------------------------------------------------------------------===//
13913// SDNode Class
13914//===----------------------------------------------------------------------===//
13915
13918 return Const != nullptr && Const->isZero();
13919}
13920
13922 return V.isUndef() || isNullConstant(V);
13923}
13924
13927 return Const != nullptr && Const->isZero() && !Const->isNegative();
13928}
13929
13932 return Const != nullptr && Const->isAllOnes();
13933}
13934
13937 return Const != nullptr && Const->isOne();
13938}
13939
13942 return Const != nullptr && Const->isMinSignedValue();
13943}
13944
13946 SDValue V, unsigned OperandNo,
13947 unsigned Depth) const {
13948 APInt DemandedElts = getDemandAllEltsMask(V);
13949 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13950}
13951
13953 SDValue V, const APInt &DemandedElts,
13954 unsigned OperandNo, unsigned Depth) const {
13955 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13956 // TODO: Target-specific opcodes could be added.
13957 if (V.getValueType().isInteger()) {
13958 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13959 if (Known.isConstant()) {
13960 const APInt &Const = Known.getConstant();
13961 switch (Opcode) {
13962 case ISD::ADD:
13963 case ISD::OR:
13964 case ISD::XOR:
13965 case ISD::UMAX:
13966 return Const.isZero();
13967 case ISD::MUL:
13968 return Const.isOne();
13969 case ISD::AND:
13970 case ISD::UMIN:
13971 return Const.isAllOnes();
13972 case ISD::SMAX:
13973 return Const.isMinSignedValue();
13974 case ISD::SMIN:
13975 return Const.isMaxSignedValue();
13976 case ISD::SUB:
13977 case ISD::SHL:
13978 case ISD::SRA:
13979 case ISD::SRL:
13980 return OperandNo == 1 && Const.isZero();
13981 case ISD::UDIV:
13982 case ISD::SDIV:
13983 return OperandNo == 1 && Const.isOne();
13984 }
13985 }
13986 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13987 switch (Opcode) {
13988 case ISD::FADD:
13989 return ConstFP->isZero() &&
13990 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13991 case ISD::FSUB:
13992 return OperandNo == 1 && ConstFP->isZero() &&
13993 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13994 case ISD::FMUL:
13995 return ConstFP->isOne();
13996 case ISD::FDIV:
13997 return OperandNo == 1 && ConstFP->isOne();
13998 case ISD::FMINNUM:
13999 case ISD::FMAXNUM:
14000 case ISD::FMINIMUMNUM:
14001 case ISD::FMAXIMUMNUM: {
14002 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
14003 // depending on fast-math flags (FMF).
14004 EVT VT = V.getValueType();
14005 const fltSemantics &Semantics = VT.getFltSemantics();
14006 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
14007 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
14008 : APFloat::getLargest(Semantics);
14009 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
14010 NeutralAF.changeSign();
14011
14012 return ConstFP->isExactlyValue(NeutralAF);
14013 }
14014 case ISD::FMINIMUM:
14015 case ISD::FMAXIMUM: {
14016 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
14017 const APFloat &VAPF = ConstFP->getValueAPF();
14018 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
14019 if (Flags.hasNoInfs())
14020 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
14021 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
14022 }
14023 }
14024 }
14025 return false;
14026}
14027
14029 while (V.getOpcode() == ISD::BITCAST)
14030 V = V.getOperand(0);
14031 return V;
14032}
14033
14035 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
14036 V = V.getOperand(0);
14037 return V;
14038}
14039
14041 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14042 V = V.getOperand(0);
14043 return V;
14044}
14045
14047 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14048 SDValue InVec = V.getOperand(0);
14049 SDValue EltNo = V.getOperand(2);
14050 EVT VT = InVec.getValueType();
14051 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14052 if (IndexC && VT.isFixedLengthVector() &&
14053 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
14054 !DemandedElts[IndexC->getZExtValue()]) {
14055 V = InVec;
14056 continue;
14057 }
14058 break;
14059 }
14060 return V;
14061}
14062
14064 while (V.getOpcode() == ISD::TRUNCATE)
14065 V = V.getOperand(0);
14066 return V;
14067}
14068
14069bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14070 if (V.getOpcode() != ISD::XOR)
14071 return false;
14072 V = peekThroughBitcasts(V.getOperand(1));
14073 unsigned NumBits = V.getScalarValueSizeInBits();
14074 ConstantSDNode *C =
14075 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14076 return C && (C->getAPIntValue().countr_one() >= NumBits);
14077}
14078
14080 bool AllowTruncation) {
14081 APInt DemandedElts = getDemandAllEltsMask(N);
14082 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14083}
14084
14086 bool AllowUndefs,
14087 bool AllowTruncation) {
14089 return CN;
14090
14091 // SplatVectors can truncate their operands. Ignore that case here unless
14092 // AllowTruncation is set.
14093 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14094 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14095 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14096 EVT CVT = CN->getValueType(0);
14097 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14098 if (AllowTruncation || CVT == VecEltVT)
14099 return CN;
14100 }
14101 }
14102
14104 BitVector UndefElements;
14105 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14106
14107 // BuildVectors can truncate their operands. Ignore that case here unless
14108 // AllowTruncation is set.
14109 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14110 if (CN && (UndefElements.none() || AllowUndefs)) {
14111 EVT CVT = CN->getValueType(0);
14112 EVT NSVT = N.getValueType().getScalarType();
14113 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14114 if (AllowTruncation || (CVT == NSVT))
14115 return CN;
14116 }
14117 }
14118
14119 if (N.getOpcode() == ISD::MERGE_VALUES)
14120 return isConstOrConstSplat(N.getOperand(N.getResNo()), DemandedElts,
14121 AllowUndefs, AllowTruncation);
14122
14123 return nullptr;
14124}
14125
14127 APInt DemandedElts = getDemandAllEltsMask(N);
14128 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14129}
14130
14132 const APInt &DemandedElts,
14133 bool AllowUndefs) {
14135 return CN;
14136
14138 BitVector UndefElements;
14139 ConstantFPSDNode *CN =
14140 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14141 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14142 if (CN && (UndefElements.none() || AllowUndefs))
14143 return CN;
14144 }
14145
14146 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14147 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14148 return CN;
14149
14150 return nullptr;
14151}
14152
14153bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14154 // TODO: may want to use peekThroughBitcast() here.
14155 ConstantSDNode *C =
14156 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14157 return C && C->isZero();
14158}
14159
14160bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14161 ConstantSDNode *C =
14162 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14163 return C && C->isOne();
14164}
14165
14166bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14167 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14168 return C && C->isOne();
14169}
14170
14171bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14173 unsigned BitWidth = N.getScalarValueSizeInBits();
14174 ConstantSDNode *C =
14175 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14176 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14177}
14178
14179bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14181 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14182 return C && C->isZero();
14183}
14184
14185bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14186 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14187 return C && C->isZero();
14188}
14189
14193
14195 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14197 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14198 bool IsVolatile = false;
14199 bool IsNonTemporal = false;
14200 bool IsDereferenceable = true;
14201 bool IsInvariant = true;
14202 for (const MachineMemOperand *MMO : memoperands()) {
14203 IsVolatile |= MMO->isVolatile();
14204 IsNonTemporal |= MMO->isNonTemporal();
14205 IsDereferenceable &= MMO->isDereferenceable();
14206 IsInvariant &= MMO->isInvariant();
14207 }
14208 MemSDNodeBits.IsVolatile = IsVolatile;
14209 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14210 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14211 MemSDNodeBits.IsInvariant = IsInvariant;
14212
14213 // For the single-MMO case, we check here that the size of the memory operand
14214 // fits within the size of the MMO. This is because the MMO might indicate
14215 // only a possible address range instead of specifying the affected memory
14216 // addresses precisely.
14219 getMemOperand()->getSize().getValue())) &&
14220 "Size mismatch!");
14221}
14222
14223namespace {
14224
14225 struct EVTArray {
14226 std::vector<EVT> VTs;
14227
14228 EVTArray() {
14229 VTs.reserve(MVT::VALUETYPE_SIZE);
14230 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14231 VTs.push_back(MVT((MVT::SimpleValueType)i));
14232 }
14233 };
14234
14235} // end anonymous namespace
14236
14237/// getValueTypeList - Return a pointer to the specified value type.
14238///
14239const EVT *SDNode::getValueTypeList(MVT VT) {
14240 static EVTArray SimpleVTArray;
14241
14242 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14243 return &SimpleVTArray.VTs[VT.SimpleTy];
14244}
14245
14246/// hasAnyUseOfValue - Return true if there are any use of the indicated
14247/// value. This method ignores uses of other values defined by this operation.
14248bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14249 assert(Value < getNumValues() && "Bad value!");
14250
14251 for (SDUse &U : uses())
14252 if (U.getResNo() == Value)
14253 return true;
14254
14255 return false;
14256}
14257
14258/// isOnlyUserOf - Return true if this node is the only use of N.
14259bool SDNode::isOnlyUserOf(const SDNode *N) const {
14260 bool Seen = false;
14261 for (const SDNode *User : N->users()) {
14262 if (User == this)
14263 Seen = true;
14264 else
14265 return false;
14266 }
14267
14268 return Seen;
14269}
14270
14271/// Return true if the only users of N are contained in Nodes.
14273 bool Seen = false;
14274 for (const SDNode *User : N->users()) {
14275 if (llvm::is_contained(Nodes, User))
14276 Seen = true;
14277 else
14278 return false;
14279 }
14280
14281 return Seen;
14282}
14283
14284/// Return true if the referenced return value is an operand of N.
14285bool SDValue::isOperandOf(const SDNode *N) const {
14286 return is_contained(N->op_values(), *this);
14287}
14288
14289bool SDNode::isOperandOf(const SDNode *N) const {
14290 return any_of(N->op_values(),
14291 [this](SDValue Op) { return this == Op.getNode(); });
14292}
14293
14294/// reachesChainWithoutSideEffects - Return true if this operand (which must
14295/// be a chain) reaches the specified operand without crossing any
14296/// side-effecting instructions on any chain path. In practice, this looks
14297/// through token factors and non-volatile loads. In order to remain efficient,
14298/// this only looks a couple of nodes in, it does not do an exhaustive search.
14299///
14300/// Note that we only need to examine chains when we're searching for
14301/// side-effects; SelectionDAG requires that all side-effects are represented
14302/// by chains, even if another operand would force a specific ordering. This
14303/// constraint is necessary to allow transformations like splitting loads.
14305 unsigned Depth) const {
14306 if (*this == Dest) return true;
14307
14308 // Don't search too deeply, we just want to be able to see through
14309 // TokenFactor's etc.
14310 if (Depth == 0) return false;
14311
14312 // If this is a token factor, all inputs to the TF happen in parallel.
14313 if (getOpcode() == ISD::TokenFactor) {
14314 // First, try a shallow search.
14315 if (is_contained((*this)->ops(), Dest)) {
14316 // We found the chain we want as an operand of this TokenFactor.
14317 // Essentially, we reach the chain without side-effects if we could
14318 // serialize the TokenFactor into a simple chain of operations with
14319 // Dest as the last operation. This is automatically true if the
14320 // chain has one use: there are no other ordering constraints.
14321 // If the chain has more than one use, we give up: some other
14322 // use of Dest might force a side-effect between Dest and the current
14323 // node.
14324 if (Dest.hasOneUse())
14325 return true;
14326 }
14327 // Next, try a deep search: check whether every operand of the TokenFactor
14328 // reaches Dest.
14329 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14330 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14331 });
14332 }
14333
14334 // Loads don't have side effects, look through them.
14335 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14336 if (Ld->isUnordered())
14337 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14338 }
14339 return false;
14340}
14341
14342bool SDNode::hasPredecessor(const SDNode *N) const {
14345 Worklist.push_back(this);
14346 return hasPredecessorHelper(N, Visited, Worklist);
14347}
14348
14350 this->Flags &= Flags;
14351}
14352
14353SDValue
14355 ArrayRef<ISD::NodeType> CandidateBinOps,
14356 bool AllowPartials) {
14357 // The pattern must end in an extract from index 0.
14358 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14359 !isNullConstant(Extract->getOperand(1)))
14360 return SDValue();
14361
14362 // Match against one of the candidate binary ops.
14363 SDValue Op = Extract->getOperand(0);
14364 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14365 return Op.getOpcode() == unsigned(BinOp);
14366 }))
14367 return SDValue();
14368
14369 // Floating-point reductions may require relaxed constraints on the final step
14370 // of the reduction because they may reorder intermediate operations.
14371 unsigned CandidateBinOp = Op.getOpcode();
14372 if (Op.getValueType().isFloatingPoint()) {
14373 SDNodeFlags Flags = Op->getFlags();
14374 switch (CandidateBinOp) {
14375 case ISD::FADD:
14376 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14377 return SDValue();
14378 break;
14379 default:
14380 llvm_unreachable("Unhandled FP opcode for binop reduction");
14381 }
14382 }
14383
14384 // Matching failed - attempt to see if we did enough stages that a partial
14385 // reduction from a subvector is possible.
14386 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14387 if (!AllowPartials || !Op)
14388 return SDValue();
14389 EVT OpVT = Op.getValueType();
14390 EVT OpSVT = OpVT.getScalarType();
14391 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14392 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14394 return SDValue();
14395 BinOp = (ISD::NodeType)CandidateBinOp;
14396 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14397 };
14398
14399 // At each stage, we're looking for something that looks like:
14400 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14401 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14402 // i32 undef, i32 undef, i32 undef, i32 undef>
14403 // %a = binop <8 x i32> %op, %s
14404 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14405 // we expect something like:
14406 // <4,5,6,7,u,u,u,u>
14407 // <2,3,u,u,u,u,u,u>
14408 // <1,u,u,u,u,u,u,u>
14409 // While a partial reduction match would be:
14410 // <2,3,u,u,u,u,u,u>
14411 // <1,u,u,u,u,u,u,u>
14412 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14413 SDValue PrevOp;
14414 for (unsigned i = 0; i < Stages; ++i) {
14415 unsigned MaskEnd = (1 << i);
14416
14417 if (Op.getOpcode() != CandidateBinOp)
14418 return PartialReduction(PrevOp, MaskEnd);
14419
14420 SDValue Op0 = Op.getOperand(0);
14421 SDValue Op1 = Op.getOperand(1);
14422
14424 if (Shuffle) {
14425 Op = Op1;
14426 } else {
14427 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14428 Op = Op0;
14429 }
14430
14431 // The first operand of the shuffle should be the same as the other operand
14432 // of the binop.
14433 if (!Shuffle || Shuffle->getOperand(0) != Op)
14434 return PartialReduction(PrevOp, MaskEnd);
14435
14436 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14437 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14438 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14439 return PartialReduction(PrevOp, MaskEnd);
14440
14441 PrevOp = Op;
14442 }
14443
14444 // Handle subvector reductions, which tend to appear after the shuffle
14445 // reduction stages.
14446 while (Op.getOpcode() == CandidateBinOp) {
14447 unsigned NumElts = Op.getValueType().getVectorNumElements();
14448 SDValue Op0 = Op.getOperand(0);
14449 SDValue Op1 = Op.getOperand(1);
14450 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14452 Op0.getOperand(0) != Op1.getOperand(0))
14453 break;
14454 SDValue Src = Op0.getOperand(0);
14455 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14456 if (NumSrcElts != (2 * NumElts))
14457 break;
14458 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14459 Op1.getConstantOperandAPInt(1) == NumElts) &&
14460 !(Op1.getConstantOperandAPInt(1) == 0 &&
14461 Op0.getConstantOperandAPInt(1) == NumElts))
14462 break;
14463 Op = Src;
14464 }
14465
14466 BinOp = (ISD::NodeType)CandidateBinOp;
14467 return Op;
14468}
14469
14471 EVT VT = N->getValueType(0);
14472 EVT EltVT = VT.getVectorElementType();
14473 unsigned NE = getMaxRuntimeNumElements(VT);
14474
14475 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14476 reportFatalUsageError("Cannot unroll scalable vector!");
14477
14478 assert(NE && "Nothing to unroll!");
14479 SDLoc dl(N);
14480
14481 // If ResNE is 0, fully unroll the vector op.
14482 if (ResNE == 0)
14483 ResNE = NE;
14484 else if (NE > ResNE)
14485 NE = ResNE;
14486
14487 if (N->getNumValues() == 2) {
14488 SmallVector<SDValue, 8> Scalars0, Scalars1;
14489 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14490 EVT VT1 = N->getValueType(1);
14491 EVT EltVT1 = VT1.getVectorElementType();
14492
14493 unsigned i;
14494 for (i = 0; i != NE; ++i) {
14495 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14496 SDValue Operand = N->getOperand(j);
14497 EVT OperandVT = Operand.getValueType();
14498
14499 // A vector operand; extract a single element.
14500 EVT OperandEltVT = OperandVT.getVectorElementType();
14501 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14502 }
14503
14504 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14505 Scalars0.push_back(EltOp);
14506 Scalars1.push_back(EltOp.getValue(1));
14507 }
14508
14509 for (; i < ResNE; ++i) {
14510 Scalars0.push_back(getUNDEF(EltVT));
14511 Scalars1.push_back(getUNDEF(EltVT1));
14512 }
14513
14515 : ElementCount::getFixed(ResNE);
14516 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14517 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14518 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14519 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14520 return getMergeValues({Vec0, Vec1}, dl);
14521 }
14522
14523 assert(N->getNumValues() == 1 &&
14524 "Can't unroll a vector with multiple results!");
14525
14527 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14528
14529 unsigned i;
14530 for (i= 0; i != NE; ++i) {
14531 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14532 SDValue Operand = N->getOperand(j);
14533 EVT OperandVT = Operand.getValueType();
14534 if (OperandVT.isVector()) {
14535 // A vector operand; extract a single element.
14536 EVT OperandEltVT = OperandVT.getVectorElementType();
14537 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14538 } else {
14539 // A scalar operand; just use it as is.
14540 Operands[j] = Operand;
14541 }
14542 }
14543
14544 switch (N->getOpcode()) {
14545 default: {
14546 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14547 N->getFlags()));
14548 break;
14549 }
14550 case ISD::VSELECT:
14551 Scalars.push_back(
14552 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14553 break;
14554 case ISD::SHL:
14555 case ISD::SRA:
14556 case ISD::SRL:
14557 case ISD::ROTL:
14558 case ISD::ROTR:
14559 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14561 Operands[1])));
14562 break;
14564 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14565 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14566 Operands[0],
14567 getValueType(ExtVT)));
14568 break;
14569 }
14570 case ISD::ADDRSPACECAST: {
14571 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14572 Scalars.push_back(
14573 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14574 ASC->getDestAddressSpace(), ASC->getFlags()));
14575 break;
14576 }
14577 }
14578 }
14579
14580 for (; i < ResNE; ++i)
14581 Scalars.push_back(getUNDEF(EltVT));
14582
14583 EVT VecVT = VT.isScalableVector()
14584 ? VT
14585 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14586 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14587}
14588
14589std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14590 SDNode *N, unsigned ResNE) {
14591 unsigned Opcode = N->getOpcode();
14592 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14593 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14594 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14595 "Expected an overflow opcode");
14596
14597 EVT ResVT = N->getValueType(0);
14598 EVT OvVT = N->getValueType(1);
14599 EVT ResEltVT = ResVT.getVectorElementType();
14600 EVT OvEltVT = OvVT.getVectorElementType();
14601 SDLoc dl(N);
14602
14603 // If ResNE is 0, fully unroll the vector op.
14604 unsigned NE = ResVT.getVectorNumElements();
14605 if (ResNE == 0)
14606 ResNE = NE;
14607 else if (NE > ResNE)
14608 NE = ResNE;
14609
14610 SmallVector<SDValue, 8> LHSScalars;
14611 SmallVector<SDValue, 8> RHSScalars;
14612 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14613 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14614
14615 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14616 SDVTList VTs = getVTList(ResEltVT, SVT);
14617 SmallVector<SDValue, 8> ResScalars;
14618 SmallVector<SDValue, 8> OvScalars;
14619 for (unsigned i = 0; i < NE; ++i) {
14620 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14621 SDValue Ov =
14622 getSelect(dl, OvEltVT, Res.getValue(1),
14623 getBoolConstant(true, dl, OvEltVT, ResVT),
14624 getConstant(0, dl, OvEltVT));
14625
14626 ResScalars.push_back(Res);
14627 OvScalars.push_back(Ov);
14628 }
14629
14630 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14631 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14632
14633 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14634 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14635 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14636 getBuildVector(NewOvVT, dl, OvScalars));
14637}
14638
14641 unsigned Bytes, int Dist,
14642 const SelectionDAG &DAG) {
14643 if (LS->isVolatile() || Base->isVolatile())
14644 return false;
14645 // TODO: probably too restrictive for atomics, revisit
14646 if (!LS->isSimple())
14647 return false;
14648 if (LS->isIndexed() || Base->isIndexed())
14649 return false;
14650 if (LS->getChain() != Base->getChain())
14651 return false;
14652 EVT VT = LS->getMemoryVT();
14653 if (VT.getSizeInBits() / 8 != Bytes)
14654 return false;
14655
14656 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14657 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14658
14659 int64_t Offset = 0;
14660 if (BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14661 return (Dist * (int64_t)Bytes == Offset);
14662 return false;
14663}
14664
14667 unsigned Bytes,
14668 int Dist) const {
14669 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14670}
14671
14674 unsigned Bytes,
14675 int Dist) const {
14676 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14677}
14678
14679/// InferPtrAlignment - Infer alignment of a load / store address. Return
14680/// std::nullopt if it cannot be inferred.
14682 // If this is a GlobalAddress + cst, return the alignment.
14683 const GlobalValue *GV = nullptr;
14684 int64_t GVOffset = 0;
14685 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14686 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14687 KnownBits Known(PtrWidth);
14689 unsigned AlignBits = Known.countMinTrailingZeros();
14690 if (AlignBits)
14691 return commonAlignment(Align::fromLog2(std::min(31U, AlignBits)),
14692 GVOffset);
14693 }
14694
14695 // If this is a direct reference to a stack slot, use information about the
14696 // stack slot's alignment.
14697 int FrameIdx = INT_MIN;
14698 int64_t FrameOffset = 0;
14700 FrameIdx = FI->getIndex();
14701 } else if (isBaseWithConstantOffset(Ptr) &&
14703 // Handle FI+Cst
14704 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14705 FrameOffset = Ptr.getConstantOperandVal(1);
14706 }
14707
14708 if (FrameIdx != INT_MIN) {
14710 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14711 }
14712
14713 return std::nullopt;
14714}
14715
14716/// Split the scalar node with EXTRACT_ELEMENT using the provided
14717/// VTs and return the low/high part.
14718std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14719 const SDLoc &DL,
14720 const EVT &LoVT,
14721 const EVT &HiVT) {
14722 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14723 "Split node must be a scalar type");
14724 SDValue Lo =
14726 SDValue Hi =
14728 return std::make_pair(Lo, Hi);
14729}
14730
14731/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14732/// which is split (or expanded) into two not necessarily identical pieces.
14733std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14734 // Currently all types are split in half.
14735 EVT LoVT, HiVT;
14736 if (!VT.isVector())
14737 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14738 else
14739 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14740
14741 return std::make_pair(LoVT, HiVT);
14742}
14743
14744/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14745/// type, dependent on an enveloping VT that has been split into two identical
14746/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14747std::pair<EVT, EVT>
14749 bool *HiIsEmpty) const {
14750 EVT EltTp = VT.getVectorElementType();
14751 // Examples:
14752 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14753 // custom VL=9 with enveloping VL=8/8 yields 8/1
14754 // custom VL=10 with enveloping VL=8/8 yields 8/2
14755 // etc.
14756 ElementCount VTNumElts = VT.getVectorElementCount();
14757 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14758 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14759 "Mixing fixed width and scalable vectors when enveloping a type");
14760 EVT LoVT, HiVT;
14761 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14762 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14763 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14764 *HiIsEmpty = false;
14765 } else {
14766 // Flag that hi type has zero storage size, but return split envelop type
14767 // (this would be easier if vector types with zero elements were allowed).
14768 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14769 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14770 *HiIsEmpty = true;
14771 }
14772 return std::make_pair(LoVT, HiVT);
14773}
14774
14775/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14776/// low/high part.
14777std::pair<SDValue, SDValue>
14778SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14779 const EVT &HiVT) {
14780 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14781 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14782 "Splitting vector with an invalid mixture of fixed and scalable "
14783 "vector types");
14785 N.getValueType().getVectorMinNumElements() &&
14786 "More vector elements requested than available!");
14787 SDValue Lo, Hi;
14788 Lo = getExtractSubvector(DL, LoVT, N, 0);
14789 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14790 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14791 // IDX with the runtime scaling factor of the result vector type. For
14792 // fixed-width result vectors, that runtime scaling factor is 1.
14794 return std::make_pair(Lo, Hi);
14795}
14796
14797std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14798 const SDLoc &DL) {
14799 // Split the vector length parameter.
14800 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14801 EVT VT = N.getValueType();
14803 "Expecting the mask to be an evenly-sized vector");
14804 SDValue HalfNumElts = getElementCount(
14806 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14807 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14808 return std::make_pair(Lo, Hi);
14809}
14810
14811/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14813 EVT VT = N.getValueType();
14816 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14817}
14818
14821 unsigned Start, unsigned Count,
14822 EVT EltVT) {
14823 EVT VT = Op.getValueType();
14824 if (Count == 0)
14826 if (EltVT == EVT())
14827 EltVT = VT.getVectorElementType();
14828 SDLoc SL(Op);
14829 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14830 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14831 }
14832}
14833
14834// getAddressSpace - Return the address space this GlobalAddress belongs to.
14836 return getGlobal()->getType()->getAddressSpace();
14837}
14838
14841 return Val.MachineCPVal->getType();
14842 return Val.ConstVal->getType();
14843}
14844
14845bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14846 unsigned &SplatBitSize,
14847 bool &HasAnyUndefs,
14848 unsigned MinSplatBits,
14849 bool IsBigEndian) const {
14850 EVT VT = getValueType(0);
14851 assert(VT.isVector() && "Expected a vector type");
14852 unsigned VecWidth = VT.getSizeInBits();
14853 if (MinSplatBits > VecWidth)
14854 return false;
14855
14856 // FIXME: The widths are based on this node's type, but build vectors can
14857 // truncate their operands.
14858 SplatValue = APInt(VecWidth, 0);
14859 SplatUndef = APInt(VecWidth, 0);
14860
14861 // Get the bits. Bits with undefined values (when the corresponding element
14862 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14863 // in SplatValue. If any of the values are not constant, give up and return
14864 // false.
14865 unsigned int NumOps = getNumOperands();
14866 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14867 unsigned EltWidth = VT.getScalarSizeInBits();
14868
14869 for (unsigned j = 0; j < NumOps; ++j) {
14870 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14871 SDValue OpVal = getOperand(i);
14872 unsigned BitPos = j * EltWidth;
14873
14874 if (OpVal.isUndef())
14875 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14876 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14877 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14878 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14879 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14880 else
14881 return false;
14882 }
14883
14884 // The build_vector is all constants or undefs. Find the smallest element
14885 // size that splats the vector.
14886 HasAnyUndefs = (SplatUndef != 0);
14887
14888 // FIXME: This does not work for vectors with elements less than 8 bits.
14889 while (VecWidth > 8) {
14890 // If we can't split in half, stop here.
14891 if (VecWidth & 1)
14892 break;
14893
14894 unsigned HalfSize = VecWidth / 2;
14895 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14896 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14897 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14898 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14899
14900 // If the two halves do not match (ignoring undef bits), stop here.
14901 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14902 MinSplatBits > HalfSize)
14903 break;
14904
14905 SplatValue = HighValue | LowValue;
14906 SplatUndef = HighUndef & LowUndef;
14907
14908 VecWidth = HalfSize;
14909 }
14910
14911 // FIXME: The loop above only tries to split in halves. But if the input
14912 // vector for example is <3 x i16> it wouldn't be able to detect a
14913 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14914 // optimizations. I guess that back in the days when this helper was created
14915 // vectors normally was power-of-2 sized.
14916
14917 SplatBitSize = VecWidth;
14918 return true;
14919}
14920
14922 BitVector *UndefElements) const {
14923 unsigned NumOps = getNumOperands();
14924 if (UndefElements) {
14925 UndefElements->clear();
14926 UndefElements->resize(NumOps);
14927 }
14928 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14929 if (!DemandedElts)
14930 return SDValue();
14931 SDValue Splatted;
14932 for (unsigned i = 0; i != NumOps; ++i) {
14933 if (!DemandedElts[i])
14934 continue;
14935 SDValue Op = getOperand(i);
14936 if (Op.isUndef()) {
14937 if (UndefElements)
14938 (*UndefElements)[i] = true;
14939 } else if (!Splatted) {
14940 Splatted = Op;
14941 } else if (Splatted != Op) {
14942 return SDValue();
14943 }
14944 }
14945
14946 if (!Splatted) {
14947 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14948 assert(getOperand(FirstDemandedIdx).isUndef() &&
14949 "Can only have a splat without a constant for all undefs.");
14950 return getOperand(FirstDemandedIdx);
14951 }
14952
14953 return Splatted;
14954}
14955
14957 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14958 return getSplatValue(DemandedElts, UndefElements);
14959}
14960
14962 SmallVectorImpl<SDValue> &Sequence,
14963 BitVector *UndefElements) const {
14964 unsigned NumOps = getNumOperands();
14965 Sequence.clear();
14966 if (UndefElements) {
14967 UndefElements->clear();
14968 UndefElements->resize(NumOps);
14969 }
14970 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14971 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14972 return false;
14973
14974 // Set the undefs even if we don't find a sequence (like getSplatValue).
14975 if (UndefElements)
14976 for (unsigned I = 0; I != NumOps; ++I)
14977 if (DemandedElts[I] && getOperand(I).isUndef())
14978 (*UndefElements)[I] = true;
14979
14980 // Iteratively widen the sequence length looking for repetitions.
14981 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14982 Sequence.append(SeqLen, SDValue());
14983 for (unsigned I = 0; I != NumOps; ++I) {
14984 if (!DemandedElts[I])
14985 continue;
14986 SDValue &SeqOp = Sequence[I % SeqLen];
14988 if (Op.isUndef()) {
14989 if (!SeqOp)
14990 SeqOp = Op;
14991 continue;
14992 }
14993 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14994 Sequence.clear();
14995 break;
14996 }
14997 SeqOp = Op;
14998 }
14999 if (!Sequence.empty())
15000 return true;
15001 }
15002
15003 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
15004 return false;
15005}
15006
15008 BitVector *UndefElements) const {
15009 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15010 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
15011}
15012
15015 BitVector *UndefElements) const {
15017 getSplatValue(DemandedElts, UndefElements));
15018}
15019
15022 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
15023}
15024
15027 BitVector *UndefElements) const {
15029 getSplatValue(DemandedElts, UndefElements));
15030}
15031
15036
15037int32_t
15039 uint32_t BitWidth) const {
15040 if (ConstantFPSDNode *CN =
15042 bool IsExact;
15043 APSInt IntVal(BitWidth);
15044 const APFloat &APF = CN->getValueAPF();
15045 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
15046 APFloat::opOK ||
15047 !IsExact)
15048 return -1;
15049
15050 return IntVal.exactLogBase2();
15051 }
15052 return -1;
15053}
15054
15056 bool IsLittleEndian, unsigned DstEltSizeInBits,
15057 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
15058 // Early-out if this contains anything but Undef/Constant/ConstantFP.
15059 if (!isConstant())
15060 return false;
15061
15062 unsigned NumSrcOps = getNumOperands();
15063 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15064 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15065 "Invalid bitcast scale");
15066
15067 // If the elements don't pack cleanly, don't attempt to recast.
15068 // TODO: Add handling (e.g. bitcast <33 x i8> --> <8 x i33>)
15069 if ((SrcEltSizeInBits % DstEltSizeInBits) != 0 &&
15070 (DstEltSizeInBits % SrcEltSizeInBits) != 0)
15071 return false;
15072
15073 // Extract raw src bits.
15074 SmallVector<APInt> SrcBitElements(NumSrcOps,
15075 APInt::getZero(SrcEltSizeInBits));
15076 BitVector SrcUndeElements(NumSrcOps, false);
15077
15078 for (unsigned I = 0; I != NumSrcOps; ++I) {
15080 if (Op.isUndef()) {
15081 SrcUndeElements.set(I);
15082 continue;
15083 }
15084 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15085 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15086 assert((CInt || CFP) && "Unknown constant");
15087 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15088 : CFP->getValueAPF().bitcastToAPInt();
15089 }
15090
15091 // Recast to dst width.
15092 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15093 SrcBitElements, UndefElements, SrcUndeElements);
15094 return true;
15095}
15096
15097void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15098 unsigned DstEltSizeInBits,
15099 SmallVectorImpl<APInt> &DstBitElements,
15100 ArrayRef<APInt> SrcBitElements,
15101 BitVector &DstUndefElements,
15102 const BitVector &SrcUndefElements) {
15103 unsigned NumSrcOps = SrcBitElements.size();
15104 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15105 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15106 "Invalid bitcast scale");
15107 assert(((SrcEltSizeInBits % DstEltSizeInBits) == 0 ||
15108 (DstEltSizeInBits % SrcEltSizeInBits) == 0) &&
15109 "Unsupported bitcast scale");
15110 assert(NumSrcOps == SrcUndefElements.size() && "Vector size mismatch");
15111
15112 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15113 DstUndefElements.clear();
15114 DstUndefElements.resize(NumDstOps, false);
15115 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15116
15117 // Concatenate src elements constant bits together into dst element.
15118 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15119 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15120 for (unsigned I = 0; I != NumDstOps; ++I) {
15121 DstUndefElements.set(I);
15122 APInt &DstBits = DstBitElements[I];
15123 for (unsigned J = 0; J != Scale; ++J) {
15124 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15125 if (SrcUndefElements[Idx])
15126 continue;
15127 DstUndefElements.reset(I);
15128 const APInt &SrcBits = SrcBitElements[Idx];
15129 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15130 "Illegal constant bitwidths");
15131 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15132 }
15133 }
15134 return;
15135 }
15136
15137 // Split src element constant bits into dst elements.
15138 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15139 for (unsigned I = 0; I != NumSrcOps; ++I) {
15140 if (SrcUndefElements[I]) {
15141 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15142 continue;
15143 }
15144 const APInt &SrcBits = SrcBitElements[I];
15145 for (unsigned J = 0; J != Scale; ++J) {
15146 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15147 APInt &DstBits = DstBitElements[Idx];
15148 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15149 }
15150 }
15151}
15152
15154 for (const SDValue &Op : op_values()) {
15155 unsigned Opc = Op.getOpcode();
15156 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15157 return false;
15158 }
15159 return true;
15160}
15161
15162std::optional<std::pair<APInt, APInt>>
15164 unsigned NumOps = getNumOperands();
15165 if (NumOps < 2)
15166 return std::nullopt;
15167
15168 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15169 APInt Start, Stride;
15170 int FirstIdx = -1, SecondIdx = -1;
15171
15172 // Find the first two non-undef constant elements to determine Start and
15173 // Stride, then verify all remaining elements match the sequence.
15174 for (unsigned I = 0; I < NumOps; ++I) {
15176 if (Op->isUndef())
15177 continue;
15178 if (!isa<ConstantSDNode>(Op))
15179 return std::nullopt;
15180
15181 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15182 if (FirstIdx < 0) {
15183 FirstIdx = I;
15184 Start = Val;
15185 } else if (SecondIdx < 0) {
15186 SecondIdx = I;
15187 // Compute stride using modular arithmetic. Simple division would handle
15188 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15189 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15190 // Note that modular arithmetic is agnostic to signed/unsigned.
15191 unsigned IdxDiff = I - FirstIdx;
15192 APInt ValDiff = Val - Start;
15193
15194 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15195 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15196 if (ValDiff.countr_zero() < CommonPow2Bits)
15197 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15198 IdxDiff >>= CommonPow2Bits;
15199 ValDiff.lshrInPlace(CommonPow2Bits);
15200
15201 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15202 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15203 // one, but we could try all candidates to handle more cases.
15204 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15205 if (Stride.isZero())
15206 return std::nullopt;
15207
15208 // Step 3: Adjust Start based on the first defined element's index.
15209 Start -= Stride * FirstIdx;
15210 } else {
15211 // Verify this element matches the sequence.
15212 if (Val != Start + Stride * I)
15213 return std::nullopt;
15214 }
15215 }
15216
15217 // Need at least two defined elements.
15218 if (SecondIdx < 0)
15219 return std::nullopt;
15220
15221 return std::make_pair(Start, Stride);
15222}
15223
15225 // Find the first non-undef value in the shuffle mask.
15226 unsigned i, e;
15227 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15228 /* search */;
15229
15230 // If all elements are undefined, this shuffle can be considered a splat
15231 // (although it should eventually get simplified away completely).
15232 if (i == e)
15233 return true;
15234
15235 // Make sure all remaining elements are either undef or the same as the first
15236 // non-undef value.
15237 for (int Idx = Mask[i]; i != e; ++i)
15238 if (Mask[i] >= 0 && Mask[i] != Idx)
15239 return false;
15240 return true;
15241}
15242
15243// Returns true if it is a constant integer BuildVector or constant integer,
15244// possibly hidden by a bitcast.
15246 SDValue N, bool AllowOpaques) const {
15248
15249 if (auto *C = dyn_cast<ConstantSDNode>(N))
15250 return AllowOpaques || !C->isOpaque();
15251
15253 return true;
15254
15255 // Treat a GlobalAddress supporting constant offset folding as a
15256 // constant integer.
15257 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15258 if (GA->getOpcode() == ISD::GlobalAddress &&
15259 TLI->isOffsetFoldingLegal(GA))
15260 return true;
15261
15262 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15263 isa<ConstantSDNode>(N.getOperand(0)))
15264 return true;
15265 return false;
15266}
15267
15268// Returns true if it is a constant float BuildVector or constant float.
15271 return true;
15272
15274 return true;
15275
15276 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15277 isa<ConstantFPSDNode>(N.getOperand(0)))
15278 return true;
15279
15280 return false;
15281}
15282
15283std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15284 ConstantSDNode *Const =
15285 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15286 if (!Const)
15287 return std::nullopt;
15288
15289 EVT VT = N.getValueType();
15290 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15291 switch (TLI->getBooleanContents(VT)) {
15293 if (CVal.isOne())
15294 return true;
15295 if (CVal.isZero())
15296 return false;
15297 return std::nullopt;
15299 if (CVal.isAllOnes())
15300 return true;
15301 if (CVal.isZero())
15302 return false;
15303 return std::nullopt;
15305 return CVal[0];
15306 }
15307 llvm_unreachable("Unknown BooleanContent enum");
15308}
15309
15310void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15311 assert(!Node->OperandList && "Node already has operands");
15313 "too many operands to fit into SDNode");
15314 SDUse *Ops = OperandRecycler.allocate(
15315 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15316
15317 bool IsDivergent = false;
15318 for (unsigned I = 0; I != Vals.size(); ++I) {
15319 Ops[I].setUser(Node);
15320 Ops[I].setInitial(Vals[I]);
15321 EVT VT = Ops[I].getValueType();
15322
15323 // Skip Chain. It does not carry divergence.
15324 if (VT != MVT::Other &&
15325 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15326 Ops[I].getNode()->isDivergent()) {
15327 IsDivergent = true;
15328 }
15329 }
15330 Node->NumOperands = Vals.size();
15331 Node->OperandList = Ops;
15332 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15333 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15334 Node->SDNodeBits.IsDivergent = IsDivergent;
15335 }
15336 checkForCycles(Node);
15337}
15338
15341 size_t Limit = SDNode::getMaxNumOperands();
15342 while (Vals.size() > Limit) {
15343 unsigned SliceIdx = Vals.size() - Limit;
15344 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15345 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15346 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15347 Vals.emplace_back(NewTF);
15348 }
15349 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15350}
15351
15353 EVT VT, SDNodeFlags Flags) {
15354 switch (Opcode) {
15355 default:
15356 return SDValue();
15357 case ISD::ADD:
15358 case ISD::OR:
15359 case ISD::XOR:
15360 case ISD::UMAX:
15361 case ISD::MUL:
15362 case ISD::AND:
15363 case ISD::UMIN:
15364 case ISD::SMAX:
15365 case ISD::SMIN:
15367 VT);
15368 case ISD::FADD:
15369 // If flags allow, prefer positive zero since it's generally cheaper
15370 // to materialize on most targets.
15371 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15372 case ISD::FMUL:
15373 return getConstantFP(1.0, DL, VT);
15374 case ISD::FMINNUM:
15375 case ISD::FMAXNUM:
15376 case ISD::FMINIMUMNUM:
15377 case ISD::FMAXIMUMNUM: {
15378 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15379 // depending on fast-math flags (FMF).
15380 const fltSemantics &Semantics = VT.getFltSemantics();
15381 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15382 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15383 APFloat::getLargest(Semantics);
15384 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15385 NeutralAF.changeSign();
15386
15387 return getConstantFP(NeutralAF, DL, VT);
15388 }
15389 case ISD::FMINIMUM:
15390 case ISD::FMAXIMUM: {
15391 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15392 const fltSemantics &Semantics = VT.getFltSemantics();
15393 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15394 : APFloat::getLargest(Semantics);
15395 if (Opcode == ISD::FMAXIMUM)
15396 NeutralAF.changeSign();
15397
15398 return getConstantFP(NeutralAF, DL, VT);
15399 }
15400
15401 }
15402}
15403
15405 SDValue Acc, SDValue LHS,
15406 SDValue RHS) {
15407 EVT AccVT = Acc.getValueType();
15408 if (AccVT.isFloatingPoint()) {
15409 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15410 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15411 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15412 }
15415 "Unexpected opcode");
15416 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15417 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15418 return getNegative(MLA, DL, AccVT);
15419}
15420
15421/// Helper used to make a call to a library function that has one argument of
15422/// pointer type.
15423///
15424/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15425/// used to get or set floating-point state. They have one argument of pointer
15426/// type, which points to the memory region containing bits of the
15427/// floating-point state. The value returned by such function is ignored in the
15428/// created call.
15429///
15430/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15431/// \param Ptr Pointer used to save/load state.
15432/// \param InChain Ingoing token chain.
15433/// \param Node Node being legalized
15434/// \returns Outgoing chain token.
15436 SDValue InChain, SDNode *Node) {
15437 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15438 RTLIB::LibcallImpl LibcallImpl =
15439 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15440 if (LibcallImpl == RTLIB::Unsupported) {
15441 getContext()->emitError(Twine("no libcall available for ") +
15442 Node->getOperationName(this));
15443 return InChain;
15444 }
15445
15447 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15448 SDValue Callee =
15449 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15451 CLI.setDebugLoc(SDLoc(Node))
15452 .setChain(InChain)
15453 .setLibCallee(Libcalls->getLibcallImplCallingConv(LibcallImpl),
15454 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15455 return TLI->LowerCallTo(CLI).second;
15456}
15457
15459 assert(From && To && "Invalid SDNode; empty source SDValue?");
15460 auto I = SDEI.find(From);
15461 if (I == SDEI.end())
15462 return;
15463
15464 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15465 // the iterator, hence the need to make a copy to prevent a use-after-free.
15466 NodeExtraInfo NEI = I->second;
15467 if (LLVM_LIKELY(!NEI.PCSections)) {
15468 // No deep copy required for the types of extra info set.
15469 //
15470 // FIXME: Investigate if other types of extra info also need deep copy. This
15471 // depends on the types of nodes they can be attached to: if some extra info
15472 // is only ever attached to nodes where a replacement To node is always the
15473 // node where later use and propagation of the extra info has the intended
15474 // semantics, no deep copy is required.
15475 SDEI[To] = std::move(NEI);
15476 return;
15477 }
15478
15479 const SDNode *EntrySDN = getEntryNode().getNode();
15480
15481 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15482 // through the replacement of From with To. Otherwise, replacements of a node
15483 // (From) with more complex nodes (To and its operands) may result in lost
15484 // extra info where the root node (To) is insignificant in further propagating
15485 // and using extra info when further lowering to MIR.
15486 //
15487 // In the first step pre-populate the visited set with the nodes reachable
15488 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15489 // DAG that is not new and should be left untouched.
15490 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15491 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15492 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15493 if (MaxDepth == 0) {
15494 // Remember this node in case we need to increase MaxDepth and continue
15495 // populating FromReach from this node.
15496 Leafs.emplace_back(N);
15497 return;
15498 }
15499 if (!FromReach.insert(N).second)
15500 return;
15501 for (const SDValue &Op : N->op_values())
15502 Self(Self, Op.getNode(), MaxDepth - 1);
15503 };
15504
15505 // Copy extra info to To and all its transitive operands (that are new).
15507 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15508 if (FromReach.contains(N))
15509 return true;
15510 if (!Visited.insert(N).second)
15511 return true;
15512 if (EntrySDN == N)
15513 return false;
15514 for (const SDValue &Op : N->op_values()) {
15515 if (N == To && Op.getNode() == EntrySDN) {
15516 // Special case: New node's operand is the entry node; just need to
15517 // copy extra info to new node.
15518 break;
15519 }
15520 if (!Self(Self, Op.getNode()))
15521 return false;
15522 }
15523 // Copy only if entry node was not reached.
15524 SDEI[N] = std::move(NEI);
15525 return true;
15526 };
15527
15528 // We first try with a lower MaxDepth, assuming that the path to common
15529 // operands between From and To is relatively short. This significantly
15530 // improves performance in the common case. The initial MaxDepth is big
15531 // enough to avoid retry in the common case; the last MaxDepth is large
15532 // enough to avoid having to use the fallback below (and protects from
15533 // potential stack exhaustion from recursion).
15534 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15535 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15536 // StartFrom is the previous (or initial) set of leafs reachable at the
15537 // previous maximum depth.
15539 std::swap(StartFrom, Leafs);
15540 for (const SDNode *N : StartFrom)
15541 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15542 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15543 return;
15544 // This should happen very rarely (reached the entry node).
15545 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15546 assert(!Leafs.empty());
15547 }
15548
15549 // This should not happen - but if it did, that means the subgraph reachable
15550 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15551 // could not visit all reachable common operands. Consequently, we were able
15552 // to reach the entry node.
15553 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15554 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15555 // Best-effort fallback if assertions disabled.
15556 SDEI[To] = std::move(NEI);
15557}
15558
15560 assert(VT.isVector() && "Can only unroll vector types!");
15561 if (VT.isFixedLengthVector())
15562 return VT.getVectorNumElements();
15563
15564 const MachineFunction &MF = getMachineFunction();
15565 const Function &F = MF.getFunction();
15566
15567 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15568 if (MaxVScale.ugt(VScaleUnrollLimit))
15569 return 0;
15570
15571 bool Overflow;
15572 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15573 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15574 if (Overflow)
15575 return 0;
15576
15577 return MaxNElts.getZExtValue();
15578}
15579
15581 ArrayRef<SDValue> Scalars) {
15582 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15583 "Element count mismatch!");
15584 if (VT.isFixedLengthVector())
15585 return getBuildVector(VT, DL, Scalars);
15586
15587 SDValue Vec = getPOISON(VT);
15588 // Iterate in reverse so result remains poison until we encounter a lane that
15589 // exists, after which all lower-numbered lanes must also exist.
15590 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15591 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15592
15593 return Vec;
15594}
15595
15596#ifndef NDEBUG
15597static void checkForCyclesHelper(const SDNode *N,
15600 const llvm::SelectionDAG *DAG) {
15601 // If this node has already been checked, don't check it again.
15602 if (Checked.count(N))
15603 return;
15604
15605 // If a node has already been visited on this depth-first walk, reject it as
15606 // a cycle.
15607 if (!Visited.insert(N).second) {
15608 errs() << "Detected cycle in SelectionDAG\n";
15609 dbgs() << "Offending node:\n";
15610 N->dumprFull(DAG); dbgs() << "\n";
15611 abort();
15612 }
15613
15614 for (const SDValue &Op : N->op_values())
15615 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15616
15617 Checked.insert(N);
15618 Visited.erase(N);
15619}
15620#endif
15621
15623 const llvm::SelectionDAG *DAG,
15624 bool force) {
15625#ifndef NDEBUG
15626 bool check = force;
15627#ifdef EXPENSIVE_CHECKS
15628 check = true;
15629#endif // EXPENSIVE_CHECKS
15630 if (check) {
15631 assert(N && "Checking nonexistent SDNode");
15634 checkForCyclesHelper(N, visited, checked, DAG);
15635 }
15636#endif // !NDEBUG
15637}
15638
15639void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15640 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15641}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
static bool isConstant(const MachineInstr &MI)
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
#define __asan_unpoison_memory_region(p, size)
Definition Compiler.h:621
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:347
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
static MaybeAlign getAlign(Value *Ptr)
iv users
Definition IVUsers.cpp:48
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG)
static bool isConstantSplatVector(SDValue N, APInt &SplatValue, unsigned MinSizeInBits)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register const TargetRegisterInfo * TRI
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
PowerPC Reduce CR logical Operation
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
int64_t C1
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Contains matchers for matching SelectionDAG nodes and values.
SI Fold Operands
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static bool shouldLowerMemFuncForSize(const MachineFunction &MF, SelectionDAG &DAG)
static SDValue getFixedOrScalableQuantity(SelectionDAG &DAG, const SDLoc &DL, EVT VT, Ty Quantity)
static std::pair< SDValue, SDValue > getRuntimeCallSDValueHelper(SDValue Chain, const SDLoc &dl, TargetLowering::ArgListTy &&Args, const CallInst *CI, RTLIB::Libcall Call, SelectionDAG *DAG, const TargetLowering *TLI)
static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo)
Lower the call to 'memset' intrinsic function into a series of store operations.
static std::optional< APInt > FoldValueWithUndef(unsigned Opcode, const APInt &C1, bool IsUndef1, const APInt &C2, bool IsUndef2)
static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, SelectionDAG &DAG)
static cl::opt< int > VScaleUnrollLimit("vscale-unroll-limit", cl::desc("Maximum vscale for which vector unrolling is allowed."), cl::Hidden, cl::init(64))
static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, const TargetLowering &TLI, const ConstantDataArraySlice &Slice)
getMemsetStringVal - Similar to getMemsetValue.
static cl::opt< bool > EnableMemCpyDAGOpt("enable-memcpy-dag-opt", cl::Hidden, cl::init(true), cl::desc("Gang up loads and stores generated by inlining of memcpy"))
static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B)
static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N)
Serialize a node the way SDNodes were uniqued before SDNodeKey, to cross-check the typed comparison a...
static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef< int > M)
Swaps the values of N1 and N2.
static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice)
Returns true if memcpy source is constant data.
static TargetLoweringBase::ArgListEntry getAtomicMemOpSizeArg(SelectionDAG *DAG, const SDLoc &dl, SDValue Size)
static bool hasSpecialNszSemantics(unsigned Opcode)
Return true if the standard nsz semantics may not apply for this opcode.
static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike)
static bool doNotCSE(SDNode *N)
doNotCSE - Return true if CSE should not be performed for this node.
static cl::opt< int > MaxLdStGlue("ldstmemcpy-glue-max", cl::desc("Number limit for gluing ld/st of memcpy."), cl::Hidden, cl::init(0))
static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth)
static SDValue getMemIntrinsicSize(SelectionDAG &DAG, const SDLoc &dl, SDValue Size, unsigned DstAS, unsigned SrcAS)
The length of a memory intrinsic (e.g.
static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, const DataLayout &DL, unsigned AS)
static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SelectionDAG &DAG)
Try to simplify vector concatenation to an input value, undef, or build vector.
static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, SelectionDAG &DAG, SDValue Ptr, int64_t Offset=0)
InferPointerInfo - If the specified ptr/offset is a frame index, infer a MachinePointerInfo record fr...
static bool isInTailCallPositionWrapper(const CallInst *CI, const SelectionDAG *SelDAG, bool AllowReturnsFirstArg)
static bool keyMatches(const SDNodeKey &Key, const SDNode &N)
static bool areNonVolatileConsecutiveLoadsOrStores(LSBaseSDNode *LS, LSBaseSDNode *Base, unsigned Bytes, int Dist, const SelectionDAG &DAG)
static bool gluePropagatesDivergence(const SDNode *Node)
Return true if a glue output should propagate divergence information.
static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N, unsigned Opc)
If this is an SDNode with special info, add this info to the NodeID data.
static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G)
static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs)
makeVTList - Return an instance of the SDVTList struct initialized with the specified members.
static void checkForCyclesHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallPtrSetImpl< const SDNode * > &Checked, const llvm::SelectionDAG *DAG)
static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, SmallVector< SDValue, 32 > &OutChains, unsigned From, unsigned To, SmallVector< SDValue, 16 > &OutLoadChains, SmallVector< SDValue, 16 > &OutStoreChains)
static int isSignedOp(ISD::CondCode Opcode)
For an integer comparison, return 1 if the comparison is a signed operation and 2 if the result is an...
static std::optional< APInt > FoldValue(unsigned Opcode, const APInt &C1, const APInt &C2)
static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SelectionDAG &DAG)
static cl::opt< unsigned > MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192), cl::desc("DAG combiner limit number of steps when searching DAG " "for predecessor nodes"))
static APInt getDemandAllEltsMask(SDValue V)
Construct a DemandedElts mask which demands all elements of V.
static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo, BatchAAResults *BatchAA, const MDNode *DstMemCacheHint, const MDNode *SrcMemCacheHint)
static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
static void removeOperands(MachineInstr &MI, unsigned i)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static unsigned getSize(unsigned Kind)
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:364
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:363
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1224
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6044
bool isNegative() const
Definition APFloat.h:1583
bool isFinite() const
Definition APFloat.h:1588
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
bool isZero() const
Definition APFloat.h:1579
LLVM_READONLY bool isOne() const
Definition APFloat.h:1661
bool isLargest() const
Definition APFloat.h:1599
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
bool isPosZero() const
Definition APFloat.h:1594
bool isNegZero() const
Definition APFloat.h:1595
void changeSign()
Definition APFloat.h:1401
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:836
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1387
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:764
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1437
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
unsigned getSrcAddressSpace() const
unsigned getDestAddressSpace() const
static Capacity get(size_t N)
Get the capacity of an array that can hold at least N elements.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI BaseIndexOffset match(const SDNode *N, const SelectionDAG &DAG)
Parses tree in N for base, index, offset addresses.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:207
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
const BlockAddress * getBlockAddress() const
The address of a basic block.
Definition Constants.h:1088
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool getConstantRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits, SmallVectorImpl< APInt > &RawBitElements, BitVector &UndefElements) const
Extract the raw bit data from a build vector of Undef, Constant or ConstantFP node elements.
static LLVM_ABI void recastRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits, SmallVectorImpl< APInt > &DstBitElements, ArrayRef< APInt > SrcBitElements, BitVector &DstUndefElements, const BitVector &SrcUndefElements)
Recast bit data SrcBitElements to DstEltSizeInBits wide elements.
LLVM_ABI bool getRepeatedSequence(const APInt &DemandedElts, SmallVectorImpl< SDValue > &Sequence, BitVector *UndefElements=nullptr) const
Find the shortest repeating sequence of values in the build vector.
LLVM_ABI ConstantFPSDNode * getConstantFPSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant FP or null if this is not a constant FP splat.
LLVM_ABI SDValue getSplatValue(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted value or a null value if this is not a splat.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI ConstantSDNode * getConstantSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant or null if this is not a constant splat.
LLVM_ABI int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, uint32_t BitWidth) const
If this is a constant FP splat and the splatted constant FP is an exact power or 2,...
LLVM_ABI std::optional< std::pair< APInt, APInt > > isArithmeticSequence() const
If this BuildVector is constant and represents an arithmetic sequence "<a, a+n, a+2n,...
LLVM_ABI bool isConstant() const
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
static LLVM_ABI bool isValueValidForType(EVT VT, const APFloat &Val)
const APFloat & getValueAPF() const
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValue() const
Definition Constants.h:464
This is the shared class of boolean and integer constants.
Definition Constants.h:87
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
LLVM_ABI Type * getType() const
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
DWARF expression.
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI const DIExpression * convertToVariadicExpression(const DIExpression *Expr)
If Expr is a non-variadic expression (i.e.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
Base class for variables.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
const char * getSymbol() const
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
Data structure describing the variable locations in a function.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
LLVM_ABI unsigned getAddressSpace() const
const GlobalValue * getGlobal() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
This class is used to form a handle around another node that is persistent and is updated across invo...
const SDValue & getValue() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static KnownFPClass getEmpty()
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Base class for LoadSDNode and StoreSDNode.
Tracks which library functions to use for a particular subtarget or function.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
This SDNode is used for LIFETIME_START/LIFETIME_END values.
This class is used to represent ISD::LOAD nodes.
static LocationSize precise(uint64_t Value)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
Machine Value Type.
SimpleValueType SimpleTy
static LLVM_ABI MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
static MVT getIntegerVT(unsigned BitWidth)
Abstract base class for all machine specific constantpool value subclasses.
virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID)=0
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
A description of a memory reference used in the backend.
const MDNode * getRanges() const
Return the range tag for the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
An SDNode that represents everything that will be needed to construct a MachineInstr.
This class is used to represent an MGATHER node.
This class is used to represent an MLOAD node.
This class is used to represent an MSTORE node.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
size_t getNumMemOperands() const
Return the number of memory operands.
LLVM_ABI MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt, PointerUnion< MachineMemOperand *, MachineMemOperand ** > memrefs)
Constructor that supports single or multiple MMOs.
PointerUnion< MachineMemOperand *, MachineMemOperand ** > MemRefs
Memory reference information.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
ArrayRef< MachineMemOperand * > memoperands() const
Return the memory operands for this node.
unsigned getRawSubclassData() const
Return the SubclassData value, without HasDebugValue.
EVT getMemoryVT() const
Return the type of the in-memory value.
Representation for a specific memory location.
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:235
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Analysis providing profile information.
void Deallocate(SubClass *E)
Deallocate - Release storage for the pointed-to object.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Keeps track of dbg_value information through SDISel.
LLVM_ABI void add(SDDbgValue *V, bool isParameter)
LLVM_ABI void erase(const SDNode *Node)
Invalidate all DbgValues attached to the node and remove it from the Node-to-DbgValues map.
Holds the information from a dbg_label node through SDISel.
Holds the information for a single machine location through SDISel; either an SDNode,...
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
@ SDNODE
Value is the result of an expression.
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
unsigned getIROrder() const
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
LLVM_ABI void dumprFull(const SelectionDAG *G=nullptr) const
printrFull to dbgs().
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isDivergent() const
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
static constexpr size_t getMaxNumOperands()
Return the maximum number of operands that a SDNode can hold.
iterator_range< use_iterator > uses()
MemSDNodeBitfields MemSDNodeBits
bool getHasDebugValue() const
SDNodeFlags getFlags() const
void setNodeId(int Id)
Set unique node id.
LLVM_ABI void intersectFlagsWith(const SDNodeFlags Flags)
Clear any flags in this node that aren't also set in Flags.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
static LLVM_ABI bool areOnlyUsersOf(ArrayRef< const SDNode * > Nodes, const SDNode *N)
Return true if all the users of N are contained in Nodes.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if this node is an operand of N.
const APInt & getConstantOperandAPInt(unsigned Num) const
Helper method returns the APInt of a ConstantSDNode operand.
std::optional< APInt > bitcastToAPInt() const
LLVM_ABI bool hasPredecessor(const SDNode *N) const
Return true if N is a predecessor of this node.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
op_iterator op_end() const
op_iterator op_begin() const
static use_iterator use_end()
LLVM_ABI void DropOperands()
Release the operands and set this node to have zero operands.
SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
Create an SDNode.
Represents a use of a SDNode.
SDNode * getUser()
This returns the SDNode that contains this Use.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if the referenced return value is an operand of N.
SDValue()=default
LLVM_ABI bool reachesChainWithoutSideEffects(SDValue Dest, unsigned Depth=2) const
Return true if this operand (which must be a chain) reaches the specified operand without crossing an...
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
virtual void verifyTargetNode(const SelectionDAG &DAG, const SDNode *N) const
Checks that the given target-specific node is valid. Aborts if it is not.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC)
LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI)
In most cases this function returns the ABI alignment for a given type, except for illegal vector typ...
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
LLVM_ABI std::pair< SDValue, SDValue > getMemccpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI)
Lower a memccpy operation into a target library call and return the resulting chain and call result a...
LLVM_ABI SDValue emitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, const SDLoc &DL, SDValue Chain)
Emit a store/load combination to the stack.
LLVM_ABI bool isKnownNeverLogicalZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Test whether the given floating point SDValue (or all elements of it, if it is a vector) is known to ...
LLVM_ABI SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsExpanding=false)
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
LLVM_ABI SDValue getSplatSourceVector(SDValue V, int &SplatIndex)
If V is a splatted value, return the source vector and its splat index.
LLVM_ABI SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI OverflowKind computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const
Determine if the result of the unsigned sub of 2 nodes can overflow.
LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth=0) const
Get the upper bound on bit size for this Value Op as a signed integer.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
LLVM_ABI std::pair< SDValue, SDValue > getStrlen(SDValue Chain, const SDLoc &dl, SDValue Src, const CallInst *CI)
Lower a strlen operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, ISD::LoadExtType ExtTy)
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, SDNode *Node)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI std::optional< bool > isBoolConstant(SDValue N) const
Check if a value \op N is a constant using the target's BooleanContent for its type.
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
LLVM_ABI ConstantRange computeConstantRange(SDValue Op, bool ForSigned, unsigned Depth=0) const
Determine the possible constant range of an integer or vector of integers.
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI void updateDivergence(SDNode *N)
LLVM_ABI SDValue getSplatValue(SDValue V, bool LegalTypes=false)
If V is a splat vector, return its scalar source operand by extracting that element from the source v...
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getAtomicMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Value, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo)
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDNode * getNodeIfExists(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops, const SDNodeFlags Flags, bool AllowCommute=false)
Get the specified node if it's already available, or else return NULL.
LLVM_ABI SDValue getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, uint64_t Guid, uint64_t Index, uint32_t Attr)
Creates a PseudoProbeSDNode with function GUID Guid and the index of the block Index it is probing,...
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
LLVM_ABI const BasicBlock * getBasicBlock() const
LLVM_ABI SelectionDAG(const TargetMachine &TM, CodeGenOptLevel)
LLVM_ABI SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getStridedLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI SDValue getSymbolFunctionGlobalAddress(SDValue Op, Function **TargetFunction=nullptr)
Return a GlobalAddress of the function from the current module with name matching the given ExternalS...
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm)
Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
OverflowKind
Used to represent the possible overflow behavior of an operation.
static LLVM_ABI unsigned getHasPredecessorMaxSteps()
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI bool cannotBeOrderedNegativeFP(SDValue Op) const
Test whether the given float value is known to be positive.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI bool calculateDivergence(SDNode *N)
LLVM_ABI std::pair< SDValue, SDValue > getStrcmp(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A)
Return an AssertAlignSDNode.
LLVM_ABI SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
LLVM_ABI bool canIgnoreSignBitOfZero(const SDUse &Use) const
Check if the user of Use produces the same result regardless of the sign of a zero in the used float ...
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI bool hasSwiftErrorArg() const
LLVM_ABI SDValue buildVectorFromUnrolledParts(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Scalars)
Returns a vector constructed from the scalar values in order.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI bool isEqualTo(SDValue A, SDValue B) const
Test whether two SDValues are known to compare equal.
static constexpr unsigned MaxRecursionDepth
LLVM_ABI unsigned getMaxRuntimeNumElements(EVT VT) const
Returns the maximum runtime number of elements in VT if known, or 0 otherwise.
LLVM_ABI SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
LLVM_ABI SDValue getIdentityElement(unsigned Opcode, const SDLoc &DL, EVT VT, SDNodeFlags Flags)
Get the (commutative) identity element for the given opcode, if it exists.
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
LLVM_ABI SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
For each demanded element of a vector, see if it is known to be zero.
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
LLVM_ABI void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI std::pair< SDValue, SDValue > UnrollVectorOverflowOp(SDNode *N, unsigned ResNE=0)
Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
LLVM_ABI std::pair< SDValue, SDValue > getStrcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, const CallInst *CI)
Lower a strcpy operation into a target library call and return the resulting chain and call result as...
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const
Test whether the given value is a constant FP or similar node.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getPartialReduceMLS(unsigned Opc, const SDLoc &DL, SDValue Acc, SDValue LHS, SDValue RHS)
Get an expression that implements a partial multiply-subtract reduction.
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(SDValue Op, bool ForSigned, unsigned Depth=0) const
Combine constant ranges from computeConstantRange() and computeKnownBits().
const SelectionDAGTargetInfo & getSelectionDAGInfo() const
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDDbgLabel * getDbgLabel(DILabel *Label, const DebugLoc &DL, unsigned O)
Creates a SDDbgLabel node.
LLVM_ABI SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI OverflowKind computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const
Determine if the result of the unsigned mul of 2 nodes can overflow.
LLVM_ABI void copyExtraInfo(SDNode *From, SDNode *To)
Copy extra info associated with one node to another.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI SDValue getLoadFFVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachineMemOperand *MMO)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
LLVM_ABI std::pair< SDValue, SDValue > getMemcmp(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, const CallInst *CI)
Lower a memcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getSrcValue(const Value *v)
Construct a node to track a Value* through the backend.
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const
Determine if the result of the signed mul of 2 nodes can overflow.
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
LLVM_ABI void dump() const
Dump the textual format of this DAG.
LLVM_ABI bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if '(Op & Mask) == Mask'.
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI void AddDbgLabel(SDDbgLabel *DB)
Add a dbg_label SDNode.
bool isConstantValueOfAnyType(SDValue N) const
LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, bool ConsiderFlags=true, unsigned Depth=0) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
SDValue getInsertVectorElt(const SDLoc &DL, SDValue Vec, SDValue Elt, unsigned Idx)
Insert Elt into Vec at offset Idx.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDDbgValue * getVRegDbgValue(DIVariable *Var, DIExpression *Expr, Register VReg, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a VReg SDDbgValue node.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI KnownFPClass computeKnownFPClass(SDValue Op, FPClassTest InterestedClasses, unsigned Depth=0) const
Determine floating-point class information about Op.
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI std::optional< unsigned > getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI std::pair< SDValue, SDValue > SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL)
Split the explicit vector length parameter of a VP operation.
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getMaskFromElementCount(const SDLoc &DL, EVT VT, ElementCount Len)
Return a vector with the first 'Len' lanes set to true and remaining lanes set to false.
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, const MDNode *Ranges=nullptr, bool IsExpanding=false)
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDDbgValue * getConstantDbgValue(DIVariable *Var, DIExpression *Expr, const Value *C, const DebugLoc &DL, unsigned O)
Creates a constant SDDbgValue node.
LLVM_ABI SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain, int FrameIndex)
Creates a LifetimeSDNode that starts (IsStart==true) or ends (IsStart==false) the lifetime of the Fra...
ArrayRef< SDDbgValue * > GetDbgValues(const SDNode *SD) const
Get the debug values which reference the given SDNode.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the signed addition of 2 nodes can overflow.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
ilist< SDNode >::size_type allnodes_size() const
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
LLVM_ABI SDValue FoldConstantBuildVector(BuildVectorSDNode *BV, const SDLoc &DL, EVT DstEltVT)
Fold BUILD_VECTOR of constants/undefs to the destination type BUILD_VECTOR of constants/undefs elemen...
LLVM_ABI SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsCompressing=false)
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
const TargetLibraryInfo & getLibInfo() const
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool MaskedVectorIsZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Return true if 'Op' is known to be zero in DemandedElts.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
LLVM_ABI SDDbgValue * getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr, unsigned FI, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a FrameIndex SDDbgValue node.
LLVM_ABI SDValue getExtStridedLoadVP(ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
LLVM_ABI SDValue getJumpTable(int JTI, EVT VT, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void getTopologicallyOrderedNodes(SmallVectorImpl< const SDNode * > &SortedNodes) const
Get all the nodes in their topological order without modifying any states.
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI std::pair< SDValue, SDValue > getStrstr(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strstr operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to extend the Op as a pointer value assuming it was the smaller SrcTy ...
LLVM_ABI OverflowKind computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the unsigned addition of 2 nodes can overflow.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getErrorMergeValues(ArrayRef< EVT > ResultTypes, SDValue Chain, const SDLoc &dl)
Return poison values for each of ResultTypes, substituting Chain for any result of type MVT::Other,...
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI bool canIgnoreSignBitOfZeroResult(SDValue Op) const
Check if all uses of Op (limited to checking two for compile-time performance) are insensitive to sig...
LLVM_ABI void canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, SDValue &N2) const
Swap N1 and N2 if Opcode is a commutative binary opcode and the canonical form expects the opposite o...
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth=0) const
Test if the given fp value is known to be an integer power-of-2, either positive or negative.
LLVM_ABI OverflowKind computeOverflowForSignedSub(SDValue N0, SDValue N1) const
Determine if the result of the signed sub of 2 nodes can overflow.
LLVM_ABI void init(MachineFunction &NewMF, const TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallsInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, SDNodeFlags Flags)
Try to simplify a floating-point binary operation into 1 of its operands or a constant.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
LLVM_ABI SDValue getDeactivationSymbol(const GlobalValue *GV)
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
LLVM_ABI bool isUndef(unsigned Opcode, ArrayRef< SDValue > Ops)
Return true if the result of this operation is always undefined.
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
LLVM_ABI std::pair< EVT, EVT > GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, bool *HiIsEmpty) const
Compute the VTs needed for the low/hi parts of a type, dependent on an enveloping VT that has been sp...
LLVM_ABI SDValue foldConstantFPMath(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops)
Fold floating-point operations when all operands are constants and/or undefined.
LLVM_ABI std::optional< ConstantRange > getValidShiftAmountRange(SDValue V, const APInt &DemandedElts, unsigned Depth) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue FoldSymbolOffset(unsigned Opcode, EVT VT, const GlobalAddressSDNode *GA, const SDNode *N2)
LLVM_ABI SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDDbgValue * getDbgValue(DIVariable *Var, DIExpression *Expr, SDNode *N, unsigned R, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a SDDbgValue node.
LLVM_ABI SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base, SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, ISD::LoadExtType, bool IsExpanding=false)
DenormalMode getDenormalMode(EVT VT) const
Return the current function's default denormal handling kind for the given floating point type.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, ArrayRef< ISD::NodeType > CandidateBinOps, bool AllowPartials=false)
Match a binop + shuffle pyramid that represents a horizontal reduction over the elements of a vector ...
LLVM_ABI bool isADDLike(SDValue Op, bool NoWrap=false) const
Return true if the specified operand is an ISD::OR or ISD::XOR node that can be treated as an ISD::AD...
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue simplifyShift(SDValue X, SDValue Y)
Try to simplify a shift into 1 of its operands or a constant.
LLVM_ABI bool areNonVolatileConsecutiveStores(StoreSDNode *ST, StoreSDNode *Base, unsigned Bytes, int Dist) const
Return true if stores are next to each other and can be merged.
LLVM_ABI void transferDbgValues(SDValue From, SDValue To, unsigned OffsetInBits=0, unsigned SizeInBits=0, bool InvalidateDbg=true)
Transfer debug values from one node to another, while optionally generating fragment expressions for ...
LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a logical NOT operation as (XOR Val, BooleanOne).
LLVM_ABI SDValue getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, bool IsTruncating=false)
ilist< SDNode >::iterator allnodes_iterator
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
int getMaskElt(unsigned Idx) const
ArrayRef< int > getMask() const
static void commuteMask(MutableArrayRef< int > Mask)
Change values in a shuffle permute mask assuming the two vector operands have swapped position.
static LLVM_ABI bool isSplatMask(ArrayRef< int > Mask)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Information about stack frame layout on the target.
virtual TargetStackID::Value getStackIDForScalableVectors() const
Returns the StackID that scalable vectors should be associated with.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
Completely target-dependent object reference.
unsigned getTargetFlags() const
Provides information about what library functions are available for the current target.
IntegerType * getSizeTType(const Module &M) const
Returns an IntegerType corresponding to size_t.
virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const
Return true if it is beneficial to convert a load of a constant to just the constant itself.
const TargetMachine & getTargetMachine() const
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
unsigned getMaxStoresPerMemcpy(bool OptSize) const
Get maximum # of store operations permitted for llvm.memcpy.
unsigned getMaxStoresPerMemset(bool OptSize) const
Get maximum # of store operations permitted for llvm.memset.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
virtual bool shallExtractConstSplatVectorElementToStore(Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const
Return true if the target shall perform extract vector element and store given that the vector is kno...
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
BooleanContent
Enum that describes how the target represents true/false values.
virtual unsigned getMaxGluedStoresPerMemcpy() const
Get maximum # of store operations to be glued together.
std::vector< ArgListEntry > ArgListTy
unsigned getMaxStoresPerMemmove(bool OptSize) const
Get maximum # of store operations permitted for llvm.memmove.
virtual bool isLegalStoreImmediate(int64_t Value) const
Return true if the specified immediate is legal for the value input of a store instruction.
static ISD::NodeType getExtendForContent(BooleanContent Content)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
Primary interface to the complete machine description for the target machine.
const Triple & getTargetTriple() const
virtual bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const SelectionDAGTargetInfo * getSelectionDAGInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:724
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
This class is used to represent an VP_GATHER node.
This class is used to represent a VP_LOAD node.
This class is used to represent an VP_SCATTER node.
This class is used to represent a VP_STORE node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_LOAD node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_STORE node.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:266
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr bool isKnownEven() const
A return value of true indicates we know at compile time that the number of elements (vscale * Min) i...
Definition TypeSize.h:177
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:238
A raw_ostream that writes to an std::string.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt clmulr(const APInt &LHS, const APInt &RHS)
Perform a reversed carry-less multiply.
Definition APInt.cpp:3245
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3175
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3152
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3142
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3255
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3226
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3167
LLVM_ABI APInt avgSubFloorS(const APInt &C1, const APInt &C2)
Compute floor((C1 - C2) / 2) where C1 and C2 are treated as signed, so the subtraction is performed w...
Definition APInt.cpp:3157
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3235
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3265
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2294
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3217
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3250
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2299
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3137
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3147
LLVM_ABI APInt avgSubFloorU(const APInt &C1, const APInt &C2)
Compute floor((C1 - C2) / 2) where C1 and C2 are treated as unsigned, so the subtraction is performed...
Definition APInt.cpp:3162
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, bool isIntegerLike)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
LLVM_ABI CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical AND between different comparisons of identical values: ((X op1 Y) & (X...
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
bool matchUnaryPredicateImpl(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstNodeType *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant BUI...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:845
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ TargetConstantPool
Definition ISDOpcodes.h:191
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ ATOMIC_LOAD_FMINIMUMNUM
@ MASK_BEFOREFIRST
Has one mask vector operand.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ MLOAD
Masked load and store - consecutive vector load and store operations with additional mask operand tha...
@ VECREDUCE_FMINIMUMNUM
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:543
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ AVGSUBFLOORS
AVGSUBFLOORS/AVGSUBFLOORU - Averaging subtract - Subtract two integers using an integer of type i[N+1...
Definition ISDOpcodes.h:733
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:805
@ TargetBlockAddress
Definition ISDOpcodes.h:193
@ DEACTIVATION_SYMBOL
Untyped node storing deactivation symbol reference (DeactivationSymbolSDNode).
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:476
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:906
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:765
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:936
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ STRICT_PSEUDO_FMAX
Definition ISDOpcodes.h:465
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:796
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ SRCVALUE
SRCVALUE - This is a node type that holds a Value* that is used to make reference to a value in the L...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ATOMIC_LOAD_USUB_SAT
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:814
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:725
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ TargetExternalSymbol
Definition ISDOpcodes.h:192
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ TargetJumpTable
Definition ISDOpcodes.h:190
@ TargetIndex
TargetIndex - Like a constant pool entry, but with completely target-dependent semantics.
Definition ISDOpcodes.h:200
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ STRICT_PSEUDO_FMIN
Definition ISDOpcodes.h:464
@ TRUNCATE_SSAT_U
Definition ISDOpcodes.h:899
@ VECREDUCE_FMAXIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM nodes do not propagate NaNs and order signed zeroes using the llvm....
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:853
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ STEP_VECTOR
STEP_VECTOR(IMM) - Returns a scalable vector whose lanes are comprised of a linear sequence of unsign...
Definition ISDOpcodes.h:701
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:71
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:187
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:818
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:475
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ TargetConstantFP
Definition ISDOpcodes.h:182
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ VSCALE
VSCALE(IMM) - Returns the runtime scaling factor used to calculate the number of elements within a sc...
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ ATOMIC_LOAD_FMINIMUM
@ TargetFrameIndex
Definition ISDOpcodes.h:189
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:663
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:925
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:914
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ MASKED_UDIV
Masked vector arithmetic that returns poison on disabled lanes.
@ LIFETIME_START
This corresponds to the llvm.lifetime.
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:831
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ MGATHER
Masked gather and scatter - load and store operations for a vector of random addresses with additiona...
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
@ ATOMIC_LOAD_FMAXIMUMNUM
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ ATOMIC_LOAD_UDEC_WRAP
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:801
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:952
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ GET_FPENV_MEM
Gets the current floating-point environment.
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:753
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:720
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:667
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:691
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:813
@ ExternalSymbol
Definition ISDOpcodes.h:95
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:985
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:709
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:947
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ EXPERIMENTAL_VECTOR_HISTOGRAM
Experimental vector histogram intrinsic Operands: Input Chain, Inc, Mask, Base, Index,...
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:971
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ VECREDUCE_SEQ_FMUL
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:859
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_REPEAT
VECTOR_REPEAT(FIXED_LENGTH_VECTOR) Repeatedly copies the elements of the source fixed-length vector t...
Definition ISDOpcodes.h:645
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ TRUNCATE_SSAT_S
TRUNCATE_[SU]SAT_[SU] - Truncate for saturated operand [SU] located in middle, prefix for SAT means i...
Definition ISDOpcodes.h:897
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:740
@ TRUNCATE_USAT_U
Definition ISDOpcodes.h:901
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:341
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:188
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:769
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
LLVM_ABI NodeType getOppositeSignednessMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns the corresponding opcode with the opposi...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
bool isExtOpcode(unsigned Opcode)
LLVM_ABI bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
LLVM_ABI NodeType getUnmaskedBinOpOpcode(unsigned MaskedOpc)
Given a MaskedOpc of ISD::MASKED_(U|S)(DIV|REM), returns the unmasked ISD::(U|S)(DIV|REM).
LLVM_ABI bool isVectorShrinkable(const SDNode *N, unsigned NewEltSize, bool Signed)
Returns true if the specified node is a vector where all elements can be truncated to the specified e...
LLVM_ABI bool isVPBinaryOp(unsigned Opcode)
Whether this is a vector-predicated binary operation opcode.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI std::optional< unsigned > getBaseOpcodeForVP(unsigned Opcode, bool hasFPExcept)
Translate this VP Opcode to its corresponding non-VP Opcode.
bool isBitwiseLogicOp(unsigned Opcode)
Whether this is bitwise logic opcode.
bool isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
unsigned getUnorderedFlavor(CondCode Cond)
This function returns 0 if the condition is always false if an operand is a NaN, 1 if the condition i...
LLVM_ABI std::optional< unsigned > getVPExplicitVectorLengthIdx(unsigned Opcode)
The operand position of the explicit vector length parameter.
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, const APInt &DemandedElts, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
LLVM_ABI bool isFreezeUndef(const SDNode *N)
Return true if the specified node is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI std::optional< unsigned > getVPForBaseOpcode(unsigned Opcode)
Translate this non-VP Opcode to its corresponding VP Opcode.
MemIndexType
MemIndexType enum - This enum defines how to interpret MGATHER/SCATTER's index parameter when calcula...
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
LLVM_ABI NodeType getInverseMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns ISD::(U|S)MAX and ISD::(U|S)MIN,...
LLVM_ABI bool isVPReduction(unsigned Opcode)
Whether this is a vector-predicated reduction opcode.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
LLVM_ABI bool isBuildVectorOfConstantFPSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantFPSDNode or undef.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
bool matchUnaryPredicate(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
LLVM_ABI CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical OR between different comparisons of identical values: ((X op1 Y) | (X ...
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
LLVM_ABI Libcall getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMCPY_ELEMENT_UNORDERED_ATOMIC - Return MEMCPY_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMSET_ELEMENT_UNORDERED_ATOMIC - Return MEMSET_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMMOVE_ELEMENT_UNORDERED_ATOMIC - Return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_* value for the given e...
bool sd_match(SDValue N, Pattern &&P)
LLVM_ABI unsigned rot(unsigned SrcSignBits, unsigned BitWidth, std::optional< APInt > RotAmt, bool IsRotateRight)
Compute the number of sign bits after rotating a value.
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ABI ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:248
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI SDValue peekThroughExtractSubvectors(SDValue V)
Return the non-extracted vector source operand of V if it exists.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1577
LLVM_ABI SDValue getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs)
If V is a bitwise not, returns the inverted operand.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
LLVM_ABI bool isOneOrOneSplatFP(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant floating-point value, or a splatted vector of a constant float...
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1801
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1559
LLVM_ABI bool isMinSignedConstant(SDValue V)
Returns true if V is a constant min signed integer value.
LLVM_ABI ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1713
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1756
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI SDValue peekThroughInsertVectorElt(SDValue V, const APInt &DemandedElts)
Recursively peek through INSERT_VECTOR_ELT nodes, returning the source vector operand of V,...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void checkForCycles(const SelectionDAG *DAG, bool force=false)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1787
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI SDValue peekThroughTruncates(SDValue V)
Return the non-truncated source operand of V if it exists.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI SDValue peekThroughOneUseBitcasts(SDValue V)
Return the non-bitcasted and one-use source operand of V if it exists.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1737
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isNullConstantOrUndef(SDValue V)
Returns true if V is a constant integer zero or an UNDEF node.
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:656
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
LLVM_ABI bool funcReturnsFirstArgOfCall(const CallInst &CI)
Returns true if the parent of CI returns CI's first argument after calling CI.
Definition Analysis.cpp:835
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI bool isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant (+/-)0.0 floating-point value or a splatted vector thereof (wi...
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1774
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1814
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:794
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
intptr_t getRawBits() const
Definition ValueTypes.h:547
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
KnownBits byteSwap() const
Definition KnownBits.h:559
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
void resetAll()
Resets the known state of all bits.
Definition KnownBits.h:72
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
static LLVM_ABI KnownBits abdu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for abdu(LHS, RHS).
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
static LLVM_ABI KnownBits computeForSubBorrow(const KnownBits &LHS, KnownBits RHS, const KnownBits &Borrow)
Compute known bits results from subtracting RHS from LHS with 1-bit Borrow.
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits abds(KnownBits LHS, KnownBits RHS)
Compute known bits for abds(LHS, RHS).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static LLVM_ABI KnownBits avgFloorS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorS.
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry)
Compute known bits resulting from adding LHS, RHS and a 1-bit Carry.
Definition KnownBits.cpp:54
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
static LLVM_ABI KnownBits avgCeilU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilU.
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
static LLVM_ABI KnownBits avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI bool isDereferenceable(unsigned Size, LLVMContext &C, const DataLayout &DL) const
Return true if memory region [V, V+Offset+Size) is known to be dereferenceable.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
static LLVM_ABI bool isEqual(const KeyTy &Key, const SDNode &N)
The key SelectionDAG uniques SDNodes by.
void AddPointer(const void *P)
SmallVector< SDValue, 0 > OpStorage
Backs Ops when the key is built from a node; empty otherwise.
void AddInteger(T I)
const EVT * VTs
ArrayRef< SDValue > Ops
FoldingSetNodeID Tail
SDNodeKey(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
unsigned int NumVTs
Clients of various APIs that cause global effects on the DAG can optionally implement this interface.
virtual void NodeDeleted(SDNode *N, SDNode *E)
The node N that was deleted and, if E is not null, an equivalent node E that replaced it.
virtual void NodeInserted(SDNode *N)
The node N that was inserted.
virtual void NodeUpdated(SDNode *N)
The node N that was updated.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)