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: {
6247 Known.setKnownFPClasses(fcNone);
6248 Known.setSignBit(false);
6249 break;
6250 }
6251 case ISD::FNEG: {
6252 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6253 InterestedClasses, Depth + 1);
6254 Known.fneg();
6255 break;
6256 }
6257 case ISD::BUILD_VECTOR: {
6258 assert(!VT.isScalableVector());
6259 bool First = true;
6260 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6261 if (!DemandedElts[I])
6262 continue;
6263
6264 if (First) {
6265 Known =
6266 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6267 First = false;
6268 } else {
6269 Known |=
6270 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6271 }
6272
6273 if (Known.isUnknown())
6274 break;
6275 }
6276 break;
6277 }
6279 SDValue Src = Op.getOperand(0);
6280 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6281 EVT SrcVT = Src.getValueType();
6282 if (SrcVT.isFixedLengthVector() && CIdx) {
6283 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6284 APInt DemandedSrcElts = APInt::getOneBitSet(
6285 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6286 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6287 Depth + 1);
6288 } else {
6289 // Out of bounds index is poison.
6290 Known.setKnownFPClasses(fcNone);
6291 }
6292 } else {
6293 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6294 }
6295 break;
6296 }
6297 case ISD::SPLAT_VECTOR: {
6298 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6299 break;
6300 }
6301 case ISD::BITCAST: {
6302 // FIXME: It should not be necessary to check for an elementwise bitcast.
6303 // If a bitcast is not elementwise between vector / scalar types,
6304 // computeKnownBits already splices the known bits of the source elements
6305 // appropriately so as to line up with the bits of the result's demanded
6306 // elements.
6307 EVT SrcVT = Op.getOperand(0).getValueType();
6308 if (VT.isScalableVector() || SrcVT.isScalableVector())
6309 break;
6310 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6311 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6312 if (VTNumElts != SrcVTNumElts)
6313 break;
6314
6315 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6317 break;
6318 }
6319 case ISD::FABS: {
6320 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6321 InterestedClasses, Depth + 1);
6322 Known.fabs();
6323 break;
6324 }
6325 case ISD::FCOPYSIGN: {
6326 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6327 InterestedClasses, Depth + 1);
6328 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6329 InterestedClasses, Depth + 1);
6330 Known.copysign(KnownSign);
6331 break;
6332 }
6333 case ISD::AssertNoFPClass: {
6334 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6335 InterestedClasses, Depth + 1);
6336 FPClassTest AssertedClasses =
6337 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6338 Known.setKnownFPClasses(Known.getKnownFPClasses() & ~AssertedClasses);
6339 break;
6340 }
6342 SDValue Src = Op.getOperand(0);
6343 EVT SrcVT = Src.getValueType();
6344 if (SrcVT.isFixedLengthVector()) {
6345 unsigned Idx = Op.getConstantOperandVal(1);
6346 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6347
6348 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6349 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6350 Depth + 1);
6351 } else {
6352 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6353 }
6354 break;
6355 }
6356 case ISD::INSERT_SUBVECTOR: {
6357 SDValue BaseVector = Op.getOperand(0);
6358 SDValue SubVector = Op.getOperand(1);
6359 EVT BaseVT = BaseVector.getValueType();
6360 if (BaseVT.isFixedLengthVector()) {
6361 unsigned Idx = Op.getConstantOperandVal(2);
6362 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6363 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6364
6365 APInt DemandedMask =
6366 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6367 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6368 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6369
6370 if (!DemandedSrcElts.isZero())
6371 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6372 InterestedClasses, Depth + 1);
6373 if (!DemandedSubElts.isZero()) {
6375 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6376 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6377 }
6378 } else {
6379 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6380 if (!Known.isUnknown())
6381 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6382 }
6383 break;
6384 }
6385 case ISD::SELECT:
6386 case ISD::VSELECT: {
6387 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6388 // IR-level ValueTracking.
6389 KnownFPClass KnownFalseClass = computeKnownFPClass(
6390 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6391 if (KnownFalseClass.isUnknown())
6392 break;
6393 KnownFPClass KnownTrueClass = computeKnownFPClass(
6394 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6395 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6396 break;
6397 }
6398 default:
6399 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6400 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6401 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6402 Depth);
6403 }
6404 break;
6405 }
6406
6407 return Known;
6408}
6409
6411 unsigned Depth) const {
6412 APInt DemandedElts = getDemandAllEltsMask(Op);
6413 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6414}
6415
6417 bool SNaN, unsigned Depth) const {
6418 assert(!DemandedElts.isZero() && "No demanded elements");
6419
6420 // If we're told that NaNs won't happen, assume they won't.
6421 if (Op->getFlags().hasNoNaNs())
6422 return true;
6423
6424 if (Depth >= MaxRecursionDepth)
6425 return false; // Limit search depth.
6426
6427 unsigned Opcode = Op.getOpcode();
6428 switch (Opcode) {
6429 case ISD::FADD:
6430 case ISD::FSUB:
6431 case ISD::FMUL:
6432 case ISD::FDIV:
6433 case ISD::FREM:
6434 case ISD::FSIN:
6435 case ISD::FCOS:
6436 case ISD::FTAN:
6437 case ISD::FASIN:
6438 case ISD::FACOS:
6439 case ISD::FATAN:
6440 case ISD::FATAN2:
6441 case ISD::FSINH:
6442 case ISD::FCOSH:
6443 case ISD::FTANH:
6444 case ISD::FMA:
6445 case ISD::FMULADD:
6446 case ISD::FMAD: {
6447 if (SNaN)
6448 return true;
6449 // TODO: Need isKnownNeverInfinity
6450 return false;
6451 }
6452 case ISD::FCANONICALIZE:
6453 case ISD::FEXP:
6454 case ISD::FEXP2:
6455 case ISD::FEXP10:
6456 case ISD::FTRUNC:
6457 case ISD::FFLOOR:
6458 case ISD::FCEIL:
6459 case ISD::FROUND:
6460 case ISD::FROUNDEVEN:
6461 case ISD::LROUND:
6462 case ISD::LLROUND:
6463 case ISD::FRINT:
6464 case ISD::LRINT:
6465 case ISD::LLRINT:
6466 case ISD::FNEARBYINT:
6467 case ISD::FLDEXP: {
6468 if (SNaN)
6469 return true;
6470 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6471 }
6472 case ISD::FABS:
6473 case ISD::FNEG:
6474 case ISD::FCOPYSIGN: {
6475 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6476 }
6477 case ISD::SELECT:
6478 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6479 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6480 case ISD::FP_EXTEND:
6481 case ISD::FP_ROUND: {
6482 if (SNaN)
6483 return true;
6484 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6485 }
6486 case ISD::SINT_TO_FP:
6487 case ISD::UINT_TO_FP:
6488 return true;
6489 case ISD::FSQRT: // Need is known positive
6490 case ISD::FLOG:
6491 case ISD::FLOG2:
6492 case ISD::FLOG10:
6493 case ISD::FPOWI:
6494 case ISD::FPOW: {
6495 if (SNaN)
6496 return true;
6497 // TODO: Refine on operand
6498 return false;
6499 }
6500 case ISD::FMINNUM:
6501 case ISD::FMAXNUM:
6502 case ISD::FMINIMUMNUM:
6503 case ISD::FMAXIMUMNUM: {
6504 // Only one needs to be known not-nan, since it will be returned if the
6505 // other ends up being one.
6506 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6507 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6508 }
6509 case ISD::FMINNUM_IEEE:
6510 case ISD::FMAXNUM_IEEE: {
6511 if (SNaN)
6512 return true;
6513 // This can return a NaN if either operand is an sNaN, or if both operands
6514 // are NaN.
6515 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6516 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6517 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6518 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6519 }
6520 case ISD::FMINIMUM:
6521 case ISD::FMAXIMUM: {
6522 // TODO: Does this quiet or return the origina NaN as-is?
6523 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6524 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6525 }
6527 SDValue Src = Op.getOperand(0);
6528 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6529 EVT SrcVT = Src.getValueType();
6530 if (SrcVT.isFixedLengthVector() && Idx &&
6531 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6532 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6533 Idx->getZExtValue());
6534 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6535 }
6536 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6537 }
6539 SDValue Src = Op.getOperand(0);
6540 if (Src.getValueType().isFixedLengthVector()) {
6541 unsigned Idx = Op.getConstantOperandVal(1);
6542 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6543 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6544 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6545 }
6546 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6547 }
6548 case ISD::INSERT_SUBVECTOR: {
6549 SDValue BaseVector = Op.getOperand(0);
6550 SDValue SubVector = Op.getOperand(1);
6551 EVT BaseVectorVT = BaseVector.getValueType();
6552 if (BaseVectorVT.isFixedLengthVector()) {
6553 unsigned Idx = Op.getConstantOperandVal(2);
6554 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6555 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6556
6557 // Clear/Extract the bits at the position where the subvector will be
6558 // inserted.
6559 APInt DemandedMask =
6560 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6561 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6562 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6563
6564 bool NeverNaN = true;
6565 if (!DemandedSrcElts.isZero())
6566 NeverNaN &=
6567 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6568 if (NeverNaN && !DemandedSubElts.isZero())
6569 NeverNaN &=
6570 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6571 return NeverNaN;
6572 }
6573 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6574 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6575 }
6576 case ISD::BUILD_VECTOR: {
6577 unsigned NumElts = Op.getNumOperands();
6578 for (unsigned I = 0; I != NumElts; ++I)
6579 if (DemandedElts[I] &&
6580 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6581 return false;
6582 return true;
6583 }
6584 case ISD::SPLAT_VECTOR:
6585 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6586 case ISD::AssertNoFPClass: {
6587 FPClassTest NoFPClass =
6588 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6589 if ((NoFPClass & fcNan) == fcNan)
6590 return true;
6591 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6592 return true;
6593 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6594 }
6595 default:
6596 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6597 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6598 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6599 Depth);
6600 }
6601 break;
6602 }
6603
6604 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6605 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6606 return Known.isKnownNever(NanMask);
6607}
6608
6610 APInt DemandedElts = getDemandAllEltsMask(Op);
6611 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6612}
6613
6615 const APInt &DemandedElts,
6616 unsigned Depth) const {
6617 assert(!DemandedElts.isZero() && "No demanded elements");
6618 EVT VT = Op.getValueType();
6620 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6621 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6622}
6623
6625 APInt DemandedElts = getDemandAllEltsMask(Op);
6626 return isKnownNeverZero(Op, DemandedElts, Depth);
6627}
6628
6630 unsigned Depth) const {
6631 if (Depth >= MaxRecursionDepth)
6632 return false; // Limit search depth.
6633
6634 EVT OpVT = Op.getValueType();
6635 unsigned BitWidth = OpVT.getScalarSizeInBits();
6636
6637 assert(!Op.getValueType().isFloatingPoint() &&
6638 "Floating point types unsupported - use isKnownNeverLogicalZero");
6639
6640 // If the value is a constant, we can obviously see if it is a zero or not.
6641 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6642 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6643 return !V.isZero();
6644 };
6645
6646 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6647 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6648 return true;
6649
6650 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6651 // some degree.
6652 switch (Op.getOpcode()) {
6653 default:
6654 break;
6655
6657 SDValue InVec = Op.getOperand(0);
6658 SDValue EltNo = Op.getOperand(1);
6659 EVT VecVT = InVec.getValueType();
6660
6661 // Skip scalable vectors or implicit extensions.
6662 if (VecVT.isScalableVector() ||
6663 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6664 break;
6665
6666 // If we know the element index, just demand that vector element, else for
6667 // an unknown element index, ignore DemandedElts and demand them all.
6668 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6669 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6670 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6671 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6672 DemandedSrcElts =
6673 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6674
6675 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6676 }
6677
6678 case ISD::OR:
6679 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6680 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6681
6682 case ISD::VSELECT:
6683 case ISD::SELECT:
6684 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6685 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6686
6687 case ISD::SHL: {
6688 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6689 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6690 KnownBits ValKnown =
6691 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6692 // 1 << X is never zero.
6693 if (ValKnown.One[0])
6694 return true;
6695 // If max shift cnt of known ones is non-zero, result is non-zero.
6696 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6697 .getMaxValue();
6698 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6699 !ValKnown.One.shl(MaxCnt).isZero())
6700 return true;
6701 break;
6702 }
6703
6704 case ISD::VECTOR_SHUFFLE: {
6705 if (Op.getValueType().isScalableVector())
6706 return false;
6707
6708 unsigned NumElts = DemandedElts.getBitWidth();
6709
6710 // All demanded elements from LHS and RHS must be known non-zero.
6711 // Demanded elements with undef shuffle mask elements are unknown.
6712
6713 APInt DemandedLHS, DemandedRHS;
6714 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6715 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6716 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6717 DemandedLHS, DemandedRHS))
6718 return false;
6719
6720 return (!DemandedLHS ||
6721 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6722 (!DemandedRHS ||
6723 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6724 }
6725
6726 case ISD::UADDSAT:
6727 case ISD::UMAX:
6728 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6729 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6730
6731 case ISD::UMIN:
6732 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6733 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6734
6735 // For smin/smax: If either operand is known negative/positive
6736 // respectively we don't need the other to be known at all.
6737 case ISD::SMAX: {
6738 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6739 if (Op1.isStrictlyPositive())
6740 return true;
6741
6742 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6743 if (Op0.isStrictlyPositive())
6744 return true;
6745
6746 if (Op1.isNonZero() && Op0.isNonZero())
6747 return true;
6748
6749 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6750 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6751 }
6752 case ISD::SMIN: {
6753 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6754 if (Op1.isNegative())
6755 return true;
6756
6757 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6758 if (Op0.isNegative())
6759 return true;
6760
6761 if (Op1.isNonZero() && Op0.isNonZero())
6762 return true;
6763
6764 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6765 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6766 }
6767
6768 case ISD::ROTL:
6769 case ISD::ROTR:
6770 case ISD::BITREVERSE:
6771 case ISD::BSWAP:
6772 case ISD::CTPOP:
6773 case ISD::ABS:
6775 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6776
6777 case ISD::SRA:
6778 case ISD::SRL: {
6779 if (Op->getFlags().hasExact())
6780 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6781 KnownBits ValKnown =
6782 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6783 if (ValKnown.isNegative())
6784 return true;
6785 // If max shift cnt of known ones is non-zero, result is non-zero.
6786 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6787 .getMaxValue();
6788 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6789 !ValKnown.One.lshr(MaxCnt).isZero())
6790 return true;
6791 break;
6792 }
6793 case ISD::UDIV:
6794 case ISD::SDIV:
6795 // div exact can only produce a zero if the dividend is zero.
6796 // TODO: For udiv this is also true if Op1 u<= Op0
6797 if (Op->getFlags().hasExact())
6798 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6799 break;
6800
6801 case ISD::ADD:
6802 if (Op->getFlags().hasNoUnsignedWrap())
6803 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6804 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6805 return true;
6806 // TODO: There are a lot more cases we can prove for add.
6807 break;
6808
6809 case ISD::SUB: {
6810 if (isNullConstant(Op.getOperand(0)))
6811 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6812
6813 std::optional<bool> ne = KnownBits::ne(
6814 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6815 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6816 return ne && *ne;
6817 }
6818
6819 case ISD::MUL:
6820 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6821 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6822 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6823 return true;
6824 break;
6825
6826 case ISD::ZERO_EXTEND:
6827 case ISD::SIGN_EXTEND:
6828 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6829 case ISD::VSCALE: {
6831 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6832 ConstantRange CR =
6833 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6834 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6835 return true;
6836 break;
6837 }
6838 }
6839
6840 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6841}
6842
6844 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6845 return !C1->isNegative();
6846
6847 switch (Op.getOpcode()) {
6848 case ISD::FABS:
6849 case ISD::FEXP:
6850 case ISD::FEXP2:
6851 case ISD::FEXP10:
6852 return true;
6853 default:
6854 return false;
6855 }
6856
6857 llvm_unreachable("covered opcode switch");
6858}
6859
6861 assert(Use.getValueType().isFloatingPoint());
6862 const SDNode *User = Use.getUser();
6863 if (User->getFlags().hasNoSignedZeros())
6864 return true;
6865
6866 unsigned OperandNo = Use.getOperandNo();
6867 // Check if this use is insensitive to the sign of zero
6868 switch (User->getOpcode()) {
6869 case ISD::SETCC:
6870 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6871 case ISD::FABS:
6872 // fabs always produces +0.0.
6873 return true;
6874 case ISD::FCOPYSIGN:
6875 // copysign overwrites the sign bit of the first operand.
6876 return OperandNo == 0;
6877 case ISD::FADD:
6878 case ISD::FSUB: {
6879 // Arithmetic with non-zero constants fixes the uncertainty around the
6880 // sign bit.
6881 SDValue Other = User->getOperand(1 - OperandNo);
6883 }
6884 case ISD::FP_TO_SINT:
6885 case ISD::FP_TO_UINT:
6886 // fp-to-int conversions normalize signed zeros.
6887 return true;
6888 default:
6889 return false;
6890 }
6891}
6892
6894 if (Op->getFlags().hasNoSignedZeros())
6895 return true;
6896 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6897 // regression. Ideally, this should be implemented as a demanded-bits
6898 // optimization that stems from the users.
6899 if (Op->use_size() > 2)
6900 return false;
6901 return all_of(Op->uses(),
6902 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6903}
6904
6906 // Check the obvious case.
6907 if (A == B) return true;
6908
6909 // For negative and positive zero.
6912 if (CA->isZero() && CB->isZero()) return true;
6913
6914 // Otherwise they may not be equal.
6915 return false;
6916}
6917
6918// Only bits set in Mask must be negated, other bits may be arbitrary.
6920 if (isBitwiseNot(V, AllowUndefs))
6921 return V.getOperand(0);
6922
6923 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6924 // bits in the non-extended part.
6925 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6926 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6927 return SDValue();
6928 SDValue ExtArg = V.getOperand(0);
6929 if (ExtArg.getScalarValueSizeInBits() >=
6930 MaskC->getAPIntValue().getActiveBits() &&
6931 isBitwiseNot(ExtArg, AllowUndefs) &&
6932 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6933 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6934 return ExtArg.getOperand(0).getOperand(0);
6935 return SDValue();
6936}
6937
6939 // Match masked merge pattern (X & ~M) op (Y & M)
6940 // Including degenerate case (X & ~M) op M
6941 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6942 SDValue Other) {
6943 if (SDValue NotOperand =
6944 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6945 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6946 NotOperand->getOpcode() == ISD::TRUNCATE)
6947 NotOperand = NotOperand->getOperand(0);
6948
6949 if (Other == NotOperand)
6950 return true;
6951 if (Other->getOpcode() == ISD::AND)
6952 return NotOperand == Other->getOperand(0) ||
6953 NotOperand == Other->getOperand(1);
6954 }
6955 return false;
6956 };
6957
6958 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6959 A = A->getOperand(0);
6960
6961 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6962 B = B->getOperand(0);
6963
6964 if (A->getOpcode() == ISD::AND)
6965 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6966 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6967 return false;
6968}
6969
6970// FIXME: unify with llvm::haveNoCommonBitsSet.
6972 assert(A.getValueType() == B.getValueType() &&
6973 "Values must have the same type");
6976 return true;
6979}
6980
6981static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6982 SelectionDAG &DAG) {
6983 if (cast<ConstantSDNode>(Step)->isZero())
6984 return DAG.getConstant(0, DL, VT);
6985
6986 return SDValue();
6987}
6988
6991 SelectionDAG &DAG) {
6992 int NumOps = Ops.size();
6993 assert(NumOps != 0 && "Can't build an empty vector!");
6994 assert(!VT.isScalableVector() &&
6995 "BUILD_VECTOR cannot be used with scalable types");
6996 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6997 "Incorrect element count in BUILD_VECTOR!");
6998
6999 // BUILD_VECTOR of UNDEFs is UNDEF.
7000 bool AllPoison = true;
7001 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7002 AllPoison &= Op.getOpcode() == ISD::POISON;
7003 return Op.isUndef();
7004 }))
7005 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7006
7007 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
7008 SDValue IdentitySrc;
7009 bool IsIdentity = true;
7010 for (int i = 0; i != NumOps; ++i) {
7011 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7012 Ops[i].getOperand(0).getValueType() != VT ||
7013 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
7014 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
7015 Ops[i].getConstantOperandAPInt(1) != i) {
7016 IsIdentity = false;
7017 break;
7018 }
7019 IdentitySrc = Ops[i].getOperand(0);
7020 }
7021 if (IsIdentity)
7022 return IdentitySrc;
7023
7024 return SDValue();
7025}
7026
7027/// Try to simplify vector concatenation to an input value, undef, or build
7028/// vector.
7031 SelectionDAG &DAG) {
7032 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
7034 [Ops](SDValue Op) {
7035 return Ops[0].getValueType() == Op.getValueType();
7036 }) &&
7037 "Concatenation of vectors with inconsistent value types!");
7038 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
7039 VT.getVectorElementCount() &&
7040 "Incorrect element count in vector concatenation!");
7041
7042 if (Ops.size() == 1)
7043 return Ops[0];
7044
7045 // Concat of UNDEFs is UNDEF.
7046 bool AllPoison = true;
7047 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7048 AllPoison &= Op.getOpcode() == ISD::POISON;
7049 return Op.isUndef();
7050 }))
7051 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7052
7053 // Scan the operands and look for extract operations from a single source
7054 // that correspond to insertion at the same location via this concatenation:
7055 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7056 SDValue IdentitySrc;
7057 bool IsIdentity = true;
7058 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7059 SDValue Op = Ops[i];
7060 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7061 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7062 Op.getOperand(0).getValueType() != VT ||
7063 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7064 Op.getConstantOperandVal(1) != IdentityIndex) {
7065 IsIdentity = false;
7066 break;
7067 }
7068 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7069 "Unexpected identity source vector for concat of extracts");
7070 IdentitySrc = Op.getOperand(0);
7071 }
7072 if (IsIdentity) {
7073 assert(IdentitySrc && "Failed to set source vector of extracts");
7074 return IdentitySrc;
7075 }
7076
7077 // The code below this point is only designed to work for fixed width
7078 // vectors, so we bail out for now.
7079 if (VT.isScalableVector())
7080 return SDValue();
7081
7082 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7083 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7084 // BUILD_VECTOR.
7085 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7086 EVT SVT = VT.getScalarType();
7088 for (SDValue Op : Ops) {
7089 EVT OpVT = Op.getValueType();
7090 if (Op.getOpcode() == ISD::POISON)
7091 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7092 else if (Op.getOpcode() == ISD::UNDEF)
7093 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7094 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7095 Elts.append(Op->op_begin(), Op->op_end());
7096 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7097 OpVT.getVectorNumElements() == 1 &&
7098 isNullConstant(Op.getOperand(2)))
7099 Elts.push_back(Op.getOperand(1));
7100 else
7101 return SDValue();
7102 }
7103
7104 // BUILD_VECTOR requires all inputs to be of the same type, find the
7105 // maximum type and extend them all.
7106 for (SDValue Op : Elts)
7107 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7108
7109 if (SVT.bitsGT(VT.getScalarType())) {
7110 for (SDValue &Op : Elts) {
7111 if (Op.getOpcode() == ISD::POISON)
7112 Op = DAG.getPOISON(SVT);
7113 else if (Op.getOpcode() == ISD::UNDEF)
7114 Op = DAG.getUNDEF(SVT);
7115 else
7116 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7117 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7118 : DAG.getSExtOrTrunc(Op, DL, SVT);
7119 }
7120 }
7121
7122 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7123 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7124 return V;
7125}
7126
7127/// Gets or creates the specified node.
7128SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7129 SDVTList VTs = getVTList(VT);
7130 SDNodeKey ID(Opcode, VTs, {});
7131 FoldingSetInsertToken InsertToken;
7132 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7133 return SDValue(E, 0);
7134
7135 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7136 CSEMap.insert(N, InsertToken);
7137
7138 InsertNode(N);
7139 SDValue V = SDValue(N, 0);
7140 NewSDValueDbgMsg(V, "Creating new node: ", this);
7141 return V;
7142}
7143
7144SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7145 SDValue N1) {
7146 SDNodeFlags Flags;
7147 if (Inserter)
7148 Flags = Inserter->getFlags();
7149 return getNode(Opcode, DL, VT, N1, Flags);
7150}
7151
7152SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7153 SDValue N1, const SDNodeFlags Flags) {
7154 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7155
7156 // Constant fold unary operations with a vector integer or float operand.
7157 switch (Opcode) {
7158 default:
7159 // FIXME: Entirely reasonable to perform folding of other unary
7160 // operations here as the need arises.
7161 break;
7162 case ISD::FNEG:
7163 case ISD::FABS:
7164 case ISD::FCEIL:
7165 case ISD::FTRUNC:
7166 case ISD::FFLOOR:
7167 case ISD::FP_EXTEND:
7168 case ISD::FP_TO_SINT:
7169 case ISD::FP_TO_UINT:
7170 case ISD::FP_TO_FP16:
7171 case ISD::FP_TO_BF16:
7172 case ISD::TRUNCATE:
7173 case ISD::ANY_EXTEND:
7174 case ISD::ZERO_EXTEND:
7175 case ISD::SIGN_EXTEND:
7176 case ISD::UINT_TO_FP:
7177 case ISD::SINT_TO_FP:
7178 case ISD::FP16_TO_FP:
7179 case ISD::BF16_TO_FP:
7180 case ISD::BITCAST:
7181 case ISD::ABS:
7183 case ISD::BITREVERSE:
7184 case ISD::BSWAP:
7185 case ISD::CTLZ:
7187 case ISD::CTTZ:
7189 case ISD::CTPOP:
7190 case ISD::PARITY:
7191 case ISD::CTLS:
7192 case ISD::VECREDUCE_ADD:
7197 case ISD::VECREDUCE_MUL:
7198 case ISD::VECREDUCE_AND:
7199 case ISD::VECREDUCE_OR:
7200 case ISD::VECREDUCE_XOR:
7201 case ISD::STEP_VECTOR: {
7202 SDValue Ops = {N1};
7203 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7204 return Fold;
7205 }
7206 }
7207
7208 unsigned OpOpcode = N1.getNode()->getOpcode();
7209 switch (Opcode) {
7210 case ISD::STEP_VECTOR:
7211 assert(VT.isScalableVector() &&
7212 "STEP_VECTOR can only be used with scalable types");
7213 assert(OpOpcode == ISD::TargetConstant &&
7214 VT.getVectorElementType() == N1.getValueType() &&
7215 "Unexpected step operand");
7216 break;
7217 case ISD::FREEZE:
7218 assert(VT == N1.getValueType() && "Unexpected VT!");
7220 return N1;
7221 break;
7222 case ISD::TokenFactor:
7223 case ISD::MERGE_VALUES:
7225 return N1; // Factor, merge or concat of one node? No need.
7226 case ISD::BUILD_VECTOR: {
7227 // Attempt to simplify BUILD_VECTOR.
7228 SDValue Ops[] = {N1};
7229 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7230 return V;
7231 break;
7232 }
7233 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7234 case ISD::FP_EXTEND:
7236 "Invalid FP cast!");
7237 if (N1.getValueType() == VT) return N1; // noop conversion.
7238 assert((!VT.isVector() || VT.getVectorElementCount() ==
7240 "Vector element count mismatch!");
7241 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7242 if (N1.isUndef())
7243 return getUNDEF(VT);
7244 break;
7245 case ISD::FP_TO_SINT:
7246 case ISD::FP_TO_UINT:
7247 if (N1.isUndef())
7248 return getUNDEF(VT);
7249 break;
7250 case ISD::SINT_TO_FP:
7251 case ISD::UINT_TO_FP:
7252 // [us]itofp(undef) = 0, because the result value is bounded.
7253 if (N1.isUndef())
7254 return getConstantFP(0.0, DL, VT);
7255 break;
7256 case ISD::SIGN_EXTEND:
7257 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7258 "Invalid SIGN_EXTEND!");
7259 assert(VT.isVector() == N1.getValueType().isVector() &&
7260 "SIGN_EXTEND result type type should be vector iff the operand "
7261 "type is vector!");
7262 if (N1.getValueType() == VT) return N1; // noop extension
7263 assert((!VT.isVector() || VT.getVectorElementCount() ==
7265 "Vector element count mismatch!");
7266 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7267 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7268 SDNodeFlags Flags;
7269 if (OpOpcode == ISD::ZERO_EXTEND)
7270 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7271 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7272 transferDbgValues(N1, NewVal);
7273 return NewVal;
7274 }
7275
7276 if (OpOpcode == ISD::POISON)
7277 return getPOISON(VT);
7278
7279 if (N1.isUndef())
7280 // sext(undef) = 0, because the top bits will all be the same.
7281 return getConstant(0, DL, VT);
7282
7283 // Skip unnecessary sext_inreg pattern:
7284 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7285 if (OpOpcode == ISD::TRUNCATE) {
7286 SDValue OpOp = N1.getOperand(0);
7287 if (OpOp.getValueType() == VT) {
7288 unsigned NumSignExtBits =
7290 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7291 transferDbgValues(N1, OpOp);
7292 return OpOp;
7293 }
7294 }
7295 }
7296 break;
7297 case ISD::ZERO_EXTEND:
7298 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7299 "Invalid ZERO_EXTEND!");
7300 assert(VT.isVector() == N1.getValueType().isVector() &&
7301 "ZERO_EXTEND result type type should be vector iff the operand "
7302 "type is vector!");
7303 if (N1.getValueType() == VT) return N1; // noop extension
7304 assert((!VT.isVector() || VT.getVectorElementCount() ==
7306 "Vector element count mismatch!");
7307 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7308 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7309 SDNodeFlags Flags;
7310 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7311 SDValue NewVal =
7312 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7313 transferDbgValues(N1, NewVal);
7314 return NewVal;
7315 }
7316
7317 if (OpOpcode == ISD::POISON)
7318 return getPOISON(VT);
7319
7320 if (N1.isUndef())
7321 // zext(undef) = 0, because the top bits will be zero.
7322 return getConstant(0, DL, VT);
7323
7324 // Skip unnecessary zext_inreg pattern:
7325 // (zext (trunc x)) -> x iff the upper bits are known zero.
7326 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7327 // use to recognise zext_inreg patterns.
7328 if (OpOpcode == ISD::TRUNCATE) {
7329 SDValue OpOp = N1.getOperand(0);
7330 if (OpOp.getValueType() == VT) {
7331 if (OpOp.getOpcode() != ISD::AND) {
7334 if (MaskedValueIsZero(OpOp, HiBits)) {
7335 transferDbgValues(N1, OpOp);
7336 return OpOp;
7337 }
7338 }
7339 }
7340 }
7341 break;
7342 case ISD::ANY_EXTEND:
7343 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7344 "Invalid ANY_EXTEND!");
7345 assert(VT.isVector() == N1.getValueType().isVector() &&
7346 "ANY_EXTEND result type type should be vector iff the operand "
7347 "type is vector!");
7348 if (N1.getValueType() == VT) return N1; // noop extension
7349 assert((!VT.isVector() || VT.getVectorElementCount() ==
7351 "Vector element count mismatch!");
7352 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7353
7354 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7355 OpOpcode == ISD::ANY_EXTEND) {
7356 SDNodeFlags Flags;
7357 if (OpOpcode == ISD::ZERO_EXTEND)
7358 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7359 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7360 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7361 }
7362 if (N1.isUndef())
7363 return getUNDEF(VT);
7364
7365 // (ext (trunc x)) -> x
7366 if (OpOpcode == ISD::TRUNCATE) {
7367 SDValue OpOp = N1.getOperand(0);
7368 if (OpOp.getValueType() == VT) {
7369 transferDbgValues(N1, OpOp);
7370 return OpOp;
7371 }
7372 }
7373 break;
7374 case ISD::TRUNCATE:
7375 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7376 "Invalid TRUNCATE!");
7377 assert(VT.isVector() == N1.getValueType().isVector() &&
7378 "TRUNCATE result type type should be vector iff the operand "
7379 "type is vector!");
7380 if (N1.getValueType() == VT) return N1; // noop truncate
7381 assert((!VT.isVector() || VT.getVectorElementCount() ==
7383 "Vector element count mismatch!");
7384 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7385 if (OpOpcode == ISD::TRUNCATE)
7386 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7387 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7388 OpOpcode == ISD::ANY_EXTEND) {
7389 // If the source is smaller than the dest, we still need an extend.
7391 VT.getScalarType())) {
7392 SDNodeFlags Flags;
7393 if (OpOpcode == ISD::ZERO_EXTEND)
7394 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7395 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7396 }
7397 if (N1.getOperand(0).getValueType().bitsGT(VT))
7398 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7399 return N1.getOperand(0);
7400 }
7401 if (N1.isUndef())
7402 return getUNDEF(VT);
7403 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7404 return getVScale(DL, VT,
7406 break;
7410 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7411 assert(N1.getValueType().bitsLE(VT) &&
7412 "The input must be the same size or smaller than the result.");
7415 "The destination vector type must have fewer lanes than the input.");
7416 break;
7417 case ISD::ABS:
7418 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7419 if (N1.isUndef())
7420 return getConstant(0, DL, VT);
7421 break;
7423 assert(VT.isInteger() && VT == N1.getValueType() &&
7424 "Invalid ABS_MIN_POISON!");
7425 if (N1.isUndef())
7426 return getConstant(0, DL, VT);
7427 break;
7428 case ISD::BSWAP:
7429 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7430 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7431 "BSWAP types must be a multiple of 16 bits!");
7432 if (N1.isUndef())
7433 return getUNDEF(VT);
7434 // bswap(bswap(X)) -> X.
7435 if (OpOpcode == ISD::BSWAP)
7436 return N1.getOperand(0);
7437 break;
7438 case ISD::BITREVERSE:
7439 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7440 if (N1.isUndef())
7441 return getUNDEF(VT);
7442 break;
7443 case ISD::BITCAST:
7445 "Cannot BITCAST between types of different sizes!");
7446 if (VT == N1.getValueType()) return N1; // noop conversion.
7447 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7448 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7449 if (N1.isUndef())
7450 return getUNDEF(VT);
7451 break;
7453 assert(VT.isVector() && !N1.getValueType().isVector() &&
7454 (VT.getVectorElementType() == N1.getValueType() ||
7456 N1.getValueType().isInteger() &&
7458 "Illegal SCALAR_TO_VECTOR node!");
7459 if (N1.isUndef())
7460 return getUNDEF(VT);
7461 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7462 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7464 N1.getConstantOperandVal(1) == 0 &&
7465 N1.getOperand(0).getValueType() == VT)
7466 return N1.getOperand(0);
7467 break;
7468 case ISD::FNEG:
7469 // Negation of an unknown bag of bits is still completely undefined.
7470 if (N1.isUndef())
7471 return getUNDEF(VT);
7472
7473 if (OpOpcode == ISD::FNEG) // --X -> X
7474 return N1.getOperand(0);
7475 break;
7476 case ISD::FABS:
7477 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7478 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7479 break;
7480 case ISD::VSCALE:
7481 assert(VT == N1.getValueType() && "Unexpected VT!");
7482 break;
7483 case ISD::CTPOP:
7484 if (N1.getValueType().getScalarType() == MVT::i1)
7485 return N1;
7486 break;
7487 case ISD::CTLZ:
7488 case ISD::CTTZ:
7489 if (N1.getValueType().getScalarType() == MVT::i1)
7490 return getNOT(DL, N1, N1.getValueType());
7491 break;
7492 case ISD::CTLS:
7493 if (N1.getValueType().getScalarType() == MVT::i1)
7494 return getConstant(0, DL, VT);
7495 break;
7496 case ISD::VECREDUCE_ADD:
7497 if (N1.getValueType().getScalarType() == MVT::i1)
7498 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7499 break;
7502 if (N1.getValueType().getScalarType() == MVT::i1)
7503 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7504 break;
7507 if (N1.getValueType().getScalarType() == MVT::i1)
7508 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7509 break;
7511 // With a single lane, the result is true iff that lane is false.
7513 return getLogicalNOT(DL, N1, VT);
7514 break;
7515 case ISD::VECTOR_REPEAT:
7517 "VECTOR_REPEAT requires a fixed-length vector operand");
7518 assert(VT.isScalableVector() &&
7519 "VECTOR_REPEAT requires a scalable vector result");
7522 "VECTOR_REPEAT operand and result element counts must match");
7523 if (VT.getVectorMinNumElements() == 1)
7524 return getSplatVector(
7525 VT, DL, getExtractVectorElt(DL, VT.getVectorElementType(), N1, 0));
7526 break;
7527 case ISD::SPLAT_VECTOR:
7528 assert(VT.isVector() && "Wrong return type!");
7529 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7530 // that for now.
7532 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7534 N1.getValueType().isInteger() &&
7536 "Wrong operand type!");
7537 break;
7538 }
7539
7540 SDNode *N;
7541 SDVTList VTs = getVTList(VT);
7542 SDValue Ops[] = {N1};
7543 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7544 SDNodeKey ID(Opcode, VTs, Ops);
7545 FoldingSetInsertToken InsertToken;
7546 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7547 E->intersectFlagsWith(Flags);
7548 return SDValue(E, 0);
7549 }
7550
7551 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7552 N->setFlags(Flags);
7553 createOperands(N, Ops);
7554 CSEMap.insert(N, InsertToken);
7555 } else {
7556 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7557 createOperands(N, Ops);
7558 }
7559
7560 InsertNode(N);
7561 SDValue V = SDValue(N, 0);
7562 NewSDValueDbgMsg(V, "Creating new node: ", this);
7563 return V;
7564}
7565
7566static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7567 switch (Opcode) {
7568 default:
7569 llvm_unreachable("Unexpected integer identity opcode");
7570 case ISD::ADD:
7571 case ISD::OR:
7572 case ISD::XOR:
7573 case ISD::UMAX:
7574 return APInt::getZero(BitWidth);
7575 case ISD::MUL:
7576 return APInt(BitWidth, 1);
7577 case ISD::AND:
7578 case ISD::UMIN:
7580 case ISD::SMAX:
7582 case ISD::SMIN:
7584 }
7585}
7586
7587static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7588 const APInt &C2) {
7589 switch (Opcode) {
7590 case ISD::ADD: return C1 + C2;
7591 case ISD::SUB: return C1 - C2;
7592 case ISD::MUL: return C1 * C2;
7593 case ISD::AND: return C1 & C2;
7594 case ISD::OR: return C1 | C2;
7595 case ISD::XOR: return C1 ^ C2;
7596 case ISD::SHL: return C1 << C2;
7597 case ISD::SRL: return C1.lshr(C2);
7598 case ISD::SRA: return C1.ashr(C2);
7599 case ISD::ROTL: return C1.rotl(C2);
7600 case ISD::ROTR: return C1.rotr(C2);
7601 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7602 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7603 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7604 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7605 case ISD::SADDSAT: return C1.sadd_sat(C2);
7606 case ISD::UADDSAT: return C1.uadd_sat(C2);
7607 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7608 case ISD::USUBSAT: return C1.usub_sat(C2);
7609 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7610 case ISD::USHLSAT: return C1.ushl_sat(C2);
7611 case ISD::UDIV:
7612 if (!C2.getBoolValue())
7613 break;
7614 return C1.udiv(C2);
7615 case ISD::UREM:
7616 if (!C2.getBoolValue())
7617 break;
7618 return C1.urem(C2);
7619 case ISD::SDIV:
7620 if (!C2.getBoolValue())
7621 break;
7622 return C1.sdiv(C2);
7623 case ISD::SREM:
7624 if (!C2.getBoolValue())
7625 break;
7626 return C1.srem(C2);
7627 case ISD::AVGFLOORS:
7628 return APIntOps::avgFloorS(C1, C2);
7629 case ISD::AVGFLOORU:
7630 return APIntOps::avgFloorU(C1, C2);
7631 case ISD::AVGCEILS:
7632 return APIntOps::avgCeilS(C1, C2);
7633 case ISD::AVGCEILU:
7634 return APIntOps::avgCeilU(C1, C2);
7635 case ISD::AVGSUBFLOORS:
7636 return APIntOps::avgSubFloorS(C1, C2);
7637 case ISD::AVGSUBFLOORU:
7638 return APIntOps::avgSubFloorU(C1, C2);
7639 case ISD::ABDS:
7640 return APIntOps::abds(C1, C2);
7641 case ISD::ABDU:
7642 return APIntOps::abdu(C1, C2);
7643 case ISD::MULHS:
7644 return APIntOps::mulhs(C1, C2);
7645 case ISD::MULHU:
7646 return APIntOps::mulhu(C1, C2);
7647 case ISD::CLMUL:
7648 return APIntOps::clmul(C1, C2);
7649 case ISD::CLMULR:
7650 return APIntOps::clmulr(C1, C2);
7651 case ISD::CLMULH:
7652 return APIntOps::clmulh(C1, C2);
7653 case ISD::PEXT:
7654 return APIntOps::pext(C1, C2);
7655 case ISD::PDEP:
7656 return APIntOps::pdep(C1, C2);
7657 }
7658 return std::nullopt;
7659}
7660// Handle constant folding with UNDEF.
7661// TODO: Handle more cases.
7662static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7663 bool IsUndef1, const APInt &C2,
7664 bool IsUndef2) {
7665 if (!(IsUndef1 || IsUndef2))
7666 return FoldValue(Opcode, C1, C2);
7667
7668 // Fold and(x, undef) -> 0
7669 // Fold mul(x, undef) -> 0
7670 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7671 return APInt::getZero(C1.getBitWidth());
7672
7673 return std::nullopt;
7674}
7675
7677 const GlobalAddressSDNode *GA,
7678 const SDNode *N2) {
7679 if (GA->getOpcode() != ISD::GlobalAddress)
7680 return SDValue();
7681 if (!TLI->isOffsetFoldingLegal(GA))
7682 return SDValue();
7683 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7684 if (!C2)
7685 return SDValue();
7686 int64_t Offset = C2->getSExtValue();
7687 switch (Opcode) {
7688 case ISD::ADD:
7689 case ISD::PTRADD:
7690 break;
7691 case ISD::SUB: Offset = -uint64_t(Offset); break;
7692 default: return SDValue();
7693 }
7694 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7695 GA->getOffset() + uint64_t(Offset));
7696}
7697
7699 switch (Opcode) {
7700 case ISD::SDIV:
7701 case ISD::UDIV:
7702 case ISD::SREM:
7703 case ISD::UREM: {
7704 // If a divisor is zero/undef or any element of a divisor vector is
7705 // zero/undef, the whole op is undef.
7706 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7707 SDValue Divisor = Ops[1];
7708 if (Divisor.isUndef() || isNullConstant(Divisor))
7709 return true;
7710
7711 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7712 llvm::any_of(Divisor->op_values(),
7713 [](SDValue V) { return V.isUndef() ||
7714 isNullConstant(V); });
7715 // TODO: Handle signed overflow.
7716 }
7717 // TODO: Handle oversized shifts.
7718 default:
7719 return false;
7720 }
7721}
7722
7725 SDNodeFlags Flags) {
7726 // If the opcode is a target-specific ISD node, there's nothing we can
7727 // do here and the operand rules may not line up with the below, so
7728 // bail early.
7729 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7730 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7731 // foldCONCAT_VECTORS in getNode before this is called.
7732 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7733 return SDValue();
7734
7735 unsigned NumOps = Ops.size();
7736 if (NumOps == 0)
7737 return SDValue();
7738
7739 if (isUndef(Opcode, Ops))
7740 return getUNDEF(VT);
7741
7742 // Handle unary special cases.
7743 if (NumOps == 1) {
7744 SDValue N1 = Ops[0];
7745
7746 // Constant fold unary operations with an integer constant operand. Even
7747 // opaque constant will be folded, because the folding of unary operations
7748 // doesn't create new constants with different values. Nevertheless, the
7749 // opaque flag is preserved during folding to prevent future folding with
7750 // other constants.
7751 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7752 const APInt &Val = C->getAPIntValue();
7753 switch (Opcode) {
7754 case ISD::SIGN_EXTEND:
7755 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7756 C->isTargetOpcode(), C->isOpaque());
7757 case ISD::TRUNCATE:
7758 if (C->isOpaque())
7759 break;
7760 [[fallthrough]];
7761 case ISD::ZERO_EXTEND:
7762 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7763 C->isTargetOpcode(), C->isOpaque());
7764 case ISD::ANY_EXTEND:
7765 // Some targets like RISCV prefer to sign extend some types.
7766 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7767 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7768 C->isTargetOpcode(), C->isOpaque());
7769 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7770 C->isTargetOpcode(), C->isOpaque());
7771 case ISD::ABS:
7772 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7773 C->isOpaque());
7775 if (Val.isMinSignedValue())
7776 return getPOISON(VT);
7777 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7778 C->isOpaque());
7779 case ISD::BITREVERSE:
7780 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7781 C->isOpaque());
7782 case ISD::BSWAP:
7783 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7784 C->isOpaque());
7785 case ISD::CTPOP:
7786 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7787 C->isOpaque());
7788 case ISD::PARITY:
7789 return getConstant(Val.popcount() & 1, DL, VT, C->isTargetOpcode(),
7790 C->isOpaque());
7791 case ISD::CTLZ:
7793 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7794 C->isOpaque());
7795 case ISD::CTTZ:
7797 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7798 C->isOpaque());
7799 case ISD::CTLS:
7800 // CTLS returns the number of extra sign bits so subtract one.
7801 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7802 C->isTargetOpcode(), C->isOpaque());
7803 case ISD::UINT_TO_FP:
7804 case ISD::SINT_TO_FP: {
7806 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7808 return getConstantFP(FPV, DL, VT);
7809 }
7810 case ISD::FP16_TO_FP:
7811 case ISD::BF16_TO_FP: {
7812 bool Ignored;
7813 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7814 : APFloat::BFloat(),
7815 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7816
7817 // This can return overflow, underflow, or inexact; we don't care.
7818 // FIXME need to be more flexible about rounding mode.
7820 &Ignored);
7821 return getConstantFP(FPV, DL, VT);
7822 }
7823 case ISD::STEP_VECTOR:
7824 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7825 return V;
7826 break;
7827 case ISD::BITCAST:
7828 if (C->isOpaque())
7829 break;
7830 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7831 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7832 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7833 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7834 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7835 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7836 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7837 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7838 break;
7839 }
7840 }
7841
7842 // Constant fold unary operations with a floating point constant operand.
7843 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7844 APFloat V = C->getValueAPF(); // make copy
7845 switch (Opcode) {
7846 case ISD::FNEG:
7847 V.changeSign();
7848 return getConstantFP(V, DL, VT);
7849 case ISD::FABS:
7850 V.clearSign();
7851 return getConstantFP(V, DL, VT);
7852 case ISD::FCEIL: {
7853 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7855 return getConstantFP(V, DL, VT);
7856 return SDValue();
7857 }
7858 case ISD::FTRUNC: {
7859 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7861 return getConstantFP(V, DL, VT);
7862 return SDValue();
7863 }
7864 case ISD::FFLOOR: {
7865 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7867 return getConstantFP(V, DL, VT);
7868 return SDValue();
7869 }
7870 case ISD::FP_EXTEND: {
7871 bool ignored;
7872 // This can return overflow, underflow, or inexact; we don't care.
7873 // FIXME need to be more flexible about rounding mode.
7874 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7875 &ignored);
7876 return getConstantFP(V, DL, VT);
7877 }
7878 case ISD::FP_TO_SINT:
7879 case ISD::FP_TO_UINT: {
7880 bool ignored;
7881 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7882 // FIXME need to be more flexible about rounding mode.
7884 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7885 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7886 break;
7887 return getConstant(IntVal, DL, VT);
7888 }
7889 case ISD::FP_TO_FP16:
7890 case ISD::FP_TO_BF16: {
7891 bool Ignored;
7892 // This can return overflow, underflow, or inexact; we don't care.
7893 // FIXME need to be more flexible about rounding mode.
7894 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7895 : APFloat::BFloat(),
7897 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7898 }
7899 case ISD::BITCAST:
7900 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7901 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7902 VT);
7903 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7904 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7905 VT);
7906 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7907 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7908 VT);
7909 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7910 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7911 break;
7912 }
7913 }
7914
7915 // Early-out if we failed to constant fold a bitcast.
7916 if (Opcode == ISD::BITCAST)
7917 return SDValue();
7918
7919 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7920 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7921 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7922 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7923 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7924 Opcode == ISD::VECREDUCE_AND) &&
7926 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7927 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7928 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7929 for (SDValue Elt : N1->op_values()) {
7930 if (Elt.getOpcode() == ISD::POISON)
7931 return getPOISON(VT);
7932 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7933 return SDValue();
7934 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7935 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7936 assert(Folded &&
7937 "Expected vector reduction base opcode to be foldable");
7938 Acc = *Folded;
7939 }
7940 EVT EltVT = N1.getValueType().getScalarType();
7941 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7942 }
7943 }
7944
7945 // Handle binops special cases.
7946 if (NumOps == 2) {
7947 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7948 return CFP;
7949
7950 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7951 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7952 if (C1->isOpaque() || C2->isOpaque())
7953 return SDValue();
7954
7955 std::optional<APInt> FoldAttempt =
7956 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7957 if (!FoldAttempt)
7958 return SDValue();
7959
7960 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7961 assert((!Folded || !VT.isVector()) &&
7962 "Can't fold vectors ops with scalar operands");
7963 return Folded;
7964 }
7965 }
7966
7967 // fold (add Sym, c) -> Sym+c
7969 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7970 if (TLI->isCommutativeBinOp(Opcode))
7972 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7973
7974 // fold (sext_in_reg c1) -> c2
7975 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7976 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7977
7978 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7979 unsigned FromBits = EVT.getScalarSizeInBits();
7980 Val <<= Val.getBitWidth() - FromBits;
7981 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7982 return getConstant(Val, DL, ConstantVT);
7983 };
7984
7985 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7986 const APInt &Val = C1->getAPIntValue();
7987 return SignExtendInReg(Val, VT);
7988 }
7989
7991 SmallVector<SDValue, 8> ScalarOps;
7992 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7993 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7994 SDValue Op = Ops[0].getOperand(I);
7995 if (Op.isUndef()) {
7996 ScalarOps.push_back(getUNDEF(OpVT));
7997 continue;
7998 }
7999 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
8000 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
8001 }
8002 return getBuildVector(VT, DL, ScalarOps);
8003 }
8004
8005 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
8006 isa<ConstantSDNode>(Ops[0].getOperand(0)))
8007 return getNode(ISD::SPLAT_VECTOR, DL, VT,
8008 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
8009 Ops[0].getOperand(0).getValueType()));
8010 }
8011 }
8012
8013 // Handle fshl/fshr special cases.
8014 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
8015 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
8016 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
8017 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
8018
8019 if (C1 && C2 && C3) {
8020 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
8021 return SDValue();
8022 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
8023 &V3 = C3->getAPIntValue();
8024
8025 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
8026 : APIntOps::fshr(V1, V2, V3);
8027 return getConstant(FoldedVal, DL, VT);
8028 }
8029 }
8030
8031 // Handle fma/fmad special cases.
8032 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8033 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8034 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8035 Ops[2].getValueType() == VT && "FMA types must match!");
8039 if (C1 && C2 && C3) {
8040 APFloat V1 = C1->getValueAPF();
8041 const APFloat &V2 = C2->getValueAPF();
8042 const APFloat &V3 = C3->getValueAPF();
8043 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8044 V1.multiply(V2, APFloat::rmNearestTiesToEven);
8046 } else
8047 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
8048 return getConstantFP(V1, DL, VT);
8049 }
8050 }
8051
8052 // This is for vector folding only from here on.
8053 if (!VT.isVector())
8054 return SDValue();
8055
8056 // Constant fold integer partial reductions with constant BUILD_VECTOR
8057 // operands. The reduction order is deliberately unspecified. Use the same
8058 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
8059 // lane I contributes to accumulator lane I % NumAccElts.
8060 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
8061 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
8062 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
8063 // These nodes have no scalar form, so unsupported cases must not fall
8064 // through to generic per-lane vector folding.
8065 if (!llvm::all_of(Ops, [](SDValue Op) {
8066 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
8067 }))
8068 return SDValue();
8069
8070 unsigned AccEltBits = VT.getScalarSizeInBits();
8071 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8072 unsigned NumAccElts = VT.getVectorNumElements();
8073 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8074 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8075 BitVector PoisonElts(NumAccElts);
8076
8077 for (unsigned I = 0; I != NumAccElts; ++I) {
8078 SDValue Elt = Ops[0].getOperand(I);
8079 if (Elt.getOpcode() == ISD::POISON) {
8080 PoisonElts.set(I);
8081 continue;
8082 }
8083 auto *C = dyn_cast<ConstantSDNode>(Elt);
8084 if (!C || C->isOpaque())
8085 return SDValue();
8086 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8087 }
8088
8089 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8090 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8091 for (unsigned I = 0; I != NumInputElts; ++I) {
8092 const unsigned AccIdx = I % NumAccElts;
8093 SDValue LHSElt = Ops[1].getOperand(I);
8094 SDValue RHSElt = Ops[2].getOperand(I);
8095 if (LHSElt.getOpcode() == ISD::POISON ||
8096 RHSElt.getOpcode() == ISD::POISON) {
8097 PoisonElts.set(AccIdx);
8098 continue;
8099 }
8100
8101 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8102 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8103 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8104 return SDValue();
8105
8106 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8107 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8108 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8109 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8110 Results[AccIdx] += LHSVal * RHSVal;
8111 }
8112
8113 // After type legalization the vector element type may not be a legal
8114 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8115 // promoted legal scalar type instead, matching the generic per-lane path
8116 // below. Bail out if legalization would narrow the type, since the lane
8117 // value would not fit.
8118 EVT AccEltVT = VT.getVectorElementType();
8119 EVT LegalSVT = AccEltVT;
8120 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8121 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8122 if (LegalSVT.bitsLT(AccEltVT))
8123 return SDValue();
8124 }
8125
8126 SmallVector<SDValue, 8> ResultOps;
8127 for (unsigned I = 0; I != NumAccElts; ++I)
8128 ResultOps.push_back(
8129 PoisonElts[I] ? getPOISON(LegalSVT)
8130 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8131 DL, LegalSVT));
8132 return getBuildVector(VT, DL, ResultOps);
8133 }
8134
8135 ElementCount NumElts = VT.getVectorElementCount();
8136
8137 // See if we can fold through any bitcasted integer ops.
8138 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8139 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8140 (Ops[0].getOpcode() == ISD::BITCAST ||
8141 Ops[1].getOpcode() == ISD::BITCAST)) {
8144 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8145 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8146 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8147 N2.getValueType().isInteger()) {
8148 bool IsLE = getDataLayout().isLittleEndian();
8149 unsigned EltBits = VT.getScalarSizeInBits();
8150 SmallVector<APInt> RawBits1, RawBits2;
8151 BitVector UndefElts1, UndefElts2;
8152 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8153 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8154 SmallVector<APInt> RawBits;
8155 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8156 std::optional<APInt> Fold = FoldValueWithUndef(
8157 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8158 if (!Fold)
8159 break;
8160 RawBits.push_back(*Fold);
8161 }
8162 if (RawBits.size() == NumElts.getFixedValue()) {
8163 // We have constant folded, but we might need to cast this again back
8164 // to the original (possibly legalized) type.
8165 EVT BVVT, BVEltVT;
8166 if (N1.getValueType() == VT) {
8167 BVVT = N1.getValueType();
8168 BVEltVT = BV1->getOperand(0).getValueType();
8169 } else {
8170 BVVT = N2.getValueType();
8171 BVEltVT = BV2->getOperand(0).getValueType();
8172 }
8173 unsigned BVEltBits = BVEltVT.getSizeInBits();
8174 SmallVector<APInt> DstBits;
8175 BitVector DstUndefs;
8177 DstBits, RawBits, DstUndefs,
8178 BitVector(RawBits.size(), false));
8179 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8180 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8181 if (DstUndefs[I])
8182 continue;
8183 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8184 }
8185 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8186 }
8187 }
8188 }
8189 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8190 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8191 isa<ConstantSDNode>(N2)) {
8192 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8193 {N1, N2}, Flags))
8194 return getBitcast(VT, Res);
8195 }
8196 }
8197
8198 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8199 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8200 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8201 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8202 APInt RHSVal;
8203 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8204 APInt NewStep = Opcode == ISD::MUL
8205 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8206 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8207 return getStepVector(DL, VT, NewStep);
8208 }
8209 }
8210
8211 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8212 return !Op.getValueType().isVector() ||
8213 Op.getValueType().getVectorElementCount() == NumElts;
8214 };
8215
8216 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8217 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8218 Op.getOpcode() == ISD::BUILD_VECTOR ||
8219 Op.getOpcode() == ISD::SPLAT_VECTOR;
8220 };
8221
8222 // All operands must be vector types with the same number of elements as
8223 // the result type and must be either UNDEF or a build/splat vector
8224 // or UNDEF scalars.
8225 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8226 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8227 return SDValue();
8228
8229 // If we are comparing vectors, then the result needs to be a i1 boolean that
8230 // is then extended back to the legal result type depending on how booleans
8231 // are represented.
8232 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8233 ISD::NodeType ExtendCode =
8234 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8235 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8237
8238 // Find legal integer scalar type for constant promotion and
8239 // ensure that its scalar size is at least as large as source.
8240 EVT LegalSVT = VT.getScalarType();
8241 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8242 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8243 if (LegalSVT.bitsLT(VT.getScalarType()))
8244 return SDValue();
8245 }
8246
8247 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8248 // only have one operand to check. For fixed-length vector types we may have
8249 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8250 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8251
8252 // Constant fold each scalar lane separately.
8253 SmallVector<SDValue, 4> ScalarResults;
8254 for (unsigned I = 0; I != NumVectorElts; I++) {
8255 SmallVector<SDValue, 4> ScalarOps;
8256 for (SDValue Op : Ops) {
8257 EVT InSVT = Op.getValueType().getScalarType();
8258 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8259 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8260 if (Op.isUndef())
8261 ScalarOps.push_back(getUNDEF(InSVT));
8262 else
8263 ScalarOps.push_back(Op);
8264 continue;
8265 }
8266
8267 SDValue ScalarOp =
8268 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8269 EVT ScalarVT = ScalarOp.getValueType();
8270
8271 // Build vector (integer) scalar operands may need implicit
8272 // truncation - do this before constant folding.
8273 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8274 // Don't create illegally-typed nodes unless they're constants or undef
8275 // - if we fail to constant fold we can't guarantee the (dead) nodes
8276 // we're creating will be cleaned up before being visited for
8277 // legalization.
8278 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8279 !isa<ConstantSDNode>(ScalarOp) &&
8280 TLI->getTypeAction(*getContext(), InSVT) !=
8282 return SDValue();
8283 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8284 }
8285
8286 ScalarOps.push_back(ScalarOp);
8287 }
8288
8289 // Constant fold the scalar operands.
8290 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8291
8292 // Scalar folding only succeeded if the result is a constant or UNDEF.
8293 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8294 ScalarResult.getOpcode() != ISD::ConstantFP)
8295 return SDValue();
8296
8297 // Legalize the (integer) scalar constant if necessary. We only do
8298 // this once we know the folding succeeded, since otherwise we would
8299 // get a node with illegal type which has a user.
8300 if (LegalSVT != SVT)
8301 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8302
8303 ScalarResults.push_back(ScalarResult);
8304 }
8305
8306 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8307 : getBuildVector(VT, DL, ScalarResults);
8308 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8309 return V;
8310}
8311
8313 SDVTList VTList,
8315 SDNodeFlags Flags) {
8316 if (VTList.NumVTs == 1)
8317 return FoldConstantArithmetic(Opcode, DL, VTList.VTs[0], Ops, Flags);
8318
8319 switch (Opcode) {
8320 case ISD::SADDO:
8321 case ISD::UADDO:
8322 case ISD::SSUBO:
8323 case ISD::USUBO:
8324 case ISD::SMULO:
8325 case ISD::UMULO: {
8326 // TODO: Support non-splat vector constants.
8329 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8330 return SDValue();
8331
8332 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8333 bool Overflow;
8334 APInt Result;
8335 switch (Opcode) {
8336 default:
8337 llvm_unreachable("Unexpected overflow opcode");
8338 case ISD::SADDO:
8339 Result = V1.sadd_ov(V2, Overflow);
8340 break;
8341 case ISD::UADDO:
8342 Result = V1.uadd_ov(V2, Overflow);
8343 break;
8344 case ISD::SSUBO:
8345 Result = V1.ssub_ov(V2, Overflow);
8346 break;
8347 case ISD::USUBO:
8348 Result = V1.usub_ov(V2, Overflow);
8349 break;
8350 case ISD::SMULO:
8351 Result = V1.smul_ov(V2, Overflow);
8352 break;
8353 case ISD::UMULO:
8354 Result = V1.umul_ov(V2, Overflow);
8355 break;
8356 }
8357
8358 EVT VT = VTList.VTs[0];
8359 return getNode(ISD::MERGE_VALUES, DL, VTList,
8360 {getConstant(Result, DL, VT),
8361 getBoolConstant(Overflow, DL, VTList.VTs[1], VT)},
8362 Flags);
8363 }
8364 }
8365 return SDValue();
8366}
8367
8370 // TODO: Add support for unary/ternary fp opcodes.
8371 if (Ops.size() != 2)
8372 return SDValue();
8373
8374 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8375 // should. That will require dealing with a potentially non-default
8376 // rounding mode, checking the "opStatus" return value from the APFloat
8377 // math calculations, and possibly other variations.
8378 SDValue N1 = Ops[0];
8379 SDValue N2 = Ops[1];
8380 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8381 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8382 if (N1CFP && N2CFP) {
8383 APFloat C1 = N1CFP->getValueAPF(); // make copy
8384 const APFloat &C2 = N2CFP->getValueAPF();
8385 switch (Opcode) {
8386 case ISD::FADD:
8388 return getConstantFP(C1, DL, VT);
8389 case ISD::FSUB:
8391 return getConstantFP(C1, DL, VT);
8392 case ISD::FMUL:
8394 return getConstantFP(C1, DL, VT);
8395 case ISD::FDIV:
8397 return getConstantFP(C1, DL, VT);
8398 case ISD::FREM:
8399 C1.mod(C2);
8400 return getConstantFP(C1, DL, VT);
8401 case ISD::FCOPYSIGN:
8402 C1.copySign(C2);
8403 return getConstantFP(C1, DL, VT);
8404 case ISD::FMINNUM:
8405 return getConstantFP(minnum(C1, C2), DL, VT);
8406 case ISD::FMAXNUM:
8407 return getConstantFP(maxnum(C1, C2), DL, VT);
8408 case ISD::FMINIMUM:
8409 return getConstantFP(minimum(C1, C2), DL, VT);
8410 case ISD::FMAXIMUM:
8411 return getConstantFP(maximum(C1, C2), DL, VT);
8412 case ISD::FMINIMUMNUM:
8413 return getConstantFP(minimumnum(C1, C2), DL, VT);
8414 case ISD::FMAXIMUMNUM:
8415 return getConstantFP(maximumnum(C1, C2), DL, VT);
8416 default: break;
8417 }
8418 }
8419 if (N1CFP && Opcode == ISD::FP_ROUND) {
8420 APFloat C1 = N1CFP->getValueAPF(); // make copy
8421 bool Unused;
8422 // This can return overflow, underflow, or inexact; we don't care.
8423 // FIXME need to be more flexible about rounding mode.
8425 &Unused);
8426 return getConstantFP(C1, DL, VT);
8427 }
8428
8429 switch (Opcode) {
8430 case ISD::FSUB:
8431 // -0.0 - undef --> undef (consistent with "fneg undef")
8432 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8433 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8434 return getUNDEF(VT);
8435 [[fallthrough]];
8436
8437 case ISD::FADD:
8438 case ISD::FMUL:
8439 case ISD::FDIV:
8440 case ISD::FREM:
8441 // If both operands are undef, the result is undef. If 1 operand is undef,
8442 // the result is NaN. This should match the behavior of the IR optimizer.
8443 if (N1.isUndef() && N2.isUndef())
8444 return getUNDEF(VT);
8445 if (N1.isUndef() || N2.isUndef())
8447 }
8448 return SDValue();
8449}
8450
8452 const SDLoc &DL, EVT DstEltVT) {
8453 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8454
8455 // If this is already the right type, we're done.
8456 if (SrcEltVT == DstEltVT)
8457 return SDValue(BV, 0);
8458
8459 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8460 unsigned DstBitSize = DstEltVT.getSizeInBits();
8461
8462 // If this is a conversion of N elements of one type to N elements of another
8463 // type, convert each element. This handles FP<->INT cases.
8464 if (SrcBitSize == DstBitSize) {
8466 for (SDValue Op : BV->op_values()) {
8467 // If the vector element type is not legal, the BUILD_VECTOR operands
8468 // are promoted and implicitly truncated. Make that explicit here.
8469 if (Op.getValueType() != SrcEltVT)
8470 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8471 Ops.push_back(getBitcast(DstEltVT, Op));
8472 }
8473 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8475 return getBuildVector(VT, DL, Ops);
8476 }
8477
8478 // Otherwise, we're growing or shrinking the elements. To avoid having to
8479 // handle annoying details of growing/shrinking FP values, we convert them to
8480 // int first.
8481 if (SrcEltVT.isFloatingPoint()) {
8482 // Convert the input float vector to a int vector where the elements are the
8483 // same sizes.
8484 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8485 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8487 DstEltVT);
8488 return SDValue();
8489 }
8490
8491 // Now we know the input is an integer vector. If the output is a FP type,
8492 // convert to integer first, then to FP of the right size.
8493 if (DstEltVT.isFloatingPoint()) {
8494 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8495 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8497 DstEltVT);
8498 return SDValue();
8499 }
8500
8501 // Okay, we know the src/dst types are both integers of differing types.
8502 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8503
8504 // Extract the constant raw bit data.
8505 BitVector UndefElements;
8506 SmallVector<APInt> RawBits;
8507 bool IsLE = getDataLayout().isLittleEndian();
8508 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8509 return SDValue();
8510
8512 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8513 if (UndefElements[I])
8514 Ops.push_back(getUNDEF(DstEltVT));
8515 else
8516 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8517 }
8518
8519 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8520 return getBuildVector(VT, DL, Ops);
8521}
8522
8524 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8525
8526 // There's no need to assert on a byte-aligned pointer. All pointers are at
8527 // least byte aligned.
8528 if (A == Align(1))
8529 return Val;
8530
8531 SDVTList VTs = getVTList(Val.getValueType());
8532 SDValue Ops[] = {Val};
8533 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8534 ID.AddInteger(A.value());
8535
8536 FoldingSetInsertToken InsertToken;
8537 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8538 return SDValue(E, 0);
8539
8540 auto *N =
8541 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8542 createOperands(N, {Val});
8543
8544 CSEMap.insert(N, InsertToken);
8545 InsertNode(N);
8546
8547 SDValue V(N, 0);
8548 NewSDValueDbgMsg(V, "Creating new node: ", this);
8549 return V;
8550}
8551
8552SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8553 SDValue N1, SDValue N2) {
8554 SDNodeFlags Flags;
8555 if (Inserter)
8556 Flags = Inserter->getFlags();
8557 return getNode(Opcode, DL, VT, N1, N2, Flags);
8558}
8559
8561 SDValue &N2) const {
8562 if (!TLI->isCommutativeBinOp(Opcode))
8563 return;
8564
8565 // Canonicalize:
8566 // binop(const, nonconst) -> binop(nonconst, const)
8569 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8570 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8571 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8572 std::swap(N1, N2);
8573
8574 // Canonicalize:
8575 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8576 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8578 std::swap(N1, N2);
8579}
8580
8581SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8582 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8584 N2.getOpcode() != ISD::DELETED_NODE &&
8585 "Operand is DELETED_NODE!");
8586
8587 canonicalizeCommutativeBinop(Opcode, N1, N2);
8588
8589 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8590 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8591
8592 // Don't allow undefs in vector splats - we might be returning N2 when folding
8593 // to zero etc.
8594 ConstantSDNode *N2CV =
8595 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8596
8597 switch (Opcode) {
8598 default: break;
8599 case ISD::TokenFactor:
8600 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8601 N2.getValueType() == MVT::Other && "Invalid token factor!");
8602 // Fold trivial token factors.
8603 if (N1.getOpcode() == ISD::EntryToken) return N2;
8604 if (N2.getOpcode() == ISD::EntryToken) return N1;
8605 if (N1 == N2) return N1;
8606 break;
8607 case ISD::BUILD_VECTOR: {
8608 // Attempt to simplify BUILD_VECTOR.
8609 SDValue Ops[] = {N1, N2};
8610 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8611 return V;
8612 break;
8613 }
8614 case ISD::CONCAT_VECTORS: {
8615 SDValue Ops[] = {N1, N2};
8616 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8617 return V;
8618 break;
8619 }
8620 case ISD::AND:
8621 assert(VT.isInteger() && "This operator does not apply to FP types!");
8622 assert(N1.getValueType() == N2.getValueType() &&
8623 N1.getValueType() == VT && "Binary operator types must match!");
8624 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8625 // worth handling here.
8626 if (N2CV && N2CV->isZero())
8627 return N2;
8628 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8629 return N1;
8630 break;
8631 case ISD::OR:
8632 case ISD::XOR:
8633 case ISD::ADD:
8634 case ISD::PTRADD:
8635 case ISD::SUB:
8636 assert(VT.isInteger() && "This operator does not apply to FP types!");
8637 assert(N1.getValueType() == N2.getValueType() &&
8638 N1.getValueType() == VT && "Binary operator types must match!");
8639 // The equal operand types requirement is unnecessarily strong for PTRADD.
8640 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8641 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8642 // logic everywhere where PTRADDs may be folded or combined to properly
8643 // support them. If/when we introduce pointer types to the SDAG, we will
8644 // need to relax this constraint.
8645
8646 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8647 // it's worth handling here.
8648 if (N2CV && N2CV->isZero())
8649 return N1;
8650 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8651 VT.getScalarType() == MVT::i1)
8652 return getNode(ISD::XOR, DL, VT, N1, N2);
8653 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8654 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8655 N2.getOpcode() == ISD::VSCALE) {
8656 const APInt &C1 = N1->getConstantOperandAPInt(0);
8657 const APInt &C2 = N2->getConstantOperandAPInt(0);
8658 return getVScale(DL, VT, C1 + C2);
8659 }
8660 break;
8661 case ISD::MUL:
8662 assert(VT.isInteger() && "This operator does not apply to FP types!");
8663 assert(N1.getValueType() == N2.getValueType() &&
8664 N1.getValueType() == VT && "Binary operator types must match!");
8665 if (VT.getScalarType() == MVT::i1)
8666 return getNode(ISD::AND, DL, VT, N1, N2);
8667 if (N2CV && N2CV->isZero())
8668 return N2;
8669 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8670 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8671 const APInt &N2CImm = N2C->getAPIntValue();
8672 return getVScale(DL, VT, MulImm * N2CImm);
8673 }
8674 break;
8675 case ISD::UDIV:
8676 case ISD::UREM:
8677 case ISD::MULHU:
8678 case ISD::MULHS:
8679 case ISD::SDIV:
8680 case ISD::SREM:
8681 case ISD::SADDSAT:
8682 case ISD::SSUBSAT:
8683 case ISD::UADDSAT:
8684 case ISD::USUBSAT:
8685 assert(VT.isInteger() && "This operator does not apply to FP types!");
8686 assert(N1.getValueType() == N2.getValueType() &&
8687 N1.getValueType() == VT && "Binary operator types must match!");
8688 if (VT.getScalarType() == MVT::i1) {
8689 // fold (add_sat x, y) -> (or x, y) for bool types.
8690 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8691 return getNode(ISD::OR, DL, VT, N1, N2);
8692 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8693 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8694 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8695 }
8696 break;
8697 case ISD::SCMP:
8698 case ISD::UCMP:
8699 assert(N1.getValueType() == N2.getValueType() &&
8700 "Types of operands of UCMP/SCMP must match");
8701 assert(N1.getValueType().isVector() == VT.isVector() &&
8702 "Operands and return type of must both be scalars or vectors");
8703 if (VT.isVector())
8706 "Result and operands must have the same number of elements");
8707 break;
8708 case ISD::AVGFLOORS:
8709 case ISD::AVGFLOORU:
8710 case ISD::AVGCEILS:
8711 case ISD::AVGCEILU:
8712 case ISD::AVGSUBFLOORS:
8713 case ISD::AVGSUBFLOORU:
8714 assert(VT.isInteger() && "This operator does not apply to FP types!");
8715 assert(N1.getValueType() == N2.getValueType() &&
8716 N1.getValueType() == VT && "Binary operator types must match!");
8717 break;
8718 case ISD::ABDS:
8719 case ISD::ABDU:
8720 assert(VT.isInteger() && "This operator does not apply to FP types!");
8721 assert(N1.getValueType() == N2.getValueType() &&
8722 N1.getValueType() == VT && "Binary operator types must match!");
8723 if (VT.getScalarType() == MVT::i1)
8724 return getNode(ISD::XOR, DL, VT, N1, N2);
8725 break;
8726 case ISD::SMIN:
8727 case ISD::UMAX:
8728 assert(VT.isInteger() && "This operator does not apply to FP types!");
8729 assert(N1.getValueType() == N2.getValueType() &&
8730 N1.getValueType() == VT && "Binary operator types must match!");
8731 if (VT.getScalarType() == MVT::i1)
8732 return getNode(ISD::OR, DL, VT, N1, N2);
8733 break;
8734 case ISD::SMAX:
8735 case ISD::UMIN:
8736 assert(VT.isInteger() && "This operator does not apply to FP types!");
8737 assert(N1.getValueType() == N2.getValueType() &&
8738 N1.getValueType() == VT && "Binary operator types must match!");
8739 if (VT.getScalarType() == MVT::i1)
8740 return getNode(ISD::AND, DL, VT, N1, N2);
8741 break;
8742 case ISD::FADD:
8743 case ISD::FSUB:
8744 case ISD::FMUL:
8745 case ISD::FDIV:
8746 case ISD::FREM:
8747 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8748 assert(N1.getValueType() == N2.getValueType() &&
8749 N1.getValueType() == VT && "Binary operator types must match!");
8750 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8751 return V;
8752 break;
8753 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8754 assert(N1.getValueType() == VT &&
8757 "Invalid FCOPYSIGN!");
8758 break;
8759 case ISD::SHL:
8760 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8761 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8762 const APInt &ShiftImm = N2C->getAPIntValue();
8763 return getVScale(DL, VT, MulImm << ShiftImm);
8764 }
8765 [[fallthrough]];
8766 case ISD::SRA:
8767 case ISD::SRL:
8768 if (SDValue V = simplifyShift(N1, N2))
8769 return V;
8770 [[fallthrough]];
8771 case ISD::ROTL:
8772 case ISD::ROTR:
8773 case ISD::SSHLSAT:
8774 case ISD::USHLSAT:
8775 assert(VT == N1.getValueType() &&
8776 "Shift operators return type must be the same as their first arg");
8777 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8778 "Shifts only work on integers");
8779 assert((!VT.isVector() || VT == N2.getValueType()) &&
8780 "Vector shift amounts must be in the same as their first arg");
8781 // Verify that the shift amount VT is big enough to hold valid shift
8782 // amounts. This catches things like trying to shift an i1024 value by an
8783 // i8, which is easy to fall into in generic code that uses
8784 // TLI.getShiftAmount().
8787 "Invalid use of small shift amount with oversized value!");
8788
8789 // Always fold shifts of i1 values so the code generator doesn't need to
8790 // handle them. Since we know the size of the shift has to be less than the
8791 // size of the value, the shift/rotate count is guaranteed to be zero.
8792 if (VT == MVT::i1)
8793 return N1;
8794 if (N2CV && N2CV->isZero())
8795 return N1;
8796 break;
8797 case ISD::FP_ROUND:
8799 VT.bitsLE(N1.getValueType()) && N2C &&
8800 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8801 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8802 if (N1.getValueType() == VT) return N1; // noop conversion.
8803 break;
8804 case ISD::IS_FPCLASS: {
8806 "IS_FPCLASS is used for a non-floating type");
8807 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8808 // is.fpclass(poison, mask) -> poison
8809 if (N1.getOpcode() == ISD::POISON)
8810 return getPOISON(VT);
8811 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8812 // If all tests are made, it doesn't matter what the value is.
8813 if ((Mask & fcAllFlags) == fcAllFlags)
8814 return getBoolConstant(true, DL, VT, N1.getValueType());
8815 if ((Mask & fcAllFlags) == 0)
8816 return getBoolConstant(false, DL, VT, N1.getValueType());
8817 break;
8818 }
8819 case ISD::AssertNoFPClass: {
8821 "AssertNoFPClass is used for a non-floating type");
8822 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8823 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8824 assert(llvm::to_underlying(NoFPClass) <=
8826 "FPClassTest value too large");
8827 (void)NoFPClass;
8828 break;
8829 }
8830 case ISD::AssertSext:
8831 case ISD::AssertZext: {
8832 EVT EVT = cast<VTSDNode>(N2)->getVT();
8833 assert(VT == N1.getValueType() && "Not an inreg extend!");
8834 assert(VT.isInteger() && EVT.isInteger() &&
8835 "Cannot *_EXTEND_INREG FP types");
8836 assert(!EVT.isVector() &&
8837 "AssertSExt/AssertZExt type should be the vector element type "
8838 "rather than the vector type!");
8839 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8840 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8841 break;
8842 }
8844 EVT EVT = cast<VTSDNode>(N2)->getVT();
8845 assert(VT == N1.getValueType() && "Not an inreg extend!");
8846 assert(VT.isInteger() && EVT.isInteger() &&
8847 "Cannot *_EXTEND_INREG FP types");
8848 assert(EVT.isVector() == VT.isVector() &&
8849 "SIGN_EXTEND_INREG type should be vector iff the operand "
8850 "type is vector!");
8851 assert((!EVT.isVector() ||
8853 "Vector element counts must match in SIGN_EXTEND_INREG");
8854 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8855 if (EVT == VT) return N1; // Not actually extending
8856 break;
8857 }
8859 case ISD::FP_TO_UINT_SAT: {
8860 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8861 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8862 assert(N1.getValueType().isVector() == VT.isVector() &&
8863 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8864 "vector!");
8865 assert((!VT.isVector() || VT.getVectorElementCount() ==
8867 "Vector element counts must match in FP_TO_*INT_SAT");
8868 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8869 "Type to saturate to must be a scalar.");
8870 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8871 "Not extending!");
8872 break;
8873 }
8876 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8877 element type of the vector.");
8878
8879 // Extract from an undefined value or using an undefined index is undefined.
8880 if (N1.isUndef() || N2.isUndef())
8881 return getUNDEF(VT);
8882
8883 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8884 // vectors. For scalable vectors we will provide appropriate support for
8885 // dealing with arbitrary indices.
8886 if (N2C && N1.getValueType().isFixedLengthVector() &&
8887 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8888 return getPOISON(VT);
8889
8890 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8891 // expanding copies of large vectors from registers. This only works for
8892 // fixed length vectors, since we need to know the exact number of
8893 // elements.
8894 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8896 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8897 return getExtractVectorElt(DL, VT,
8898 N1.getOperand(N2C->getZExtValue() / Factor),
8899 N2C->getZExtValue() % Factor);
8900 }
8901
8902 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8903 // lowering is expanding large vector constants.
8904 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8905 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8908 "BUILD_VECTOR used for scalable vectors");
8909 unsigned Index =
8910 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8911 SDValue Elt = N1.getOperand(Index);
8912
8913 if (VT != Elt.getValueType())
8914 // If the vector element type is not legal, the BUILD_VECTOR operands
8915 // are promoted and implicitly truncated, and the result implicitly
8916 // extended. Make that explicit here.
8917 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8918
8919 return Elt;
8920 }
8921
8922 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8923 // operations are lowered to scalars.
8924 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8925 // If the indices are the same, return the inserted element else
8926 // if the indices are known different, extract the element from
8927 // the original vector.
8928 SDValue N1Op2 = N1.getOperand(2);
8930
8931 if (N1Op2C && N2C) {
8932 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8933 if (VT == N1.getOperand(1).getValueType())
8934 return N1.getOperand(1);
8935 if (VT.isFloatingPoint()) {
8937 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8938 }
8939 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8940 }
8941 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8942 }
8943 }
8944
8945 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8946 // when vector types are scalarized and v1iX is legal.
8947 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8948 // Here we are completely ignoring the extract element index (N2),
8949 // which is fine for fixed width vectors, since any index other than 0
8950 // is undefined anyway. However, this cannot be ignored for scalable
8951 // vectors - in theory we could support this, but we don't want to do this
8952 // without a profitability check.
8953 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8955 N1.getValueType().getVectorNumElements() == 1) {
8956 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8957 N1.getOperand(1));
8958 }
8959 break;
8961 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8962 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8963 (N1.getValueType().isInteger() == VT.isInteger()) &&
8964 N1.getValueType() != VT &&
8965 "Wrong types for EXTRACT_ELEMENT!");
8966
8967 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8968 // 64-bit integers into 32-bit parts. Instead of building the extract of
8969 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8970 if (N1.getOpcode() == ISD::BUILD_PAIR)
8971 return N1.getOperand(N2C->getZExtValue());
8972
8973 // EXTRACT_ELEMENT of a constant int is also very common.
8974 if (N1C) {
8975 unsigned ElementSize = VT.getSizeInBits();
8976 unsigned Shift = ElementSize * N2C->getZExtValue();
8977 const APInt &Val = N1C->getAPIntValue();
8978 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8979 }
8980 break;
8982 EVT N1VT = N1.getValueType();
8983 assert(VT.isVector() && N1VT.isVector() &&
8984 "Extract subvector VTs must be vectors!");
8986 "Extract subvector VTs must have the same element type!");
8987 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8988 "Cannot extract a scalable vector from a fixed length vector!");
8989 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8991 "Extract subvector must be from larger vector to smaller vector!");
8992 assert(N2C && "Extract subvector index must be a constant");
8993 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8994 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8995 N1VT.getVectorMinNumElements()) &&
8996 "Extract subvector overflow!");
8997 assert(N2C->getAPIntValue().getBitWidth() ==
8998 TLI->getVectorIdxWidth(getDataLayout()) &&
8999 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
9000 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
9001 "Extract index is not a multiple of the output vector length");
9002
9003 // Trivial extraction.
9004 if (VT == N1VT)
9005 return N1;
9006
9007 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
9008 if (N1.isUndef())
9009 return getUNDEF(VT);
9010
9011 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
9012 // the concat have the same type as the extract.
9013 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9014 VT == N1.getOperand(0).getValueType()) {
9015 unsigned Factor = VT.getVectorMinNumElements();
9016 return N1.getOperand(N2C->getZExtValue() / Factor);
9017 }
9018
9019 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
9020 // during shuffle legalization.
9021 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
9022 VT == N1.getOperand(1).getValueType())
9023 return N1.getOperand(1);
9024 break;
9025 }
9026 }
9027
9028 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
9029 switch (Opcode) {
9030 case ISD::XOR:
9031 case ISD::ADD:
9032 case ISD::PTRADD:
9033 case ISD::SUB:
9035 case ISD::UDIV:
9036 case ISD::SDIV:
9037 case ISD::UREM:
9038 case ISD::SREM:
9039 case ISD::MUL:
9040 case ISD::AND:
9041 case ISD::SSUBSAT:
9042 case ISD::USUBSAT:
9043 case ISD::UMIN:
9044 case ISD::OR:
9045 case ISD::SADDSAT:
9046 case ISD::UADDSAT:
9047 case ISD::UMAX:
9048 case ISD::SMAX:
9049 case ISD::SMIN:
9050 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9051 return N2.getOpcode() == ISD::POISON ? N2 : N1;
9052 }
9053 }
9054
9055 // Canonicalize an UNDEF to the RHS, even over a constant.
9056 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
9057 if (TLI->isCommutativeBinOp(Opcode)) {
9058 std::swap(N1, N2);
9059 } else {
9060 switch (Opcode) {
9061 case ISD::PTRADD:
9062 case ISD::SUB:
9063 // fold op(undef, non_undef_arg2) -> undef.
9064 return N1;
9066 case ISD::UDIV:
9067 case ISD::SDIV:
9068 case ISD::UREM:
9069 case ISD::SREM:
9070 case ISD::SSUBSAT:
9071 case ISD::USUBSAT:
9072 // fold op(undef, non_undef_arg2) -> 0.
9073 return getConstant(0, DL, VT);
9074 }
9075 }
9076 }
9077
9078 // Fold a bunch of operators when the RHS is undef.
9079 if (N2.getOpcode() == ISD::UNDEF) {
9080 switch (Opcode) {
9081 case ISD::XOR:
9082 if (N1.getOpcode() == ISD::UNDEF)
9083 // Handle undef ^ undef -> 0 special case. This is a common
9084 // idiom (misuse).
9085 return getConstant(0, DL, VT);
9086 [[fallthrough]];
9087 case ISD::ADD:
9088 case ISD::PTRADD:
9089 case ISD::SUB:
9090 // fold op(arg1, undef) -> undef.
9091 return N2;
9092 case ISD::UDIV:
9093 case ISD::SDIV:
9094 case ISD::UREM:
9095 case ISD::SREM:
9096 // fold op(arg1, undef) -> poison.
9097 return getPOISON(VT);
9098 case ISD::MUL:
9099 case ISD::AND:
9100 case ISD::SSUBSAT:
9101 case ISD::USUBSAT:
9102 case ISD::UMIN:
9103 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
9104 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
9105 case ISD::OR:
9106 case ISD::SADDSAT:
9107 case ISD::UADDSAT:
9108 case ISD::UMAX:
9109 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
9110 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
9111 case ISD::SMAX:
9112 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
9113 return N1.getOpcode() == ISD::UNDEF
9114 ? N2
9115 : getConstant(
9117 VT);
9118 case ISD::SMIN:
9119 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
9120 return N1.getOpcode() == ISD::UNDEF
9121 ? N2
9122 : getConstant(
9124 VT);
9125 }
9126 }
9127
9128 // Perform trivial constant folding.
9129 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9130 return SV;
9131
9132 // Memoize this node if possible.
9133 SDNode *N;
9134 SDVTList VTs = getVTList(VT);
9135 SDValue Ops[] = {N1, N2};
9136 if (VT != MVT::Glue) {
9137 SDNodeKey ID(Opcode, VTs, Ops);
9138 FoldingSetInsertToken InsertToken;
9139 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9140 E->intersectFlagsWith(Flags);
9141 return SDValue(E, 0);
9142 }
9143
9144 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9145 N->setFlags(Flags);
9146 createOperands(N, Ops);
9147 CSEMap.insert(N, InsertToken);
9148 } else {
9149 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9150 createOperands(N, Ops);
9151 }
9152
9153 InsertNode(N);
9154 SDValue V = SDValue(N, 0);
9155 NewSDValueDbgMsg(V, "Creating new node: ", this);
9156 return V;
9157}
9158
9159SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9160 SDValue N1, SDValue N2, SDValue N3) {
9161 SDNodeFlags Flags;
9162 if (Inserter)
9163 Flags = Inserter->getFlags();
9164 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9165}
9166
9167SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9168 SDValue N1, SDValue N2, SDValue N3,
9169 const SDNodeFlags Flags) {
9171 N2.getOpcode() != ISD::DELETED_NODE &&
9172 N3.getOpcode() != ISD::DELETED_NODE &&
9173 "Operand is DELETED_NODE!");
9174 // Perform various simplifications.
9175 switch (Opcode) {
9176 case ISD::BUILD_VECTOR: {
9177 // Attempt to simplify BUILD_VECTOR.
9178 SDValue Ops[] = {N1, N2, N3};
9179 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9180 return V;
9181 break;
9182 }
9183 case ISD::CONCAT_VECTORS: {
9184 SDValue Ops[] = {N1, N2, N3};
9185 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9186 return V;
9187 break;
9188 }
9189 case ISD::SETCC: {
9190 assert(VT.isInteger() && "SETCC result type must be an integer!");
9191 assert(N1.getValueType() == N2.getValueType() &&
9192 "SETCC operands must have the same type!");
9193 assert(VT.isVector() == N1.getValueType().isVector() &&
9194 "SETCC type should be vector iff the operand type is vector!");
9195 assert((!VT.isVector() || VT.getVectorElementCount() ==
9197 "SETCC vector element counts must match!");
9198 // Use FoldSetCC to simplify SETCC's.
9199 if (SDValue V =
9200 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9201 return V;
9202 break;
9203 }
9204 case ISD::SELECT:
9205 case ISD::VSELECT:
9206 if (SDValue V = simplifySelect(N1, N2, N3))
9207 return V;
9208 break;
9210 llvm_unreachable("should use getVectorShuffle constructor!");
9212 if (isNullConstant(N3))
9213 return N1;
9214 break;
9216 if (isNullConstant(N3))
9217 return N2;
9218 break;
9220 assert(VT.isVector() && VT == N1.getValueType() &&
9221 "INSERT_VECTOR_ELT vector type mismatch");
9223 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9224 assert((!VT.isFloatingPoint() ||
9225 VT.getVectorElementType() == N2.getValueType()) &&
9226 "INSERT_VECTOR_ELT fp scalar type mismatch");
9227 assert((!VT.isInteger() ||
9229 "INSERT_VECTOR_ELT int scalar size mismatch");
9230
9231 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9232 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9233 // for scalable vectors where we will generate appropriate code to
9234 // deal with out-of-bounds cases correctly.
9235 if (N3C && VT.isFixedLengthVector() &&
9236 N3C->getZExtValue() >= VT.getVectorNumElements())
9237 return getUNDEF(VT);
9238
9239 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9240 if (N3.isUndef())
9241 return getUNDEF(VT);
9242
9243 // If inserting poison, just use the input vector.
9244 if (N2.getOpcode() == ISD::POISON)
9245 return N1;
9246
9247 // Inserting undef into undef/poison is still undef.
9248 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9249 return getUNDEF(VT);
9250
9251 // If the inserted element is an UNDEF, just use the input vector.
9252 // But not if skipping the insert could make the result more poisonous.
9253 if (N2.isUndef()) {
9254 if (N3C && VT.isFixedLengthVector()) {
9255 APInt EltMask =
9256 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9257 if (isGuaranteedNotToBePoison(N1, EltMask))
9258 return N1;
9259 } else if (isGuaranteedNotToBePoison(N1))
9260 return N1;
9261 }
9262 break;
9263 }
9264 case ISD::INSERT_SUBVECTOR: {
9265 // If inserting poison, just use the input vector,
9266 if (N2.getOpcode() == ISD::POISON)
9267 return N1;
9268
9269 // Inserting undef into undef/poison is still undef.
9270 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9271 return getUNDEF(VT);
9272
9273 EVT N2VT = N2.getValueType();
9274 assert(VT == N1.getValueType() &&
9275 "Dest and insert subvector source types must match!");
9276 assert(VT.isVector() && N2VT.isVector() &&
9277 "Insert subvector VTs must be vectors!");
9279 "Insert subvector VTs must have the same element type!");
9280 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9281 "Cannot insert a scalable vector into a fixed length vector!");
9282 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9284 "Insert subvector must be from smaller vector to larger vector!");
9286 "Insert subvector index must be constant");
9287 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9288 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9290 "Insert subvector overflow!");
9292 TLI->getVectorIdxWidth(getDataLayout()) &&
9293 "Constant index for INSERT_SUBVECTOR has an invalid size");
9294
9295 // Trivial insertion.
9296 if (VT == N2VT)
9297 return N2;
9298
9299 // If this is an insert of an extracted vector into an undef/poison vector,
9300 // we can just use the input to the extract. But not if skipping the
9301 // extract+insert could make the result more poisonous.
9302 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9303 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9304 if (N1.getOpcode() == ISD::POISON)
9305 return N2.getOperand(0);
9306 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9307 unsigned LoBit = N3->getAsZExtVal();
9308 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9309 APInt EltMask =
9310 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9311 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9312 return N2.getOperand(0);
9313 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9314 return N2.getOperand(0);
9315 }
9316
9317 // If the inserted subvector is UNDEF, just use the input vector.
9318 // But not if skipping the insert could make the result more poisonous.
9319 if (N2.isUndef()) {
9320 if (VT.isFixedLengthVector()) {
9321 unsigned LoBit = N3->getAsZExtVal();
9322 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9323 APInt EltMask =
9324 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9325 if (isGuaranteedNotToBePoison(N1, EltMask))
9326 return N1;
9327 } else if (isGuaranteedNotToBePoison(N1))
9328 return N1;
9329 }
9330 break;
9331 }
9332 case ISD::BITCAST:
9333 // Fold bit_convert nodes from a type to themselves.
9334 if (N1.getValueType() == VT)
9335 return N1;
9336 break;
9337 case ISD::VECTOR_COMPRESS: {
9338 [[maybe_unused]] EVT VecVT = N1.getValueType();
9339 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9340 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9341 assert(VT == VecVT && "Vector and result type don't match.");
9342 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9343 "All inputs must be vectors.");
9344 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9346 "Vector and mask must have same number of elements.");
9347
9348 if (N1.isUndef() || N2.isUndef())
9349 return N3;
9350
9351 break;
9352 }
9357 [[maybe_unused]] EVT AccVT = N1.getValueType();
9358 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9359 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9360 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9361 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9362 "node to have the same type!");
9363 assert(VT.isVector() && VT == AccVT &&
9364 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9365 "the same type as its result!");
9367 AccVT.getVectorElementCount()) &&
9368 "Expected the element count of the second and third operands of the "
9369 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9370 "element count of the first operand and the result!");
9372 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9373 "node to have an element type which is the same as or smaller than "
9374 "the element type of the first operand and result!");
9375 break;
9376 }
9377 }
9378
9379 // Perform trivial constant folding for arithmetic operators.
9380 switch (Opcode) {
9384 case ISD::FMA:
9385 case ISD::FMAD:
9386 case ISD::SETCC:
9387 case ISD::FSHL:
9388 case ISD::FSHR:
9389 if (SDValue SV =
9390 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9391 return SV;
9392 break;
9393 }
9394
9395 // Memoize node if it doesn't produce a glue result.
9396 SDNode *N;
9397 SDVTList VTs = getVTList(VT);
9398 SDValue Ops[] = {N1, N2, N3};
9399 if (VT != MVT::Glue) {
9400 SDNodeKey ID(Opcode, VTs, Ops);
9401 FoldingSetInsertToken InsertToken;
9402 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9403 E->intersectFlagsWith(Flags);
9404 return SDValue(E, 0);
9405 }
9406
9407 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9408 N->setFlags(Flags);
9409 createOperands(N, Ops);
9410 CSEMap.insert(N, InsertToken);
9411 } else {
9412 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9413 createOperands(N, Ops);
9414 }
9415
9416 InsertNode(N);
9417 SDValue V = SDValue(N, 0);
9418 NewSDValueDbgMsg(V, "Creating new node: ", this);
9419 return V;
9420}
9421
9422SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9423 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9424 const SDNodeFlags Flags) {
9425 SDValue Ops[] = { N1, N2, N3, N4 };
9426 return getNode(Opcode, DL, VT, Ops, Flags);
9427}
9428
9429SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9430 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9431 SDNodeFlags Flags;
9432 if (Inserter)
9433 Flags = Inserter->getFlags();
9434 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9435}
9436
9437SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9438 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9439 SDValue N5, const SDNodeFlags Flags) {
9440 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9441 return getNode(Opcode, DL, VT, Ops, Flags);
9442}
9443
9444SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9445 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9446 SDValue N5) {
9447 SDNodeFlags Flags;
9448 if (Inserter)
9449 Flags = Inserter->getFlags();
9450 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9451}
9452
9453/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9454/// the incoming stack arguments to be loaded from the stack.
9456 SmallVector<SDValue, 8> ArgChains;
9457
9458 // Include the original chain at the beginning of the list. When this is
9459 // used by target LowerCall hooks, this helps legalize find the
9460 // CALLSEQ_BEGIN node.
9461 ArgChains.push_back(Chain);
9462
9463 // Add a chain value for each stack argument.
9464 for (SDNode *U : getEntryNode().getNode()->users())
9465 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9466 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9467 if (FI->getIndex() < 0)
9468 ArgChains.push_back(SDValue(L, 1));
9469
9470 // Build a tokenfactor for all the chains.
9471 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9472}
9473
9474/// getMemsetValue - Vectorized representation of the memset value
9475/// operand.
9477 const SDLoc &dl) {
9478 assert(!Value.isUndef());
9479
9480 unsigned NumBits = VT.getScalarSizeInBits();
9482 assert(C->getAPIntValue().getBitWidth() == 8);
9483 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9484 if (VT.isInteger()) {
9485 bool IsOpaque = VT.getSizeInBits() > 64 ||
9486 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9487 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9488 }
9489 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9490 }
9491
9492 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9493 EVT IntVT = VT.getScalarType();
9494 if (!IntVT.isInteger())
9495 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9496
9497 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9498 if (NumBits > 8) {
9499 // Use a multiplication with 0x010101... to extend the input to the
9500 // required length.
9501 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9502 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9503 DAG.getConstant(Magic, dl, IntVT));
9504 }
9505
9506 if (VT != Value.getValueType() && !VT.isInteger())
9507 Value = DAG.getBitcast(VT.getScalarType(), Value);
9508 if (VT != Value.getValueType())
9509 Value = DAG.getSplatBuildVector(VT, dl, Value);
9510
9511 return Value;
9512}
9513
9514/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9515/// used when a memcpy is turned into a memset when the source is a constant
9516/// string ptr.
9518 const TargetLowering &TLI,
9519 const ConstantDataArraySlice &Slice) {
9520 // Handle vector with all elements zero.
9521 if (Slice.Array == nullptr) {
9522 if (VT.isInteger())
9523 return DAG.getConstant(0, dl, VT);
9524 return DAG.getNode(ISD::BITCAST, dl, VT,
9525 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9526 }
9527
9528 assert(!VT.isVector() && "Can't handle vector type here!");
9529 unsigned NumVTBits = VT.getSizeInBits();
9530 unsigned NumVTBytes = NumVTBits / 8;
9531 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9532
9533 APInt Val(NumVTBits, 0);
9534 if (DAG.getDataLayout().isLittleEndian()) {
9535 for (unsigned i = 0; i != NumBytes; ++i)
9536 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9537 } else {
9538 for (unsigned i = 0; i != NumBytes; ++i)
9539 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9540 }
9541
9542 // If the "cost" of materializing the integer immediate is less than the cost
9543 // of a load, then it is cost effective to turn the load into the immediate.
9544 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9545 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9546 return DAG.getConstant(Val, dl, VT);
9547 return SDValue();
9548}
9549
9551 const SDLoc &DL,
9552 const SDNodeFlags Flags) {
9553 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9554 return getMemBasePlusOffset(Base, Index, DL, Flags);
9555}
9556
9558 const SDLoc &DL,
9559 const SDNodeFlags Flags) {
9560 assert(Offset.getValueType().isInteger());
9561 EVT BasePtrVT = Ptr.getValueType();
9562 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9563 BasePtrVT))
9564 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9565 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9566 SDNodeFlags AddFlags = Flags;
9567 AddFlags.setInBounds(false);
9568 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9569}
9570
9571/// Returns true if memcpy source is constant data.
9573 uint64_t SrcDelta = 0;
9574 GlobalAddressSDNode *G = nullptr;
9575 if (Src.getOpcode() == ISD::GlobalAddress)
9577 else if (Src->isAnyAdd() &&
9578 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9579 Src.getOperand(1).getOpcode() == ISD::Constant) {
9580 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9581 SrcDelta = Src.getConstantOperandVal(1);
9582 }
9583 if (!G)
9584 return false;
9585
9586 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9587 SrcDelta + G->getOffset());
9588}
9589
9591 SelectionDAG &DAG) {
9592 // On Darwin, -Os means optimize for size without hurting performance, so
9593 // only really optimize for size when -Oz (MinSize) is used.
9595 return MF.getFunction().hasMinSize();
9596 return DAG.shouldOptForSize();
9597}
9598
9600 SmallVector<SDValue, 32> &OutChains, unsigned From,
9601 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9602 SmallVector<SDValue, 16> &OutStoreChains) {
9603 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9604 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9605 SmallVector<SDValue, 16> GluedLoadChains;
9606 for (unsigned i = From; i < To; ++i) {
9607 OutChains.push_back(OutLoadChains[i]);
9608 GluedLoadChains.push_back(OutLoadChains[i]);
9609 }
9610
9611 // Chain for all loads.
9612 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9613 GluedLoadChains);
9614
9615 for (unsigned i = From; i < To; ++i) {
9616 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9617 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9618 ST->getBasePtr(), ST->getMemoryVT(),
9619 ST->getMemOperand());
9620 OutChains.push_back(NewStore);
9621 }
9622}
9623
9624static SDValue
9626 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9627 Align SrcAlign, bool isVol, bool AlwaysInline,
9628 MachinePointerInfo DstPtrInfo,
9629 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9630 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9631 const MDNode *SrcMemCacheHint) {
9632 // Turn a memcpy of undef to nop.
9633 // FIXME: We need to honor volatile even is Src is undef.
9634 if (Src.isUndef())
9635 return Chain;
9636
9637 // Expand memcpy to a series of load and store ops if the size operand falls
9638 // below a certain threshold.
9639 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9640 // rather than maybe a humongous number of loads and stores.
9641 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9642 const DataLayout &DL = DAG.getDataLayout();
9643 LLVMContext &C = *DAG.getContext();
9644 std::vector<EVT> MemOps;
9645 bool DstAlignCanChange = false;
9647 MachineFrameInfo &MFI = MF.getFrameInfo();
9648 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9650 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9651 DstAlignCanChange = true;
9652 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9654 // If marked as volatile, perform a copy even when marked as constant.
9655 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9656 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9657 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9658 const MemOp Op = isZeroConstant
9659 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9660 /*IsZeroMemset*/ true, isVol)
9661 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9662 SrcAlign, isVol, CopyFromConstant);
9663 if (!TLI.findOptimalMemOpLowering(
9664 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9665 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9666 return SDValue();
9667
9668 if (DstAlignCanChange) {
9669 Type *Ty = MemOps[0].getTypeForEVT(C);
9670 Align NewDstAlign = DL.getABITypeAlign(Ty);
9671
9672 // Don't promote to an alignment that would require dynamic stack
9673 // realignment which may conflict with optimizations such as tail call
9674 // optimization.
9676 if (!TRI->hasStackRealignment(MF))
9677 if (MaybeAlign StackAlign = DL.getStackAlignment())
9678 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9679
9680 if (NewDstAlign > DstAlign) {
9681 // Give the stack frame object a larger alignment if needed.
9682 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9683 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9684 DstAlign = NewDstAlign;
9685 }
9686 }
9687
9688 // Prepare AAInfo for loads/stores after lowering this memcpy.
9689 AAMDNodes NewAAInfo = AAInfo;
9690 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9691
9692 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9693 bool isConstant =
9694 BatchAA && SrcVal &&
9695 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9696
9697 MachineMemOperand::Flags MMOFlags =
9699 SmallVector<SDValue, 16> OutLoadChains;
9700 SmallVector<SDValue, 16> OutStoreChains;
9701 SmallVector<SDValue, 32> OutChains;
9702 unsigned NumMemOps = MemOps.size();
9703 uint64_t SrcOff = 0, DstOff = 0;
9704 for (unsigned i = 0; i != NumMemOps; ++i) {
9705 EVT VT = MemOps[i];
9706 unsigned VTSize = VT.getSizeInBits() / 8;
9708
9709 if (VTSize > Size) {
9710 // Issuing an unaligned load / store pair that overlaps with the previous
9711 // pair. Adjust the offset accordingly.
9712 assert(i == NumMemOps-1 && i != 0);
9713 SrcOff -= VTSize - Size;
9714 DstOff -= VTSize - Size;
9715 }
9716
9717 if (CopyFromConstant &&
9718 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9719 // It's unlikely a store of a vector immediate can be done in a single
9720 // instruction. It would require a load from a constantpool first.
9721 // We only handle zero vectors here.
9722 // FIXME: Handle other cases where store of vector immediate is done in
9723 // a single instruction.
9724 ConstantDataArraySlice SubSlice;
9725 if (SrcOff < Slice.Length) {
9726 SubSlice = Slice;
9727 SubSlice.move(SrcOff);
9728 } else {
9729 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9730 SubSlice.Array = nullptr;
9731 SubSlice.Offset = 0;
9732 SubSlice.Length = VTSize;
9733 }
9734 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9735 if (Value.getNode()) {
9736 Store = DAG.getStore(
9737 Chain, dl, Value,
9738 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9739 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9740 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9741 OutChains.push_back(Store);
9742 }
9743 }
9744
9745 if (!Store.getNode()) {
9746 // The type might not be legal for the target. This should only happen
9747 // if the type is smaller than a legal type, as on PPC, so the right
9748 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9749 // to Load/Store if NVT==VT.
9750 // FIXME does the case above also need this?
9751 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9752 assert(NVT.bitsGE(VT));
9753
9754 bool isDereferenceable =
9755 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9756 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9757 if (isDereferenceable)
9759 if (isConstant)
9760 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9761
9762 Value = DAG.getExtLoad(
9763 ISD::EXTLOAD, dl, NVT, Chain,
9764 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9765 SrcPtrInfo.getWithOffset(SrcOff), VT,
9766 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9767 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9768 OutLoadChains.push_back(Value.getValue(1));
9769
9770 Store = DAG.getTruncStore(
9771 Chain, dl, Value,
9772 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9773 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9774 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9775 OutStoreChains.push_back(Store);
9776 }
9777 SrcOff += VTSize;
9778 DstOff += VTSize;
9779 Size -= VTSize;
9780 }
9781
9782 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9784 unsigned NumLdStInMemcpy = OutStoreChains.size();
9785
9786 if (NumLdStInMemcpy) {
9787 // It may be that memcpy might be converted to memset if it's memcpy
9788 // of constants. In such a case, we won't have loads and stores, but
9789 // just stores. In the absence of loads, there is nothing to gang up.
9790 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9791 // If target does not care, just leave as it.
9792 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9793 OutChains.push_back(OutLoadChains[i]);
9794 OutChains.push_back(OutStoreChains[i]);
9795 }
9796 } else {
9797 // Ld/St less than/equal limit set by target.
9798 if (NumLdStInMemcpy <= GluedLdStLimit) {
9799 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9800 NumLdStInMemcpy, OutLoadChains,
9801 OutStoreChains);
9802 } else {
9803 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9804 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9805 unsigned GlueIter = 0;
9806
9807 // Residual ld/st.
9808 if (RemainingLdStInMemcpy) {
9810 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9811 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9812 }
9813
9814 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9815 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9816 GlueIter - GluedLdStLimit;
9817 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9818 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9819 OutLoadChains, OutStoreChains);
9820 GlueIter += GluedLdStLimit;
9821 }
9822 }
9823 }
9824 }
9825 return DAG.getTokenFactor(dl, OutChains);
9826}
9827
9829 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9830 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9831 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9832 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9833 // Turn a memmove of undef to nop.
9834 // FIXME: We need to honor volatile even is Src is undef.
9835 if (Src.isUndef())
9836 return Chain;
9837
9838 // Expand memmove to a series of load and store ops if the size operand falls
9839 // below a certain threshold.
9840 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9841 const DataLayout &DL = DAG.getDataLayout();
9842 LLVMContext &C = *DAG.getContext();
9843 std::vector<EVT> MemOps;
9844 bool DstAlignCanChange = false;
9846 MachineFrameInfo &MFI = MF.getFrameInfo();
9847 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9849 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9850 DstAlignCanChange = true;
9851 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9852 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9853 if (!TLI.findOptimalMemOpLowering(
9854 C, MemOps, Limit,
9855 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9856 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9857 MF.getFunction().getAttributes(), nullptr))
9858 return SDValue();
9859
9860 if (DstAlignCanChange) {
9861 Type *Ty = MemOps[0].getTypeForEVT(C);
9862 Align NewDstAlign = DL.getABITypeAlign(Ty);
9863
9864 // Don't promote to an alignment that would require dynamic stack
9865 // realignment which may conflict with optimizations such as tail call
9866 // optimization.
9868 if (!TRI->hasStackRealignment(MF))
9869 if (MaybeAlign StackAlign = DL.getStackAlignment())
9870 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9871
9872 if (NewDstAlign > DstAlign) {
9873 // Give the stack frame object a larger alignment if needed.
9874 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9875 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9876 DstAlign = NewDstAlign;
9877 }
9878 }
9879
9880 // Prepare AAInfo for loads/stores after lowering this memmove.
9881 AAMDNodes NewAAInfo = AAInfo;
9882 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9883
9884 MachineMemOperand::Flags MMOFlags =
9886 uint64_t SrcOff = 0;
9887 SmallVector<SDValue, 8> LoadValues;
9888 SmallVector<SDValue, 8> LoadChains;
9889 SmallVector<SDValue, 8> OutChains;
9890 unsigned NumMemOps = MemOps.size();
9891 for (unsigned i = 0; i < NumMemOps; i++) {
9892 EVT VT = MemOps[i];
9893 unsigned VTSize = VT.getSizeInBits() / 8;
9894 SDValue Value;
9895 bool IsOverlapping = false;
9896
9897 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9898 // Issuing an unaligned load / store pair that overlaps with the previous
9899 // pair. Adjust the offset accordingly.
9900 SrcOff = Size - VTSize;
9901 IsOverlapping = true;
9902 }
9903
9904 // Calculate the actual alignment at the current offset. The alignment at
9905 // SrcOff may be lower than the base alignment, especially when using
9906 // overlapping loads.
9907 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9908 if (IsOverlapping) {
9909 // Verify that the target allows misaligned memory accesses at the
9910 // adjusted offset when using overlapping loads.
9911 unsigned Fast;
9912 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9913 SrcAlignAtOffset, MMOFlags,
9914 &Fast) ||
9915 !Fast) {
9916 // This should have been caught by findOptimalMemOpLowering, but verify
9917 // here for safety.
9918 return SDValue();
9919 }
9920 }
9921
9922 bool isDereferenceable =
9923 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9924 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9925 if (isDereferenceable)
9927 Value =
9928 DAG.getLoad(VT, dl, Chain,
9929 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9930 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9931 SrcMMOFlags, NewAAInfo);
9932 LoadValues.push_back(Value);
9933 LoadChains.push_back(Value.getValue(1));
9934 SrcOff += VTSize;
9935 }
9936 Chain = DAG.getTokenFactor(dl, LoadChains);
9937 OutChains.clear();
9938 uint64_t DstOff = 0;
9939 for (unsigned i = 0; i < NumMemOps; i++) {
9940 EVT VT = MemOps[i];
9941 unsigned VTSize = VT.getSizeInBits() / 8;
9942 SDValue Store;
9943 bool IsOverlapping = false;
9944
9945 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9946 // Issuing an unaligned load / store pair that overlaps with the previous
9947 // pair. Adjust the offset accordingly.
9948 DstOff = Size - VTSize;
9949 IsOverlapping = true;
9950 }
9951
9952 // Calculate the actual alignment at the current offset. The alignment at
9953 // DstOff may be lower than the base alignment, especially when using
9954 // overlapping stores.
9955 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9956 if (IsOverlapping) {
9957 // Verify that the target allows misaligned memory accesses at the
9958 // adjusted offset when using overlapping stores.
9959 unsigned Fast;
9960 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9961 DstAlignAtOffset, MMOFlags,
9962 &Fast) ||
9963 !Fast) {
9964 // This should have been caught by findOptimalMemOpLowering, but verify
9965 // here for safety.
9966 return SDValue();
9967 }
9968 }
9969 Store = DAG.getStore(
9970 Chain, dl, LoadValues[i],
9971 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9972 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9973 NewAAInfo);
9974 OutChains.push_back(Store);
9975 DstOff += VTSize;
9976 }
9977
9978 return DAG.getTokenFactor(dl, OutChains);
9979}
9980
9981/// Lower the call to 'memset' intrinsic function into a series of store
9982/// operations.
9983///
9984/// \param DAG Selection DAG where lowered code is placed.
9985/// \param dl Link to corresponding IR location.
9986/// \param Chain Control flow dependency.
9987/// \param Dst Pointer to destination memory location.
9988/// \param Src Value of byte to write into the memory.
9989/// \param Size Number of bytes to write.
9990/// \param Alignment Alignment of the destination in bytes.
9991/// \param isVol True if destination is volatile.
9992/// \param AlwaysInline Makes sure no function call is generated.
9993/// \param DstPtrInfo IR information on the memory pointer.
9994/// \returns New head in the control flow, if lowering was successful, empty
9995/// SDValue otherwise.
9996///
9997/// The function tries to replace 'llvm.memset' intrinsic with several store
9998/// operations and value calculation code. This is usually profitable for small
9999/// memory size or when the semantic requires inlining.
10001 SDValue Chain, SDValue Dst, SDValue Src,
10002 uint64_t Size, Align Alignment, bool isVol,
10003 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
10004 const AAMDNodes &AAInfo) {
10005 // Turn a memset of undef to nop.
10006 // FIXME: We need to honor volatile even is Src is undef.
10007 if (Src.isUndef())
10008 return Chain;
10009
10010 // Expand memset to a series of load/store ops if the size operand
10011 // falls below a certain threshold.
10012 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10013 std::vector<EVT> MemOps;
10014 bool DstAlignCanChange = false;
10015 LLVMContext &C = *DAG.getContext();
10017 MachineFrameInfo &MFI = MF.getFrameInfo();
10018 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10020 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10021 DstAlignCanChange = true;
10022 bool IsZeroVal = isNullConstant(Src);
10023 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
10024
10025 EVT LargestVT;
10026 if (!TLI.findOptimalMemOpLowering(
10027 C, MemOps, Limit,
10028 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
10029 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
10030 &LargestVT))
10031 return SDValue();
10032
10033 if (DstAlignCanChange) {
10034 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
10035 const DataLayout &DL = DAG.getDataLayout();
10036 Align NewAlign = DL.getABITypeAlign(Ty);
10037
10038 // Don't promote to an alignment that would require dynamic stack
10039 // realignment which may conflict with optimizations such as tail call
10040 // optimization.
10042 if (!TRI->hasStackRealignment(MF))
10043 if (MaybeAlign StackAlign = DL.getStackAlignment())
10044 NewAlign = std::min(NewAlign, *StackAlign);
10045
10046 if (NewAlign > Alignment) {
10047 // Give the stack frame object a larger alignment if needed.
10048 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
10049 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
10050 Alignment = NewAlign;
10051 }
10052 }
10053
10054 SmallVector<SDValue, 8> OutChains;
10055 uint64_t DstOff = 0;
10056 unsigned NumMemOps = MemOps.size();
10057
10058 // Find the largest store and generate the bit pattern for it.
10059 // If target didn't set LargestVT, compute it from MemOps.
10060 if (!LargestVT.isSimple()) {
10061 LargestVT = MemOps[0];
10062 for (unsigned i = 1; i < NumMemOps; i++)
10063 if (MemOps[i].bitsGT(LargestVT))
10064 LargestVT = MemOps[i];
10065 }
10066 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
10067
10068 // Prepare AAInfo for loads/stores after lowering this memset.
10069 AAMDNodes NewAAInfo = AAInfo;
10070 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10071
10072 for (unsigned i = 0; i < NumMemOps; i++) {
10073 EVT VT = MemOps[i];
10074 unsigned VTSize = VT.getSizeInBits() / 8;
10075 // The target should specify store types that exactly cover the memset size
10076 // (with the last store potentially being oversized for overlapping stores).
10077 assert(Size > 0 && "Target specified more stores than needed in "
10078 "findOptimalMemOpLowering");
10079 if (VTSize > Size) {
10080 // Issuing an unaligned load / store pair that overlaps with the previous
10081 // pair. Adjust the offset accordingly.
10082 assert(i == NumMemOps-1 && i != 0);
10083 DstOff -= VTSize - Size;
10084 }
10085
10086 // If this store is smaller than the largest store see whether we can get
10087 // the smaller value for free with a truncate or extract vector element and
10088 // then store.
10089 SDValue Value = MemSetValue;
10090 if (VT.bitsLT(LargestVT)) {
10091 unsigned Index;
10092 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
10093 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
10094 if (!LargestVT.isVector() && !VT.isVector() &&
10095 TLI.isTruncateFree(LargestVT, VT))
10096 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
10097 else if (LargestVT.isVector() && !VT.isVector() &&
10099 LargestVT.getTypeForEVT(*DAG.getContext()),
10100 VT.getSizeInBits(), Index) &&
10101 TLI.isTypeLegal(SVT) &&
10102 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
10103 // Target which can combine store(extractelement VectorTy, Idx) can get
10104 // the smaller value for free.
10105 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
10106 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
10107 } else
10108 Value = getMemsetValue(Src, VT, DAG, dl);
10109 }
10110 assert(Value.getValueType() == VT && "Value with wrong type.");
10111 SDValue Store = DAG.getStore(
10112 Chain, dl, Value,
10113 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10114 DstPtrInfo.getWithOffset(DstOff), Alignment,
10116 NewAAInfo);
10117 OutChains.push_back(Store);
10118 DstOff += VT.getSizeInBits() / 8;
10119 // For oversized overlapping stores, only subtract the remaining bytes.
10120 // For normal stores, subtract the full store size.
10121 if (VTSize > Size) {
10122 Size = 0;
10123 } else {
10124 Size -= VTSize;
10125 }
10126 }
10127
10128 // After processing all stores, Size should be exactly 0. Any remaining bytes
10129 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10130 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10131 "stores that exactly cover the memset size");
10132
10133 return DAG.getTokenFactor(dl, OutChains);
10134}
10135
10137 const DataLayout &DL, unsigned AS) {
10138 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10139 // pointer operands can be losslessly bitcasted to pointers of address space 0
10140 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(DL, AS, 0)) {
10141 report_fatal_error("cannot lower memory intrinsic in address space " +
10142 Twine(AS));
10143 }
10144}
10145
10146/// The length of a memory intrinsic (e.g. number of bytes to copy) is unsigned
10147/// and may have any integer type. We zero-extend or truncate it to the pointer
10148/// type of the narrower address space being accessed.
10150 SDValue Size, unsigned DstAS,
10151 unsigned SrcAS) {
10152 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10153 MVT DstVT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
10154 MVT SrcVT = TLI.getPointerTy(DAG.getDataLayout(), SrcAS);
10155 return DAG.getZExtOrTrunc(Size, dl, DstVT.bitsLT(SrcVT) ? DstVT : SrcVT);
10156}
10157
10159 const SelectionDAG *SelDAG,
10160 bool AllowReturnsFirstArg) {
10161 if (!CI || !CI->isTailCall())
10162 return false;
10163 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10164 // helper symbol we lower to.
10165 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10166 AllowReturnsFirstArg &&
10168}
10169
10170static std::pair<SDValue, SDValue>
10173 const CallInst *CI, RTLIB::Libcall Call,
10174 SelectionDAG *DAG, const TargetLowering *TLI) {
10175 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10176
10177 if (LCImpl == RTLIB::Unsupported)
10178 return {};
10179
10181 bool IsTailCall =
10182 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10183 // Lowering doesn't support tail calling inside a function with
10184 // a swifterror argument yet.
10185 !DAG->hasSwiftErrorArg();
10186 SDValue Callee =
10187 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10188
10189 CLI.setDebugLoc(dl)
10190 .setChain(Chain)
10192 CI->getType(), Callee, std::move(Args))
10193 .setTailCall(IsTailCall);
10194
10195 return TLI->LowerCallTo(CLI);
10196}
10197
10198std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10199 const SDLoc &dl, SDValue S1,
10200 SDValue S2,
10201 const CallInst *CI) {
10203 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10204 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10205 RTLIB::STRCMP, this, TLI);
10206}
10207
10208std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10209 const SDLoc &dl, SDValue S1,
10210 SDValue S2,
10211 const CallInst *CI) {
10213 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10214 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10215 RTLIB::STRSTR, this, TLI);
10216}
10217
10218std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10219 const SDLoc &dl,
10220 SDValue Dst, SDValue Src,
10222 const CallInst *CI) {
10224
10226 {Dst, PT},
10227 {Src, PT},
10230 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10231 RTLIB::MEMCCPY, this, TLI);
10232}
10233
10234std::pair<SDValue, SDValue>
10236 SDValue Mem1, SDValue Size, const CallInst *CI) {
10239 {Mem0, PT},
10240 {Mem1, PT},
10242 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10243 RTLIB::MEMCMP, this, TLI);
10244}
10245
10246std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10247 const SDLoc &dl,
10248 SDValue Dst, SDValue Src,
10249 const CallInst *CI) {
10251 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10252 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10253 RTLIB::STRCPY, this, TLI);
10254}
10255
10256std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10257 const SDLoc &dl,
10258 SDValue Src,
10259 const CallInst *CI) {
10260 // Emit a library call.
10263 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10264 RTLIB::STRLEN, this, TLI);
10265}
10266
10268 return TLI->supportSwiftError() &&
10269 MF->getFunction().getAttributes().hasAttrSomewhere(
10270 Attribute::SwiftError);
10271}
10272
10274 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10275 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10276 const CallInst *CI, std::optional<bool> OverrideTailCall,
10277 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10278 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10279 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10280 SrcPtrInfo.getAddrSpace());
10281 // Check to see if we should lower the memcpy to loads and stores first.
10282 // For cases within the target-specified limits, this is the best choice.
10283 const MDNode *DstMemCacheHint =
10284 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10285 const MDNode *SrcMemCacheHint =
10286 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10287
10289 if (ConstantSize) {
10290 // Memcpy with size zero? Just return the original chain.
10291 if (ConstantSize->isZero())
10292 return Chain;
10293
10295 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10296 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10297 DstMemCacheHint, SrcMemCacheHint);
10298 if (Result.getNode())
10299 return Result;
10300 }
10301
10302 // Then check to see if we should lower the memcpy with target-specific
10303 // code. If the target chooses to do this, this is the next best.
10304 if (TSI) {
10305 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10306 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10307 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10308 if (Result.getNode())
10309 return Result;
10310 }
10311
10312 // If we really need inline code and the target declined to provide it,
10313 // use a (potentially long) sequence of loads and stores.
10314 if (AlwaysInline) {
10315 assert(ConstantSize && "AlwaysInline requires a constant size!");
10317 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10318 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10319 DstMemCacheHint, SrcMemCacheHint);
10320 }
10321
10323 DstPtrInfo.getAddrSpace());
10325 SrcPtrInfo.getAddrSpace());
10326
10327 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10328 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10329 // respect volatile, so they may do things like read or write memory
10330 // beyond the given memory regions. But fixing this isn't easy, and most
10331 // people don't care.
10332
10333 // Emit a library call.
10336 Args.emplace_back(Dst, PtrTy);
10337 Args.emplace_back(Src, PtrTy);
10338 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10339 // FIXME: pass in SDLoc
10341 bool IsTailCall = false;
10342 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10343
10344 if (OverrideTailCall.has_value()) {
10345 IsTailCall = *OverrideTailCall;
10346 } else {
10347 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10348 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10349 }
10350 // Lowering doesn't support tail calling inside a function with a
10351 // swifterror argument yet.
10352 IsTailCall &= !hasSwiftErrorArg();
10353
10354 CLI.setDebugLoc(dl)
10355 .setChain(Chain)
10356 .setLibCallee(
10357 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10358 Dst.getValueType().getTypeForEVT(*getContext()),
10359 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10360 std::move(Args))
10362 .setTailCall(IsTailCall);
10363
10364 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10365 return CallResult.second;
10366}
10367
10370 const Module &M = *DAG->getMachineFunction().getFunction().getParent();
10371 Type *SizeTTy = DAG->getLibInfo().getSizeTType(M);
10373 DAG->getZExtOrTrunc(Size, dl, MVT::getVT(SizeTTy)), SizeTTy);
10374}
10375
10377 SDValue Dst, SDValue Src, SDValue Size,
10378 Type *SizeTy, unsigned ElemSz,
10379 bool isTailCall,
10380 MachinePointerInfo DstPtrInfo,
10381 MachinePointerInfo SrcPtrInfo) {
10382 // Lowering doesn't support tail calling inside a function with a
10383 // swifterror argument yet.
10384 isTailCall &= !hasSwiftErrorArg();
10385
10386 // Emit a library call.
10389 Args.emplace_back(Dst, ArgTy);
10390 Args.emplace_back(Src, ArgTy);
10391 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10392
10393 RTLIB::Libcall LibraryCall =
10395 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10396 if (LibcallImpl == RTLIB::Unsupported)
10397 report_fatal_error("Unsupported element size");
10398
10400 CLI.setDebugLoc(dl)
10401 .setChain(Chain)
10402 .setLibCallee(
10403 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10405 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10406 std::move(Args))
10408 .setTailCall(isTailCall);
10409
10410 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10411 return CallResult.second;
10412}
10413
10415 SDValue Src, SDValue Size, Align DstAlign,
10416 Align SrcAlign, bool isVol, const CallInst *CI,
10417 std::optional<bool> OverrideTailCall,
10418 MachinePointerInfo DstPtrInfo,
10419 MachinePointerInfo SrcPtrInfo,
10420 const AAMDNodes &AAInfo,
10421 BatchAAResults *BatchAA) {
10422 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10423 SrcPtrInfo.getAddrSpace());
10424 // Check to see if we should lower the memmove to loads and stores first.
10425 // For cases within the target-specified limits, this is the best choice.
10427 if (ConstantSize) {
10428 // Memmove with size zero? Just return the original chain.
10429 if (ConstantSize->isZero())
10430 return Chain;
10431
10433 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10434 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10435 if (Result.getNode())
10436 return Result;
10437 }
10438
10439 // Then check to see if we should lower the memmove with target-specific
10440 // code. If the target chooses to do this, this is the next best.
10441 if (TSI) {
10442 SDValue Result = TSI->EmitTargetCodeForMemmove(
10443 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10444 SrcPtrInfo);
10445 if (Result.getNode())
10446 return Result;
10447 }
10448
10450 DstPtrInfo.getAddrSpace());
10452 SrcPtrInfo.getAddrSpace());
10453
10454 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10455 // not be safe. See memcpy above for more details.
10456
10457 // Emit a library call.
10460 Args.emplace_back(Dst, PtrTy);
10461 Args.emplace_back(Src, PtrTy);
10462 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10463 // FIXME: pass in SDLoc
10465
10466 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10467
10468 bool IsTailCall = false;
10469 if (OverrideTailCall.has_value()) {
10470 IsTailCall = *OverrideTailCall;
10471 } else {
10472 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10473 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10474 }
10475 // Lowering doesn't support tail calling inside a function with a
10476 // swifterror argument yet.
10477 IsTailCall &= !hasSwiftErrorArg();
10478
10479 CLI.setDebugLoc(dl)
10480 .setChain(Chain)
10481 .setLibCallee(
10482 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10483 Dst.getValueType().getTypeForEVT(*getContext()),
10484 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10485 std::move(Args))
10487 .setTailCall(IsTailCall);
10488
10489 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10490 return CallResult.second;
10491}
10492
10494 SDValue Dst, SDValue Src, SDValue Size,
10495 Type *SizeTy, unsigned ElemSz,
10496 bool isTailCall,
10497 MachinePointerInfo DstPtrInfo,
10498 MachinePointerInfo SrcPtrInfo) {
10499 // Lowering doesn't support tail calling inside a function with a
10500 // swifterror argument yet.
10501 isTailCall &= !hasSwiftErrorArg();
10502
10503 // Emit a library call.
10506 Args.emplace_back(Dst, IntPtrTy);
10507 Args.emplace_back(Src, IntPtrTy);
10508 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10509
10510 RTLIB::Libcall LibraryCall =
10512 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10513 if (LibcallImpl == RTLIB::Unsupported)
10514 report_fatal_error("Unsupported element size");
10515
10517 CLI.setDebugLoc(dl)
10518 .setChain(Chain)
10519 .setLibCallee(
10520 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10522 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10523 std::move(Args))
10525 .setTailCall(isTailCall);
10526
10527 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10528 return CallResult.second;
10529}
10530
10532 SDValue Src, SDValue Size, Align Alignment,
10533 bool isVol, bool AlwaysInline,
10534 const CallInst *CI,
10535 MachinePointerInfo DstPtrInfo,
10536 const AAMDNodes &AAInfo) {
10537 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10538 DstPtrInfo.getAddrSpace());
10539 // Check to see if we should lower the memset to stores first.
10540 // For cases within the target-specified limits, this is the best choice.
10542 if (ConstantSize) {
10543 // Memset with size zero? Just return the original chain.
10544 if (ConstantSize->isZero())
10545 return Chain;
10546
10547 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10548 ConstantSize->getZExtValue(), Alignment,
10549 isVol, false, DstPtrInfo, AAInfo);
10550
10551 if (Result.getNode())
10552 return Result;
10553 }
10554
10555 // Then check to see if we should lower the memset with target-specific
10556 // code. If the target chooses to do this, this is the next best.
10557 if (TSI) {
10558 SDValue Result = TSI->EmitTargetCodeForMemset(
10559 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10560 if (Result.getNode())
10561 return Result;
10562 }
10563
10564 // If we really need inline code and the target declined to provide it,
10565 // use a (potentially long) sequence of loads and stores.
10566 if (AlwaysInline) {
10567 assert(ConstantSize && "AlwaysInline requires a constant size!");
10568 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10569 ConstantSize->getZExtValue(), Alignment,
10570 isVol, true, DstPtrInfo, AAInfo);
10571 assert(Result &&
10572 "getMemsetStores must return a valid sequence when AlwaysInline");
10573 return Result;
10574 }
10575
10577 DstPtrInfo.getAddrSpace());
10578
10579 // Emit a library call.
10580 auto &Ctx = *getContext();
10581 const auto& DL = getDataLayout();
10582
10584 // FIXME: pass in SDLoc
10585 CLI.setDebugLoc(dl).setChain(Chain);
10586
10587 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10588 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10589
10590 // If zeroing out and bzero is present, use it.
10591 if (UseBZero) {
10593 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10594 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10595 CLI.setLibCallee(
10596 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10597 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10598 } else {
10599 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10600
10601 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10603 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10604 Args.emplace_back(getAnyExtOrTrunc(Src, dl, IntVT),
10605 Type::getIntNTy(Ctx, LibInfo->getIntSize()),
10606 LibInfo->getExtAttrForI32Param());
10607 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10608
10609 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10610 Dst.getValueType().getTypeForEVT(Ctx),
10611 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10612 std::move(Args));
10613 }
10614
10615 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10616 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10617
10618 // If we're going to use bzero, make sure not to tail call unless the
10619 // subsequent return doesn't need a value, as bzero doesn't return the first
10620 // arg unlike memset.
10621 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10622 bool IsTailCall = CI && CI->isTailCall() &&
10624 ReturnsFirstArg && LowersToMemset) &&
10625 // Lowering doesn't support tail calling inside a function
10626 // with a swifterror argument yet.
10628 CLI.setDiscardResult().setTailCall(IsTailCall);
10629
10630 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10631 return CallResult.second;
10632}
10633
10636 Type *SizeTy, unsigned ElemSz,
10637 bool isTailCall,
10638 MachinePointerInfo DstPtrInfo) {
10639 // Lowering doesn't support tail calling inside a function with a
10640 // swifterror argument yet.
10641 isTailCall &= !hasSwiftErrorArg();
10642
10643 // Emit a library call.
10644 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10646 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10647 Args.emplace_back(getAnyExtOrTrunc(Value, dl, IntVT),
10648 Type::getIntNTy(*getContext(), LibInfo->getIntSize()),
10649 LibInfo->getExtAttrForI32Param());
10650 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10651
10652 RTLIB::Libcall LibraryCall =
10654 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10655 if (LibcallImpl == RTLIB::Unsupported)
10656 report_fatal_error("Unsupported element size");
10657
10659 CLI.setDebugLoc(dl)
10660 .setChain(Chain)
10661 .setLibCallee(
10662 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10664 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10665 std::move(Args))
10667 .setTailCall(isTailCall);
10668
10669 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10670 return CallResult.second;
10671}
10672
10673SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10675 MachineMemOperand *MMO,
10676 ISD::LoadExtType ExtType) {
10677 SDNodeKey ID(Opcode, VTList, Ops);
10678 ID.AddInteger(MemVT.getRawBits());
10679 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10680 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10681 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10682 ID.AddInteger(MMO->getFlags());
10683 FoldingSetInsertToken InsertToken;
10684 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10685 E->refineAlignment(MMO);
10686 E->refineMMOMetadata(MMO);
10687 return SDValue(E, 0);
10688 }
10689
10690 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10691 VTList, MemVT, MMO, ExtType);
10692 createOperands(N, Ops);
10693
10694 CSEMap.insert(N, InsertToken);
10695 InsertNode(N);
10696 SDValue V(N, 0);
10697 NewSDValueDbgMsg(V, "Creating new node: ", this);
10698 return V;
10699}
10700
10702 EVT MemVT, SDVTList VTs, SDValue Chain,
10703 SDValue Ptr, SDValue Cmp, SDValue Swp,
10704 MachineMemOperand *MMO) {
10705 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10707 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10708
10709 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10710 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10711}
10712
10713SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10714 SDValue Chain, SDValue Ptr, SDValue Val,
10715 MachineMemOperand *MMO) {
10716 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10717 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10718 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10719 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10720 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10721 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10722 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10723 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10724 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10725 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10726 Opcode == ISD::ATOMIC_LOAD_FMINIMUMNUM ||
10727 Opcode == ISD::ATOMIC_LOAD_FMAXIMUMNUM ||
10728 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10729 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10730 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10731 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10732 Opcode == ISD::ATOMIC_STORE) &&
10733 "Invalid Atomic Op");
10734
10735 EVT VT = Val.getValueType();
10736
10737 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10738 getVTList(VT, MVT::Other);
10739 SDValue Ops[] = {Chain, Ptr, Val};
10740 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10741}
10742
10744 EVT MemVT, EVT VT, SDValue Chain,
10745 SDValue Ptr, MachineMemOperand *MMO) {
10746 SDVTList VTs = getVTList(VT, MVT::Other);
10747 SDValue Ops[] = {Chain, Ptr};
10748 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10749}
10750
10751/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10753 if (Ops.size() == 1)
10754 return Ops[0];
10755
10757 VTs.reserve(Ops.size());
10758 for (const SDValue &Op : Ops)
10759 VTs.push_back(Op.getValueType());
10760 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10761}
10762
10764 SDValue Chain, const SDLoc &dl) {
10765 SmallVector<SDValue, 4> RetValues;
10766 RetValues.reserve(ResultTypes.size());
10767 for (EVT VT : ResultTypes)
10768 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10769 return getMergeValues(RetValues, dl);
10770}
10771
10773 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10774 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10776 const AAMDNodes &AAInfo) {
10777 if (Size.hasValue() && !Size.getValue())
10779
10781 MachineMemOperand *MMO =
10782 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10783
10784 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10785}
10786
10788 SDVTList VTList,
10789 ArrayRef<SDValue> Ops, EVT MemVT,
10790 MachineMemOperand *MMO) {
10791 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10792}
10793
10795 SDVTList VTList,
10796 ArrayRef<SDValue> Ops, EVT MemVT,
10798 assert(!MMOs.empty() && "Must have at least one MMO");
10799 assert(
10800 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10801 Opcode == ISD::PREFETCH ||
10802 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10803 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10804 "Opcode is not a memory-accessing opcode!");
10805
10807 if (MMOs.size() == 1) {
10808 MemRefs = MMOs[0];
10809 } else {
10810 // Allocate: [size_t count][MMO*][MMO*]...
10811 size_t AllocSize =
10812 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10813 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10814 size_t *CountPtr = static_cast<size_t *>(Buffer);
10815 *CountPtr = MMOs.size();
10816 MachineMemOperand **Array =
10817 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10818 llvm::copy(MMOs, Array);
10819 MemRefs = Array;
10820 }
10821
10822 // Memoize the node unless it returns a glue result.
10824 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10825 SDNodeKey ID(Opcode, VTList, Ops);
10826 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10827 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10828 ID.AddInteger(MemVT.getRawBits());
10829 for (const MachineMemOperand *MMO : MMOs) {
10830 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10831 ID.AddInteger(MMO->getFlags());
10832 }
10833 FoldingSetInsertToken InsertToken;
10834 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10835 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10836 return SDValue(E, 0);
10837 }
10838
10839 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10840 VTList, MemVT, MemRefs);
10841 createOperands(N, Ops);
10842 CSEMap.insert(N, InsertToken);
10843 } else {
10844 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10845 VTList, MemVT, MemRefs);
10846 createOperands(N, Ops);
10847 }
10848 InsertNode(N);
10849 SDValue V(N, 0);
10850 NewSDValueDbgMsg(V, "Creating new node: ", this);
10851 return V;
10852}
10853
10855 SDValue Chain, int FrameIndex) {
10856 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10857 const auto VTs = getVTList(MVT::Other);
10858 SDValue Ops[2] = {
10859 Chain,
10860 getFrameIndex(FrameIndex,
10861 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10862 true)};
10863
10864 SDNodeKey ID(Opcode, VTs, Ops);
10865 FoldingSetInsertToken InsertToken;
10866 if (SDNode *E = lookupNode(ID, dl, InsertToken))
10867 return SDValue(E, 0);
10868
10869 LifetimeSDNode *N =
10870 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10871 createOperands(N, Ops);
10872 CSEMap.insert(N, InsertToken);
10873 InsertNode(N);
10874 SDValue V(N, 0);
10875 NewSDValueDbgMsg(V, "Creating new node: ", this);
10876 return V;
10877}
10878
10880 uint64_t Guid, uint64_t Index,
10881 uint32_t Attr) {
10882 const unsigned Opcode = ISD::PSEUDO_PROBE;
10883 const auto VTs = getVTList(MVT::Other);
10884 SDValue Ops[] = {Chain};
10885 SDNodeKey ID(Opcode, VTs, Ops);
10886 ID.AddInteger(Guid);
10887 ID.AddInteger(Index);
10888 ID.AddInteger(Attr);
10889 FoldingSetInsertToken InsertToken;
10890 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
10891 return SDValue(E, 0);
10892
10893 auto *N = newSDNode<PseudoProbeSDNode>(
10894 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10895 createOperands(N, Ops);
10896 CSEMap.insert(N, InsertToken);
10897 InsertNode(N);
10898 SDValue V(N, 0);
10899 NewSDValueDbgMsg(V, "Creating new node: ", this);
10900 return V;
10901}
10902
10903/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10904/// MachinePointerInfo record from it. This is particularly useful because the
10905/// code generator has many cases where it doesn't bother passing in a
10906/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10908 SelectionDAG &DAG, SDValue Ptr,
10909 int64_t Offset = 0) {
10910 // If this is FI+Offset, we can model it.
10911 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10913 FI->getIndex(), Offset);
10914
10915 // If this is (FI+Offset1)+Offset2, we can model it.
10916 if (Ptr.getOpcode() != ISD::ADD ||
10919 return Info;
10920
10921 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10923 DAG.getMachineFunction(), FI,
10924 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10925}
10926
10927/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10928/// MachinePointerInfo record from it. This is particularly useful because the
10929/// code generator has many cases where it doesn't bother passing in a
10930/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10932 SelectionDAG &DAG, SDValue Ptr,
10933 SDValue OffsetOp) {
10934 // If the 'Offset' value isn't a constant, we can't handle this.
10936 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10937 if (OffsetOp.isUndef())
10938 return InferPointerInfo(Info, DAG, Ptr);
10939 return Info;
10940}
10941
10943 EVT VT, const SDLoc &dl, SDValue Chain,
10944 SDValue Ptr, SDValue Offset,
10945 MachinePointerInfo PtrInfo, EVT MemVT,
10946 Align Alignment,
10947 MachineMemOperand::Flags MMOFlags,
10948 const MMOMetadata &Metadata) {
10949 assert(Chain.getValueType() == MVT::Other &&
10950 "Invalid chain type");
10951
10952 MMOFlags |= MachineMemOperand::MOLoad;
10953 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10954 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10955 // clients.
10956 if (PtrInfo.V.isNull())
10957 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10958
10959 TypeSize Size = MemVT.getStoreSize();
10961 MachineMemOperand *MMO =
10962 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10963 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10964}
10965
10967 EVT VT, const SDLoc &dl, SDValue Chain,
10968 SDValue Ptr, SDValue Offset, EVT MemVT,
10969 MachineMemOperand *MMO) {
10970 if (VT == MemVT) {
10971 ExtType = ISD::NON_EXTLOAD;
10972 } else if (ExtType == ISD::NON_EXTLOAD) {
10973 assert(VT == MemVT && "Non-extending load from different memory type!");
10974 } else {
10975 // Extending load.
10976 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10977 "Should only be an extending load, not truncating!");
10978 assert(VT.isInteger() == MemVT.isInteger() &&
10979 "Cannot convert from FP to Int or Int -> FP!");
10980 assert(VT.isVector() == MemVT.isVector() &&
10981 "Cannot use an ext load to convert to or from a vector!");
10982 assert((!VT.isVector() ||
10984 "Cannot use an ext load to change the number of vector elements!");
10985 }
10986
10987 assert((!MMO->getRanges() ||
10989 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10990 MemVT.isInteger())) &&
10991 "Range metadata and load type must match!");
10992
10993 bool Indexed = AM != ISD::UNINDEXED;
10994 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10995 "Unindexed load with an offset!");
10996
10997 SDVTList VTs = Indexed ?
10998 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10999 SDValue Ops[] = { Chain, Ptr, Offset };
11000 SDNodeKey ID(ISD::LOAD, VTs, Ops);
11001 ID.AddInteger(MemVT.getRawBits());
11002 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
11003 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
11004 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11005 ID.AddInteger(MMO->getFlags());
11006 FoldingSetInsertToken InsertToken;
11007 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11008 E->refineAlignment(MMO);
11009 E->refineMMOMetadata(MMO);
11010 return SDValue(E, 0);
11011 }
11012 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11013 ExtType, MemVT, MMO);
11014 createOperands(N, Ops);
11015
11016 CSEMap.insert(N, InsertToken);
11017 InsertNode(N);
11018 SDValue V(N, 0);
11019 NewSDValueDbgMsg(V, "Creating new node: ", this);
11020 return V;
11021}
11022
11024 SDValue Ptr, MachinePointerInfo PtrInfo,
11025 MaybeAlign Alignment,
11026 MachineMemOperand::Flags MMOFlags,
11027 const MMOMetadata &Metadata) {
11029 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11030 PtrInfo, VT, Alignment, MMOFlags, Metadata);
11031}
11032
11034 SDValue Ptr, MachineMemOperand *MMO) {
11036 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11037 VT, MMO);
11038}
11039
11041 EVT VT, SDValue Chain, SDValue Ptr,
11042 MachinePointerInfo PtrInfo, EVT MemVT,
11043 MaybeAlign Alignment,
11044 MachineMemOperand::Flags MMOFlags,
11045 const MMOMetadata &Metadata) {
11047 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
11048 MemVT, Alignment, MMOFlags, Metadata);
11049}
11050
11052 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
11053 MachineMemOperand *MMO) {
11055 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
11056 MemVT, MMO);
11057}
11058
11062 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
11063 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11064 "Load is already a indexed load!");
11065 // Don't propagate the invariant or dereferenceable flags.
11066 auto MMOFlags =
11067 LD->getMemOperand()->getFlags() &
11069 return getLoad(
11070 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
11071 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
11072 MMOFlags,
11073 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
11074}
11075
11077 SDValue Ptr, MachinePointerInfo PtrInfo,
11078 Align Alignment,
11079 MachineMemOperand::Flags MMOFlags,
11080 const MMOMetadata &Metadata) {
11081 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11082
11083 MMOFlags |= MachineMemOperand::MOStore;
11084 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11085 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11086
11087 if (PtrInfo.V.isNull())
11088 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11089
11092 MachineMemOperand *MMO =
11093 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11094 return getStore(Chain, dl, Val, Ptr, MMO);
11095}
11096
11098 SDValue Ptr, MachineMemOperand *MMO) {
11100 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
11102}
11103
11105 SDValue Ptr, SDValue Offset, EVT SVT,
11107 bool IsTruncating) {
11108 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11109 EVT VT = Val.getValueType();
11110 if (VT == SVT) {
11111 IsTruncating = false;
11112 } else if (!IsTruncating) {
11113 assert(VT == SVT && "No-truncating store from different memory type!");
11114 } else {
11116 "Should only be a truncating store, not extending!");
11117 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11118 assert(VT.isVector() == SVT.isVector() &&
11119 "Cannot use trunc store to convert to or from a vector!");
11120 assert((!VT.isVector() ||
11122 "Cannot use trunc store to change the number of vector elements!");
11123 }
11124
11125 bool Indexed = AM != ISD::UNINDEXED;
11126 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11127 "Unindexed store with an offset!");
11128 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11129 : getVTList(MVT::Other);
11130 SDValue Ops[] = {Chain, Val, Ptr, Offset};
11131 SDNodeKey ID(ISD::STORE, VTs, Ops);
11132 ID.AddInteger(SVT.getRawBits());
11133 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
11134 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
11135 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11136 ID.AddInteger(MMO->getFlags());
11137 FoldingSetInsertToken InsertToken;
11138 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11139 cast<StoreSDNode>(E)->refineAlignment(MMO);
11140 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
11141 return SDValue(E, 0);
11142 }
11143 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11144 IsTruncating, SVT, MMO);
11145 createOperands(N, Ops);
11146
11147 CSEMap.insert(N, InsertToken);
11148 InsertNode(N);
11149 SDValue V(N, 0);
11150 NewSDValueDbgMsg(V, "Creating new node: ", this);
11151 return V;
11152}
11153
11155 SDValue Ptr, SDValue Offset,
11156 MachinePointerInfo PtrInfo, EVT SVT,
11157 Align Alignment,
11158 MachineMemOperand::Flags MMOFlags,
11159 const MMOMetadata &Metadata) {
11160 assert(Chain.getValueType() == MVT::Other &&
11161 "Invalid chain type");
11162
11163 MMOFlags |= MachineMemOperand::MOStore;
11164 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11165 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11166
11167 if (PtrInfo.V.isNull())
11168 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11169
11171 MachineMemOperand *MMO = MF.getMachineMemOperand(
11172 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11173 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11174}
11175
11177 SDValue Ptr, MachinePointerInfo PtrInfo,
11178 EVT SVT, Align Alignment,
11179 MachineMemOperand::Flags MMOFlags,
11180 const MMOMetadata &Metadata) {
11181 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11182 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11183}
11184
11186 SDValue Ptr, SDValue Offset, EVT SVT,
11187 MachineMemOperand *MMO) {
11188 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11189}
11190
11192 SDValue Ptr, EVT SVT,
11193 MachineMemOperand *MMO) {
11194 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11195 ISD::UNINDEXED, true);
11196}
11197
11201 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11202 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11203 "Store is already a indexed store!");
11204 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11205 ST->getMemoryVT(), ST->getMemOperand(), AM,
11206 ST->isTruncatingStore());
11207}
11208
11210 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11211 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11212 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11213 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11214 const MDNode *Ranges, bool IsExpanding) {
11215 MMOFlags |= MachineMemOperand::MOLoad;
11216 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11217 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11218 // clients.
11219 if (PtrInfo.V.isNull())
11220 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11221
11222 TypeSize Size = MemVT.getStoreSize();
11224 MachineMemOperand *MMO = MF.getMachineMemOperand(
11225 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11226 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11227 MMO, IsExpanding);
11228}
11229
11231 ISD::LoadExtType ExtType, EVT VT,
11232 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11233 SDValue Offset, SDValue Mask, SDValue EVL,
11234 EVT MemVT, MachineMemOperand *MMO,
11235 bool IsExpanding) {
11236 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11237 assert(Mask.getValueType().getVectorElementCount() ==
11238 VT.getVectorElementCount() &&
11239 "Vector width mismatch between mask and data");
11240
11241 bool Indexed = AM != ISD::UNINDEXED;
11242 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11243 "Unindexed load with an offset!");
11244
11245 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11246 : getVTList(VT, MVT::Other);
11247 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11248 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11249 ID.AddInteger(MemVT.getRawBits());
11250 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11251 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11252 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11253 ID.AddInteger(MMO->getFlags());
11254 FoldingSetInsertToken InsertToken;
11255 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11256 E->refineAlignment(MMO);
11257 E->refineMMOMetadata(MMO);
11258 return SDValue(E, 0);
11259 }
11260 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11261 ExtType, IsExpanding, MemVT, MMO);
11262 createOperands(N, Ops);
11263
11264 CSEMap.insert(N, InsertToken);
11265 InsertNode(N);
11266 SDValue V(N, 0);
11267 NewSDValueDbgMsg(V, "Creating new node: ", this);
11268 return V;
11269}
11270
11272 SDValue Ptr, SDValue Mask, SDValue EVL,
11273 MachinePointerInfo PtrInfo,
11274 MaybeAlign Alignment,
11275 MachineMemOperand::Flags MMOFlags,
11276 const AAMDNodes &AAInfo, const MDNode *Ranges,
11277 bool IsExpanding) {
11279 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11280 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11281 IsExpanding);
11282}
11283
11285 SDValue Ptr, SDValue Mask, SDValue EVL,
11286 MachineMemOperand *MMO, bool IsExpanding) {
11288 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11289 Mask, EVL, VT, MMO, IsExpanding);
11290}
11291
11293 EVT VT, SDValue Chain, SDValue Ptr,
11294 SDValue Mask, SDValue EVL,
11295 MachinePointerInfo PtrInfo, EVT MemVT,
11296 MaybeAlign Alignment,
11297 MachineMemOperand::Flags MMOFlags,
11298 const AAMDNodes &AAInfo, bool IsExpanding) {
11300 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11301 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11302 IsExpanding);
11303}
11304
11306 EVT VT, SDValue Chain, SDValue Ptr,
11307 SDValue Mask, SDValue EVL, EVT MemVT,
11308 MachineMemOperand *MMO, bool IsExpanding) {
11310 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11311 EVL, MemVT, MMO, IsExpanding);
11312}
11313
11315 SDValue Ptr, SDValue Offset, SDValue Mask,
11316 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11317 ISD::MemIndexedMode AM, bool IsTruncating,
11318 bool IsCompressing) {
11319 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11320 assert(Mask.getValueType().getVectorElementCount() ==
11322 "Vector width mismatch between mask and data");
11323
11324 bool Indexed = AM != ISD::UNINDEXED;
11325 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11326 "Unindexed vp_store with an offset!");
11327 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11328 : getVTList(MVT::Other);
11329 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11330 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11331 ID.AddInteger(MemVT.getRawBits());
11332 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11333 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11334 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11335 ID.AddInteger(MMO->getFlags());
11336 FoldingSetInsertToken InsertToken;
11337 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11338 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11339 return SDValue(E, 0);
11340 }
11341 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11342 IsTruncating, IsCompressing, MemVT, MMO);
11343 createOperands(N, Ops);
11344
11345 CSEMap.insert(N, InsertToken);
11346 InsertNode(N);
11347 SDValue V(N, 0);
11348 NewSDValueDbgMsg(V, "Creating new node: ", this);
11349 return V;
11350}
11351
11353 SDValue Val, SDValue Ptr, SDValue Mask,
11354 SDValue EVL, MachinePointerInfo PtrInfo,
11355 EVT SVT, Align Alignment,
11356 MachineMemOperand::Flags MMOFlags,
11357 const AAMDNodes &AAInfo,
11358 bool IsCompressing) {
11359 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11360
11361 MMOFlags |= MachineMemOperand::MOStore;
11362 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11363
11364 if (PtrInfo.V.isNull())
11365 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11366
11368 MachineMemOperand *MMO = MF.getMachineMemOperand(
11369 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11370 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11371 IsCompressing);
11372}
11373
11375 SDValue Val, SDValue Ptr, SDValue Mask,
11376 SDValue EVL, EVT SVT,
11377 MachineMemOperand *MMO,
11378 bool IsCompressing) {
11379 EVT VT = Val.getValueType();
11380
11381 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11382 if (VT == SVT)
11383 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11384 EVL, VT, MMO, ISD::UNINDEXED,
11385 /*IsTruncating*/ false, IsCompressing);
11386
11388 "Should only be a truncating store, not extending!");
11389 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11390 assert(VT.isVector() == SVT.isVector() &&
11391 "Cannot use trunc store to convert to or from a vector!");
11392 assert((!VT.isVector() ||
11394 "Cannot use trunc store to change the number of vector elements!");
11395
11396 SDVTList VTs = getVTList(MVT::Other);
11398 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11399 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11400 ID.AddInteger(SVT.getRawBits());
11401 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11402 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11403 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11404 ID.AddInteger(MMO->getFlags());
11405 FoldingSetInsertToken InsertToken;
11406 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11407 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11408 return SDValue(E, 0);
11409 }
11410 auto *N =
11411 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11412 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11413 createOperands(N, Ops);
11414
11415 CSEMap.insert(N, InsertToken);
11416 InsertNode(N);
11417 SDValue V(N, 0);
11418 NewSDValueDbgMsg(V, "Creating new node: ", this);
11419 return V;
11420}
11421
11423 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11424 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11425 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11426 bool Indexed = AM != ISD::UNINDEXED;
11427 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11428 "Unindexed load with an offset!");
11429
11430 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11431 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11432 : getVTList(VT, MVT::Other);
11433 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11434 ID.AddInteger(MemVT.getRawBits());
11435 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11436 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11437 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11438
11439 FoldingSetInsertToken InsertToken;
11440 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11441 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11442 return SDValue(E, 0);
11443 }
11444
11445 auto *N =
11446 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11447 ExtType, IsExpanding, MemVT, MMO);
11448 createOperands(N, Ops);
11449 CSEMap.insert(N, InsertToken);
11450 InsertNode(N);
11451 SDValue V(N, 0);
11452 NewSDValueDbgMsg(V, "Creating new node: ", this);
11453 return V;
11454}
11455
11457 SDValue Ptr, SDValue Stride,
11458 SDValue Mask, SDValue EVL,
11459 MachineMemOperand *MMO,
11460 bool IsExpanding) {
11462 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11463 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11464}
11465
11467 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11468 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11469 MachineMemOperand *MMO, bool IsExpanding) {
11471 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11472 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11473}
11474
11476 SDValue Val, SDValue Ptr,
11477 SDValue Offset, SDValue Stride,
11478 SDValue Mask, SDValue EVL, EVT MemVT,
11479 MachineMemOperand *MMO,
11481 bool IsTruncating, bool IsCompressing) {
11482 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11483 bool Indexed = AM != ISD::UNINDEXED;
11484 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11485 "Unindexed vp_store with an offset!");
11486 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11487 : getVTList(MVT::Other);
11488 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11489 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11490 ID.AddInteger(MemVT.getRawBits());
11491 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11492 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11493 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11494 FoldingSetInsertToken InsertToken;
11495 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11496 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11497 return SDValue(E, 0);
11498 }
11499 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11500 VTs, AM, IsTruncating,
11501 IsCompressing, MemVT, MMO);
11502 createOperands(N, Ops);
11503
11504 CSEMap.insert(N, InsertToken);
11505 InsertNode(N);
11506 SDValue V(N, 0);
11507 NewSDValueDbgMsg(V, "Creating new node: ", this);
11508 return V;
11509}
11510
11513 ISD::MemIndexType IndexType) {
11514 assert(Ops.size() == 6 && "Incompatible number of operands");
11515
11516 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11517 ID.AddInteger(VT.getRawBits());
11518 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11519 dl.getIROrder(), VTs, VT, MMO, IndexType));
11520 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11521 ID.AddInteger(MMO->getFlags());
11522 FoldingSetInsertToken InsertToken;
11523 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11524 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11525 return SDValue(E, 0);
11526 }
11527
11528 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11529 VT, MMO, IndexType);
11530 createOperands(N, Ops);
11531
11532 assert(N->getMask().getValueType().getVectorElementCount() ==
11533 N->getValueType(0).getVectorElementCount() &&
11534 "Vector width mismatch between mask and data");
11535 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11536 N->getValueType(0).getVectorElementCount().isScalable() &&
11537 "Scalable flags of index and data do not match");
11539 N->getIndex().getValueType().getVectorElementCount(),
11540 N->getValueType(0).getVectorElementCount()) &&
11541 "Vector width mismatch between index and data");
11542 assert(isa<ConstantSDNode>(N->getScale()) &&
11543 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11544 "Scale should be a constant power of 2");
11545
11546 CSEMap.insert(N, InsertToken);
11547 InsertNode(N);
11548 SDValue V(N, 0);
11549 NewSDValueDbgMsg(V, "Creating new node: ", this);
11550 return V;
11551}
11552
11555 MachineMemOperand *MMO,
11556 ISD::MemIndexType IndexType) {
11557 assert(Ops.size() == 7 && "Incompatible number of operands");
11558
11559 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11560 ID.AddInteger(VT.getRawBits());
11561 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11562 dl.getIROrder(), VTs, VT, MMO, IndexType));
11563 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11564 ID.AddInteger(MMO->getFlags());
11565 FoldingSetInsertToken InsertToken;
11566 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11567 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11568 return SDValue(E, 0);
11569 }
11570 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11571 VT, MMO, IndexType);
11572 createOperands(N, Ops);
11573
11574 assert(N->getMask().getValueType().getVectorElementCount() ==
11575 N->getValue().getValueType().getVectorElementCount() &&
11576 "Vector width mismatch between mask and data");
11577 assert(
11578 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11579 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11580 "Scalable flags of index and data do not match");
11582 N->getIndex().getValueType().getVectorElementCount(),
11583 N->getValue().getValueType().getVectorElementCount()) &&
11584 "Vector width mismatch between index and data");
11585 assert(isa<ConstantSDNode>(N->getScale()) &&
11586 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11587 "Scale should be a constant power of 2");
11588
11589 CSEMap.insert(N, InsertToken);
11590 InsertNode(N);
11591 SDValue V(N, 0);
11592 NewSDValueDbgMsg(V, "Creating new node: ", this);
11593 return V;
11594}
11595
11598 SDValue PassThru, EVT MemVT,
11599 MachineMemOperand *MMO,
11601 ISD::LoadExtType ExtTy, bool isExpanding) {
11602 bool Indexed = AM != ISD::UNINDEXED;
11603 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11604 "Unindexed masked load with an offset!");
11605 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11606 : getVTList(VT, MVT::Other);
11607 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11608 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11609 ID.AddInteger(MemVT.getRawBits());
11610 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11611 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11612 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11613 ID.AddInteger(MMO->getFlags());
11614 FoldingSetInsertToken InsertToken;
11615 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11616 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11617 return SDValue(E, 0);
11618 }
11619 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11620 AM, ExtTy, isExpanding, MemVT, MMO);
11621 createOperands(N, Ops);
11622
11623 CSEMap.insert(N, InsertToken);
11624 InsertNode(N);
11625 SDValue V(N, 0);
11626 NewSDValueDbgMsg(V, "Creating new node: ", this);
11627 return V;
11628}
11629
11634 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11635 "Masked load is already a indexed load!");
11636 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11637 Offset, LD->getMask(), LD->getPassThru(),
11638 LD->getMemoryVT(), LD->getMemOperand(), AM,
11639 LD->getExtensionType(), LD->isExpandingLoad());
11640}
11641
11644 SDValue Mask, EVT MemVT,
11645 MachineMemOperand *MMO,
11646 ISD::MemIndexedMode AM, bool IsTruncating,
11647 bool IsCompressing) {
11648 assert(Chain.getValueType() == MVT::Other &&
11649 "Invalid chain type");
11650 bool Indexed = AM != ISD::UNINDEXED;
11651 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11652 "Unindexed masked store with an offset!");
11653 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11654 : getVTList(MVT::Other);
11655 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11656 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11657 ID.AddInteger(MemVT.getRawBits());
11658 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11659 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11660 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11661 ID.AddInteger(MMO->getFlags());
11662 FoldingSetInsertToken InsertToken;
11663 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11664 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11665 return SDValue(E, 0);
11666 }
11667 auto *N =
11668 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11669 IsTruncating, IsCompressing, MemVT, MMO);
11670 createOperands(N, Ops);
11671
11672 CSEMap.insert(N, InsertToken);
11673 InsertNode(N);
11674 SDValue V(N, 0);
11675 NewSDValueDbgMsg(V, "Creating new node: ", this);
11676 return V;
11677}
11678
11683 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11684 "Masked store is already a indexed store!");
11685 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11686 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11687 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11688}
11689
11692 MachineMemOperand *MMO,
11693 ISD::MemIndexType IndexType,
11694 ISD::LoadExtType ExtTy) {
11695 assert(Ops.size() == 6 && "Incompatible number of operands");
11696
11697 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11698 ID.AddInteger(MemVT.getRawBits());
11699 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11700 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11701 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11702 ID.AddInteger(MMO->getFlags());
11703 FoldingSetInsertToken InsertToken;
11704 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11705 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11706 return SDValue(E, 0);
11707 }
11708
11709 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11710 VTs, MemVT, MMO, IndexType, ExtTy);
11711 createOperands(N, Ops);
11712
11713 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11714 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11715 assert(N->getMask().getValueType().getVectorElementCount() ==
11716 N->getValueType(0).getVectorElementCount() &&
11717 "Vector width mismatch between mask and data");
11718 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11719 N->getValueType(0).getVectorElementCount().isScalable() &&
11720 "Scalable flags of index and data do not match");
11722 N->getIndex().getValueType().getVectorElementCount(),
11723 N->getValueType(0).getVectorElementCount()) &&
11724 "Vector width mismatch between index and data");
11725 assert(isa<ConstantSDNode>(N->getScale()) &&
11726 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11727 "Scale should be a constant power of 2");
11728
11729 CSEMap.insert(N, InsertToken);
11730 InsertNode(N);
11731 SDValue V(N, 0);
11732 NewSDValueDbgMsg(V, "Creating new node: ", this);
11733 return V;
11734}
11735
11738 MachineMemOperand *MMO,
11739 ISD::MemIndexType IndexType,
11740 bool IsTrunc) {
11741 assert(Ops.size() == 6 && "Incompatible number of operands");
11742
11743 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11744 ID.AddInteger(MemVT.getRawBits());
11745 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11746 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11747 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11748 ID.AddInteger(MMO->getFlags());
11749 FoldingSetInsertToken InsertToken;
11750 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11751 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11752 return SDValue(E, 0);
11753 }
11754
11755 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11756 VTs, MemVT, MMO, IndexType, IsTrunc);
11757 createOperands(N, Ops);
11758
11759 assert(N->getMask().getValueType().getVectorElementCount() ==
11760 N->getValue().getValueType().getVectorElementCount() &&
11761 "Vector width mismatch between mask and data");
11762 assert(
11763 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11764 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11765 "Scalable flags of index and data do not match");
11767 N->getIndex().getValueType().getVectorElementCount(),
11768 N->getValue().getValueType().getVectorElementCount()) &&
11769 "Vector width mismatch between index and data");
11770 assert(isa<ConstantSDNode>(N->getScale()) &&
11771 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11772 "Scale should be a constant power of 2");
11773
11774 CSEMap.insert(N, InsertToken);
11775 InsertNode(N);
11776 SDValue V(N, 0);
11777 NewSDValueDbgMsg(V, "Creating new node: ", this);
11778 return V;
11779}
11780
11782 const SDLoc &dl, ArrayRef<SDValue> Ops,
11783 MachineMemOperand *MMO,
11784 ISD::MemIndexType IndexType) {
11785 assert(Ops.size() == 7 && "Incompatible number of operands");
11786
11788 ID.AddInteger(MemVT.getRawBits());
11789 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11790 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11791 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11792 ID.AddInteger(MMO->getFlags());
11793 FoldingSetInsertToken InsertToken;
11794 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11795 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11796 return SDValue(E, 0);
11797 }
11798
11799 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11800 VTs, MemVT, MMO, IndexType);
11801 createOperands(N, Ops);
11802
11803 assert(N->getMask().getValueType().getVectorElementCount() ==
11804 N->getIndex().getValueType().getVectorElementCount() &&
11805 "Vector width mismatch between mask and data");
11806 assert(isa<ConstantSDNode>(N->getScale()) &&
11807 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11808 "Scale should be a constant power of 2");
11809 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11810
11811 CSEMap.insert(N, InsertToken);
11812 InsertNode(N);
11813 SDValue V(N, 0);
11814 NewSDValueDbgMsg(V, "Creating new node: ", this);
11815 return V;
11816}
11817
11819 SDValue Ptr, SDValue Mask, SDValue EVL,
11820 MachineMemOperand *MMO) {
11821 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11822 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11823 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11824 ID.AddInteger(VT.getRawBits());
11825 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11826 VTs, VT, MMO));
11827 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11828 ID.AddInteger(MMO->getFlags());
11829 FoldingSetInsertToken InsertToken;
11830 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11831 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11832 return SDValue(E, 0);
11833 }
11834 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11835 VT, MMO);
11836 createOperands(N, Ops);
11837
11838 CSEMap.insert(N, InsertToken);
11839 InsertNode(N);
11840 SDValue V(N, 0);
11841 NewSDValueDbgMsg(V, "Creating new node: ", this);
11842 return V;
11843}
11844
11846 EVT MemVT, MachineMemOperand *MMO) {
11847 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11848 SDVTList VTs = getVTList(MVT::Other);
11849 SDValue Ops[] = {Chain, Ptr};
11851 ID.AddInteger(MemVT.getRawBits());
11852 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11853 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11854 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11855 ID.AddInteger(MMO->getFlags());
11856 FoldingSetInsertToken InsertToken;
11857 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11858 return SDValue(E, 0);
11859
11860 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11861 dl.getDebugLoc(), VTs, MemVT, MMO);
11862 createOperands(N, Ops);
11863
11864 CSEMap.insert(N, InsertToken);
11865 InsertNode(N);
11866 SDValue V(N, 0);
11867 NewSDValueDbgMsg(V, "Creating new node: ", this);
11868 return V;
11869}
11870
11872 EVT MemVT, MachineMemOperand *MMO) {
11873 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11874 SDVTList VTs = getVTList(MVT::Other);
11875 SDValue Ops[] = {Chain, Ptr};
11877 ID.AddInteger(MemVT.getRawBits());
11878 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11879 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11880 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11881 ID.AddInteger(MMO->getFlags());
11882 FoldingSetInsertToken InsertToken;
11883 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11884 return SDValue(E, 0);
11885
11886 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11887 dl.getDebugLoc(), VTs, MemVT, MMO);
11888 createOperands(N, Ops);
11889
11890 CSEMap.insert(N, InsertToken);
11891 InsertNode(N);
11892 SDValue V(N, 0);
11893 NewSDValueDbgMsg(V, "Creating new node: ", this);
11894 return V;
11895}
11896
11898 // select undef, T, F --> T (if T is a constant), otherwise F
11899 // select, ?, undef, F --> F
11900 // select, ?, T, undef --> T
11901 if (Cond.isUndef())
11902 return isConstantValueOfAnyType(T) ? T : F;
11903 if (T.isUndef())
11905 if (F.isUndef())
11907
11908 // select true, T, F --> T
11909 // select false, T, F --> F
11910 if (auto C = isBoolConstant(Cond))
11911 return *C ? T : F;
11912
11913 // select ?, T, T --> T
11914 if (T == F)
11915 return T;
11916
11917 return SDValue();
11918}
11919
11921 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11922 if (X.isUndef())
11923 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11924 // shift X, undef --> undef (because it may shift by the bitwidth)
11925 if (Y.isUndef())
11926 return getUNDEF(X.getValueType());
11927
11928 // shift 0, Y --> 0
11929 // shift X, 0 --> X
11931 return X;
11932
11933 // shift X, C >= bitwidth(X) --> undef
11934 // All vector elements must be too big (or undef) to avoid partial undefs.
11935 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11936 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11937 };
11938 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11939 return getUNDEF(X.getValueType());
11940
11941 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11942 if (X.getValueType().getScalarType() == MVT::i1)
11943 return X;
11944
11945 return SDValue();
11946}
11947
11949 SDNodeFlags Flags) {
11950 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11951 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11952 // operation is poison. That result can be relaxed to undef.
11953 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11954 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11955 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11956 (YC && YC->getValueAPF().isNaN());
11957 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11958 (YC && YC->getValueAPF().isInfinity());
11959
11960 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11961 return getUNDEF(X.getValueType());
11962
11963 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11964 return getUNDEF(X.getValueType());
11965
11966 if (!YC)
11967 return SDValue();
11968
11969 // X + -0.0 --> X
11970 if (Opcode == ISD::FADD)
11971 if (YC->getValueAPF().isNegZero())
11972 return X;
11973
11974 // X - +0.0 --> X
11975 if (Opcode == ISD::FSUB)
11976 if (YC->getValueAPF().isPosZero())
11977 return X;
11978
11979 // X * 1.0 --> X
11980 // X / 1.0 --> X
11981 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11982 if (YC->getValueAPF().isOne())
11983 return X;
11984
11985 // X * 0.0 --> 0.0
11986 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11987 if (YC->getValueAPF().isZero())
11988 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11989
11990 return SDValue();
11991}
11992
11994 SDValue Ptr, SDValue SV, unsigned Align) {
11995 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11996 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11997}
11998
11999SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12001 switch (Ops.size()) {
12002 case 0: return getNode(Opcode, DL, VT);
12003 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
12004 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
12005 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
12006 default: break;
12007 }
12008
12009 // Copy from an SDUse array into an SDValue array for use with
12010 // the regular getNode logic.
12012 return getNode(Opcode, DL, VT, NewOps);
12013}
12014
12015SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12017 SDNodeFlags Flags;
12018 if (Inserter)
12019 Flags = Inserter->getFlags();
12020 return getNode(Opcode, DL, VT, Ops, Flags);
12021}
12022
12023SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12024 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12025 unsigned NumOps = Ops.size();
12026 switch (NumOps) {
12027 case 0: return getNode(Opcode, DL, VT);
12028 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
12029 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
12030 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
12031 default: break;
12032 }
12033
12034#ifndef NDEBUG
12035 for (const auto &Op : Ops)
12036 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12037 "Operand is DELETED_NODE!");
12038#endif
12039
12040 switch (Opcode) {
12041 default: break;
12042 case ISD::BUILD_VECTOR:
12043 // Attempt to simplify BUILD_VECTOR.
12044 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12045 return V;
12046 break;
12048 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12049 return V;
12050 break;
12051 case ISD::SELECT_CC:
12052 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12053 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12054 "LHS and RHS of condition must have same type!");
12055 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12056 "True and False arms of SelectCC must have same type!");
12057 assert(Ops[2].getValueType() == VT &&
12058 "select_cc node must be of same type as true and false value!");
12059 assert((!Ops[0].getValueType().isVector() ||
12060 Ops[0].getValueType().getVectorElementCount() ==
12061 VT.getVectorElementCount()) &&
12062 "Expected select_cc with vector result to have the same sized "
12063 "comparison type!");
12064 break;
12065 case ISD::BR_CC:
12066 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12067 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12068 "LHS/RHS of comparison should match types!");
12069 break;
12070 case ISD::VP_REDUCE_MUL:
12071 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12072 if (VT == MVT::i1)
12073 Opcode = ISD::VP_REDUCE_AND;
12074 break;
12075 case ISD::VP_REDUCE_ADD:
12076 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12077 if (VT == MVT::i1)
12078 Opcode = ISD::VP_REDUCE_XOR;
12079 break;
12080 case ISD::VP_REDUCE_SMAX:
12081 case ISD::VP_REDUCE_UMIN:
12082 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12083 // VP_REDUCE_AND.
12084 if (VT == MVT::i1)
12085 Opcode = ISD::VP_REDUCE_AND;
12086 break;
12087 case ISD::VP_REDUCE_SMIN:
12088 case ISD::VP_REDUCE_UMAX:
12089 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12090 // VP_REDUCE_OR.
12091 if (VT == MVT::i1)
12092 Opcode = ISD::VP_REDUCE_OR;
12093 break;
12094 }
12095
12096 // Memoize nodes.
12097 SDNode *N;
12098 SDVTList VTs = getVTList(VT);
12099
12100 if (VT != MVT::Glue) {
12101 SDNodeKey ID(Opcode, VTs, Ops);
12102 FoldingSetInsertToken InsertToken;
12103
12104 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12105 E->intersectFlagsWith(Flags);
12106 return SDValue(E, 0);
12107 }
12108
12109 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12110 createOperands(N, Ops);
12111
12112 CSEMap.insert(N, InsertToken);
12113 } else {
12114 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12115 createOperands(N, Ops);
12116 }
12117
12118 N->setFlags(Flags);
12119 InsertNode(N);
12120 SDValue V(N, 0);
12121 NewSDValueDbgMsg(V, "Creating new node: ", this);
12122 return V;
12123}
12124
12125SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12126 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12127 SDNodeFlags Flags;
12128 if (Inserter)
12129 Flags = Inserter->getFlags();
12130 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12131}
12132
12133SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12135 const SDNodeFlags Flags) {
12136 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12137}
12138
12139SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12141 SDNodeFlags Flags;
12142 if (Inserter)
12143 Flags = Inserter->getFlags();
12144 return getNode(Opcode, DL, VTList, Ops, Flags);
12145}
12146
12147SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12148 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12149 if (VTList.NumVTs == 1)
12150 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12151
12152#ifndef NDEBUG
12153 for (const auto &Op : Ops)
12154 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12155 "Operand is DELETED_NODE!");
12156#endif
12157
12158 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VTList, Ops, Flags))
12159 return V;
12160
12161 switch (Opcode) {
12162 case ISD::SADDO:
12163 case ISD::UADDO:
12164 case ISD::SSUBO:
12165 case ISD::USUBO: {
12166 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12167 "Invalid add/sub overflow op!");
12168 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12169 Ops[0].getValueType() == Ops[1].getValueType() &&
12170 Ops[0].getValueType() == VTList.VTs[0] &&
12171 "Binary operator types must match!");
12172 SDValue N1 = Ops[0], N2 = Ops[1];
12173 canonicalizeCommutativeBinop(Opcode, N1, N2);
12174
12175 // (X +- 0) -> X with zero-overflow.
12176 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12177 /*AllowTruncation*/ true);
12178 if (N2CV && N2CV->isZero()) {
12179 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12180 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12181 }
12182
12183 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12184 VTList.VTs[1].getScalarType() == MVT::i1) {
12185 SDValue F1 = getFreeze(N1);
12186 SDValue F2 = getFreeze(N2);
12187 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12188 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12189 return getNode(ISD::MERGE_VALUES, DL, VTList,
12190 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12191 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12192 Flags);
12193 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12194 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12195 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12196 return getNode(ISD::MERGE_VALUES, DL, VTList,
12197 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12198 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12199 Flags);
12200 }
12201 }
12202 break;
12203 }
12204 case ISD::SADDO_CARRY:
12205 case ISD::UADDO_CARRY:
12206 case ISD::SSUBO_CARRY:
12207 case ISD::USUBO_CARRY:
12208 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12209 "Invalid add/sub overflow op!");
12210 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12211 Ops[0].getValueType() == Ops[1].getValueType() &&
12212 Ops[0].getValueType() == VTList.VTs[0] &&
12213 Ops[2].getValueType() == VTList.VTs[1] &&
12214 "Binary operator types must match!");
12215 break;
12216 case ISD::SMUL_LOHI:
12217 case ISD::UMUL_LOHI: {
12218 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12219 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12220 VTList.VTs[0] == Ops[0].getValueType() &&
12221 VTList.VTs[0] == Ops[1].getValueType() &&
12222 "Binary operator types must match!");
12223 // Constant fold.
12226 if (LHS && RHS) {
12227 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12228 unsigned OutWidth = Width * 2;
12229 APInt Val = LHS->getAPIntValue();
12230 APInt Mul = RHS->getAPIntValue();
12231 if (Opcode == ISD::SMUL_LOHI) {
12232 Val = Val.sext(OutWidth);
12233 Mul = Mul.sext(OutWidth);
12234 } else {
12235 Val = Val.zext(OutWidth);
12236 Mul = Mul.zext(OutWidth);
12237 }
12238 Val *= Mul;
12239
12240 SDValue Hi =
12241 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12242 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12243 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12244 }
12245 break;
12246 }
12247 case ISD::FFREXP: {
12248 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12249 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12250 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12251
12253 int FrexpExp;
12254 APFloat FrexpMant =
12255 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12256 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12257 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12258 DL, VTList.VTs[1]);
12259 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12260 }
12261
12262 break;
12263 }
12265 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12266 "Invalid STRICT_FP_EXTEND!");
12267 assert(VTList.VTs[0].isFloatingPoint() &&
12268 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12269 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12270 "STRICT_FP_EXTEND result type should be vector iff the operand "
12271 "type is vector!");
12272 assert((!VTList.VTs[0].isVector() ||
12273 VTList.VTs[0].getVectorElementCount() ==
12274 Ops[1].getValueType().getVectorElementCount()) &&
12275 "Vector element count mismatch!");
12276 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12277 "Invalid fpext node, dst <= src!");
12278 break;
12280 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12281 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12282 "STRICT_FP_ROUND result type should be vector iff the operand "
12283 "type is vector!");
12284 assert((!VTList.VTs[0].isVector() ||
12285 VTList.VTs[0].getVectorElementCount() ==
12286 Ops[1].getValueType().getVectorElementCount()) &&
12287 "Vector element count mismatch!");
12288 assert(VTList.VTs[0].isFloatingPoint() &&
12289 Ops[1].getValueType().isFloatingPoint() &&
12290 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12291 Ops[2].getOpcode() == ISD::TargetConstant &&
12292 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12293 "Invalid STRICT_FP_ROUND!");
12294 break;
12295 }
12296
12297 // Memoize the node unless it returns a glue result.
12298 SDNode *N;
12299 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12300 SDNodeKey ID(Opcode, VTList, Ops);
12301 FoldingSetInsertToken InsertToken;
12302 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12303 E->intersectFlagsWith(Flags);
12304 return SDValue(E, 0);
12305 }
12306
12307 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12308 createOperands(N, Ops);
12309 CSEMap.insert(N, InsertToken);
12310 } else {
12311 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12312 createOperands(N, Ops);
12313 }
12314
12315 N->setFlags(Flags);
12316 InsertNode(N);
12317 SDValue V(N, 0);
12318 NewSDValueDbgMsg(V, "Creating new node: ", this);
12319 return V;
12320}
12321
12322SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12323 SDVTList VTList) {
12324 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12325}
12326
12327SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12328 SDValue N1) {
12329 SDValue Ops[] = { N1 };
12330 return getNode(Opcode, DL, VTList, Ops);
12331}
12332
12333SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12334 SDValue N1, SDValue N2) {
12335 SDValue Ops[] = { N1, N2 };
12336 return getNode(Opcode, DL, VTList, Ops);
12337}
12338
12339SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12340 SDValue N1, SDValue N2, SDValue N3) {
12341 SDValue Ops[] = { N1, N2, N3 };
12342 return getNode(Opcode, DL, VTList, Ops);
12343}
12344
12345SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12346 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12347 SDValue Ops[] = { N1, N2, N3, N4 };
12348 return getNode(Opcode, DL, VTList, Ops);
12349}
12350
12351SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12352 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12353 SDValue N5) {
12354 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12355 return getNode(Opcode, DL, VTList, Ops);
12356}
12357
12359 if (!VT.isExtended())
12360 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12361
12362 EVT VTs[] = {VT};
12363 return getVTList(VTs);
12364}
12365
12367 EVT VTs[] = {VT1, VT2};
12368 return getVTList(VTs);
12369}
12370
12372 EVT VTs[] = {VT1, VT2, VT3};
12373 return getVTList(VTs);
12374}
12375
12377 EVT VTs[] = {VT1, VT2, VT3, VT4};
12378 return getVTList(VTs);
12379}
12380
12382 auto It = VTLists.find(VTs);
12383 if (It == VTLists.end()) {
12384 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12385 llvm::copy(VTs, Array);
12386 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12387 }
12388 return makeVTList(It->data(), It->size());
12389}
12390
12391/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12392/// specified operands. If the resultant node already exists in the DAG,
12393/// this does not modify the specified node, instead it returns the node that
12394/// already exists. If the resultant node does not exist in the DAG, the
12395/// input node is returned. As a degenerate case, if you specify the same
12396/// input operands as the node already has, the input node is returned.
12398 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12399
12400 // Check to see if there is no change.
12401 if (Op == N->getOperand(0)) return N;
12402
12403 // See if the modified node already exists.
12404 FoldingSetInsertToken InsertToken;
12405 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken))
12406 return Existing;
12407
12408 // Nope it doesn't. Remove the node from its current place in the maps.
12409 if (InsertToken)
12410 if (!RemoveNodeFromCSEMaps(N))
12411 InsertToken = {};
12412
12413 // Now we update the operands.
12414 N->OperandList[0].set(Op);
12415
12417 // If this gets put into a CSE map, add it.
12418 if (InsertToken)
12419 CSEMap.insert(N, InsertToken);
12420 return N;
12421}
12422
12424 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12425
12426 // Check to see if there is no change.
12427 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12428 return N; // No operands changed, just return the input node.
12429
12430 // See if the modified node already exists.
12431 FoldingSetInsertToken InsertToken;
12432 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken))
12433 return Existing;
12434
12435 // Nope it doesn't. Remove the node from its current place in the maps.
12436 if (InsertToken)
12437 if (!RemoveNodeFromCSEMaps(N))
12438 InsertToken = {};
12439
12440 // Now we update the operands.
12441 if (N->OperandList[0] != Op1)
12442 N->OperandList[0].set(Op1);
12443 if (N->OperandList[1] != Op2)
12444 N->OperandList[1].set(Op2);
12445
12447 // If this gets put into a CSE map, add it.
12448 if (InsertToken)
12449 CSEMap.insert(N, InsertToken);
12450 return N;
12451}
12452
12455 SDValue Ops[] = { Op1, Op2, Op3 };
12456 return UpdateNodeOperands(N, Ops);
12457}
12458
12461 SDValue Op3, SDValue Op4) {
12462 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12463 return UpdateNodeOperands(N, Ops);
12464}
12465
12468 SDValue Op3, SDValue Op4, SDValue Op5) {
12469 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12470 return UpdateNodeOperands(N, Ops);
12471}
12472
12475 unsigned NumOps = Ops.size();
12476 assert(N->getNumOperands() == NumOps &&
12477 "Update with wrong number of operands");
12478
12479 // If no operands changed just return the input node.
12480 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12481 return N;
12482
12483 // See if the modified node already exists.
12484 FoldingSetInsertToken InsertToken;
12485 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken))
12486 return Existing;
12487
12488 // Nope it doesn't. Remove the node from its current place in the maps.
12489 if (InsertToken)
12490 if (!RemoveNodeFromCSEMaps(N))
12491 InsertToken = {};
12492
12493 // Now we update the operands.
12494 for (unsigned i = 0; i != NumOps; ++i)
12495 if (N->OperandList[i] != Ops[i])
12496 N->OperandList[i].set(Ops[i]);
12497
12499 // If this gets put into a CSE map, add it.
12500 if (InsertToken)
12501 CSEMap.insert(N, InsertToken);
12502 return N;
12503}
12504
12505/// DropOperands - Release the operands and set this node to have
12506/// zero operands.
12508 // Unlike the code in MorphNodeTo that does this, we don't need to
12509 // watch for dead nodes here.
12510 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12511 SDUse &Use = *I++;
12512 Use.set(SDValue());
12513 }
12514}
12515
12517 ArrayRef<MachineMemOperand *> NewMemRefs) {
12518 if (NewMemRefs.empty()) {
12519 N->clearMemRefs();
12520 return;
12521 }
12522
12523 // Check if we can avoid allocating by storing a single reference directly.
12524 if (NewMemRefs.size() == 1) {
12525 N->MemRefs = NewMemRefs[0];
12526 N->NumMemRefs = 1;
12527 return;
12528 }
12529
12530 MachineMemOperand **MemRefsBuffer =
12531 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12532 llvm::copy(NewMemRefs, MemRefsBuffer);
12533 N->MemRefs = MemRefsBuffer;
12534 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12535}
12536
12537/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12538/// machine opcode.
12539///
12541 EVT VT) {
12542 SDVTList VTs = getVTList(VT);
12543 return SelectNodeTo(N, MachineOpc, VTs, {});
12544}
12545
12547 EVT VT, SDValue Op1) {
12548 SDVTList VTs = getVTList(VT);
12549 SDValue Ops[] = { Op1 };
12550 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12551}
12552
12554 EVT VT, SDValue Op1,
12555 SDValue Op2) {
12556 SDVTList VTs = getVTList(VT);
12557 SDValue Ops[] = { Op1, Op2 };
12558 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12559}
12560
12562 EVT VT, SDValue Op1,
12563 SDValue Op2, SDValue Op3) {
12564 SDVTList VTs = getVTList(VT);
12565 SDValue Ops[] = { Op1, Op2, Op3 };
12566 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12567}
12568
12571 SDVTList VTs = getVTList(VT);
12572 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12573}
12574
12576 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12577 SDVTList VTs = getVTList(VT1, VT2);
12578 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12579}
12580
12582 EVT VT1, EVT VT2) {
12583 SDVTList VTs = getVTList(VT1, VT2);
12584 return SelectNodeTo(N, MachineOpc, VTs, {});
12585}
12586
12588 EVT VT1, EVT VT2, EVT VT3,
12590 SDVTList VTs = getVTList(VT1, VT2, VT3);
12591 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12592}
12593
12595 EVT VT1, EVT VT2,
12596 SDValue Op1, SDValue Op2) {
12597 SDVTList VTs = getVTList(VT1, VT2);
12598 SDValue Ops[] = { Op1, Op2 };
12599 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12600}
12601
12604 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12605 // Reset the NodeID to -1.
12606 New->setNodeId(-1);
12607 if (New != N) {
12608 ReplaceAllUsesWith(N, New);
12610 }
12611 return New;
12612}
12613
12614/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12615/// the line number information on the merged node since it is not possible to
12616/// preserve the information that operation is associated with multiple lines.
12617/// This will make the debugger working better at -O0, were there is a higher
12618/// probability having other instructions associated with that line.
12619///
12620/// For IROrder, we keep the smaller of the two
12621SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12622 DebugLoc NLoc = N->getDebugLoc();
12623 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12624 N->setDebugLoc(DebugLoc());
12625 }
12626 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12627 N->setIROrder(Order);
12628 return N;
12629}
12630
12631/// MorphNodeTo - This *mutates* the specified node to have the specified
12632/// return type, opcode, and operands.
12633///
12634/// Note that MorphNodeTo returns the resultant node. If there is already a
12635/// node of the specified opcode and operands, it returns that node instead of
12636/// the current one. Note that the SDLoc need not be the same.
12637///
12638/// Using MorphNodeTo is faster than creating a new node and swapping it in
12639/// with ReplaceAllUsesWith both because it often avoids allocating a new
12640/// node, and because it doesn't require CSE recalculation for any of
12641/// the node's users.
12642///
12643/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12644/// As a consequence it isn't appropriate to use from within the DAG combiner or
12645/// the legalizer which maintain worklists that would need to be updated when
12646/// deleting things.
12649 // If an identical node already exists, use it.
12650 FoldingSetInsertToken InsertToken;
12651 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12652 SDNodeKey ID(Opc, VTs, Ops);
12653 AddNodeIDCustom(ID.Tail, N, Opc);
12654 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12655 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12656 }
12657
12658 if (!RemoveNodeFromCSEMaps(N))
12659 InsertToken = {};
12660
12661 // Start the morphing.
12662 N->NodeType = Opc;
12663 N->ValueList = VTs.VTs;
12664 N->NumValues = VTs.NumVTs;
12665
12666 // Clear the operands list, updating used nodes to remove this from their
12667 // use list. Keep track of any operands that become dead as a result.
12668 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12669 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12670 SDUse &Use = *I++;
12671 SDNode *Used = Use.getNode();
12672 Use.set(SDValue());
12673 if (Used->use_empty())
12674 DeadNodeSet.insert(Used);
12675 }
12676
12677 // For MachineNode, initialize the memory references information.
12679 MN->clearMemRefs();
12680
12681 // Swap for an appropriately sized array from the recycler.
12682 removeOperands(N);
12683 createOperands(N, Ops);
12684
12685 // Delete any nodes that are still dead after adding the uses for the
12686 // new operands.
12687 if (!DeadNodeSet.empty()) {
12688 SmallVector<SDNode *, 16> DeadNodes;
12689 for (SDNode *N : DeadNodeSet)
12690 if (N->use_empty())
12691 DeadNodes.push_back(N);
12692 RemoveDeadNodes(DeadNodes);
12693 }
12694
12695 if (InsertToken)
12696 CSEMap.insert(N, InsertToken); // Memoize the new node.
12697 return N;
12698}
12699
12701 unsigned OrigOpc = Node->getOpcode();
12702 unsigned NewOpc;
12703 switch (OrigOpc) {
12704 default:
12705 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12706#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12707 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12708#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12709 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12710#include "llvm/IR/ConstrainedOps.def"
12711 }
12712
12713 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12714
12715 // We're taking this node out of the chain, so we need to re-link things.
12716 SDValue InputChain = Node->getOperand(0);
12717 SDValue OutputChain = SDValue(Node, 1);
12718 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12719
12721 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12722 Ops.push_back(Node->getOperand(i));
12723
12724 SDVTList VTs = getVTList(Node->getValueType(0));
12725 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12726
12727 // MorphNodeTo can operate in two ways: if an existing node with the
12728 // specified operands exists, it can just return it. Otherwise, it
12729 // updates the node in place to have the requested operands.
12730 if (Res == Node) {
12731 // If we updated the node in place, reset the node ID. To the isel,
12732 // this should be just like a newly allocated machine node.
12733 Res->setNodeId(-1);
12734 } else {
12737 }
12738
12739 return Res;
12740}
12741
12742/// getMachineNode - These are used for target selectors to create a new node
12743/// with specified return type(s), MachineInstr opcode, and operands.
12744///
12745/// Note that getMachineNode returns the resultant node. If there is already a
12746/// node of the specified opcode and operands, it returns that node instead of
12747/// the current one.
12749 EVT VT) {
12750 SDVTList VTs = getVTList(VT);
12751 return getMachineNode(Opcode, dl, VTs, {});
12752}
12753
12755 EVT VT, SDValue Op1) {
12756 SDVTList VTs = getVTList(VT);
12757 SDValue Ops[] = { Op1 };
12758 return getMachineNode(Opcode, dl, VTs, Ops);
12759}
12760
12762 EVT VT, SDValue Op1, SDValue Op2) {
12763 SDVTList VTs = getVTList(VT);
12764 SDValue Ops[] = { Op1, Op2 };
12765 return getMachineNode(Opcode, dl, VTs, Ops);
12766}
12767
12769 EVT VT, SDValue Op1, SDValue Op2,
12770 SDValue Op3) {
12771 SDVTList VTs = getVTList(VT);
12772 SDValue Ops[] = { Op1, Op2, Op3 };
12773 return getMachineNode(Opcode, dl, VTs, Ops);
12774}
12775
12778 SDVTList VTs = getVTList(VT);
12779 return getMachineNode(Opcode, dl, VTs, Ops);
12780}
12781
12783 EVT VT1, EVT VT2, SDValue Op1,
12784 SDValue Op2) {
12785 SDVTList VTs = getVTList(VT1, VT2);
12786 SDValue Ops[] = { Op1, Op2 };
12787 return getMachineNode(Opcode, dl, VTs, Ops);
12788}
12789
12791 EVT VT1, EVT VT2, SDValue Op1,
12792 SDValue Op2, SDValue Op3) {
12793 SDVTList VTs = getVTList(VT1, VT2);
12794 SDValue Ops[] = { Op1, Op2, Op3 };
12795 return getMachineNode(Opcode, dl, VTs, Ops);
12796}
12797
12799 EVT VT1, EVT VT2,
12801 SDVTList VTs = getVTList(VT1, VT2);
12802 return getMachineNode(Opcode, dl, VTs, Ops);
12803}
12804
12806 EVT VT1, EVT VT2, EVT VT3,
12807 SDValue Op1, SDValue Op2) {
12808 SDVTList VTs = getVTList(VT1, VT2, VT3);
12809 SDValue Ops[] = { Op1, Op2 };
12810 return getMachineNode(Opcode, dl, VTs, Ops);
12811}
12812
12814 EVT VT1, EVT VT2, EVT VT3,
12815 SDValue Op1, SDValue Op2,
12816 SDValue Op3) {
12817 SDVTList VTs = getVTList(VT1, VT2, VT3);
12818 SDValue Ops[] = { Op1, Op2, Op3 };
12819 return getMachineNode(Opcode, dl, VTs, Ops);
12820}
12821
12823 EVT VT1, EVT VT2, EVT VT3,
12825 SDVTList VTs = getVTList(VT1, VT2, VT3);
12826 return getMachineNode(Opcode, dl, VTs, Ops);
12827}
12828
12830 ArrayRef<EVT> ResultTys,
12832 SDVTList VTs = getVTList(ResultTys);
12833 return getMachineNode(Opcode, dl, VTs, Ops);
12834}
12835
12837 SDVTList VTs,
12839 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12841 FoldingSetInsertToken InsertToken;
12842
12843 if (DoCSE) {
12844 SDNodeKey ID(~Opcode, VTs, Ops);
12845 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12846 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12847 }
12848 }
12849
12850 // Allocate a new MachineSDNode.
12851 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12852 createOperands(N, Ops);
12853
12854 if (DoCSE)
12855 CSEMap.insert(N, InsertToken);
12856
12857 InsertNode(N);
12858 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12859 return N;
12860}
12861
12862/// getTargetExtractSubreg - A convenience function for creating
12863/// TargetOpcode::EXTRACT_SUBREG nodes.
12865 SDValue Operand) {
12866 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12867 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12868 VT, Operand, SRIdxVal);
12869 return SDValue(Subreg, 0);
12870}
12871
12872/// getTargetInsertSubreg - A convenience function for creating
12873/// TargetOpcode::INSERT_SUBREG nodes.
12875 SDValue Operand, SDValue Subreg) {
12876 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12877 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12878 VT, Operand, Subreg, SRIdxVal);
12879 return SDValue(Result, 0);
12880}
12881
12882/// getNodeIfExists - Get the specified node if it's already available, or
12883/// else return NULL.
12886 bool AllowCommute) {
12887 SDNodeFlags Flags;
12888 if (Inserter)
12889 Flags = Inserter->getFlags();
12890 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12891}
12892
12895 const SDNodeFlags Flags,
12896 bool AllowCommute) {
12897 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12898 return nullptr;
12899
12900 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12901 SDNodeKey ID(Opcode, VTList, LookupOps);
12902 FoldingSetInsertToken InsertToken;
12903 if (SDNode *E = lookupNode(ID, InsertToken)) {
12904 E->intersectFlagsWith(Flags);
12905 return E;
12906 }
12907 return nullptr;
12908 };
12909
12910 if (SDNode *Existing = Lookup(Ops))
12911 return Existing;
12912
12913 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12914 return Lookup({Ops[1], Ops[0]});
12915
12916 return nullptr;
12917}
12918
12919/// doesNodeExist - Check if a node exists without modifying its flags.
12920bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12922 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12923 SDNodeKey ID(Opcode, VTList, Ops);
12924 FoldingSetInsertToken InsertToken;
12925 if (lookupNode(ID, SDLoc(), InsertToken))
12926 return true;
12927 }
12928 return false;
12929}
12930
12931/// getDbgValue - Creates a SDDbgValue node.
12932///
12933/// SDNode
12935 SDNode *N, unsigned R, bool IsIndirect,
12936 const DebugLoc &DL, unsigned O) {
12937 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12938 "Expected inlined-at fields to agree");
12939 return new (DbgInfo->getAlloc())
12940 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12941 {}, IsIndirect, DL, O,
12942 /*IsVariadic=*/false);
12943}
12944
12945/// Constant
12947 DIExpression *Expr,
12948 const Value *C,
12949 const DebugLoc &DL, unsigned O) {
12950 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12951 "Expected inlined-at fields to agree");
12952 return new (DbgInfo->getAlloc())
12953 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12954 /*IsIndirect=*/false, DL, O,
12955 /*IsVariadic=*/false);
12956}
12957
12958/// FrameIndex
12960 DIExpression *Expr, unsigned FI,
12961 bool IsIndirect,
12962 const DebugLoc &DL,
12963 unsigned O) {
12964 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12965 "Expected inlined-at fields to agree");
12966 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12967}
12968
12969/// FrameIndex with dependencies
12971 DIExpression *Expr, unsigned FI,
12972 ArrayRef<SDNode *> Dependencies,
12973 bool IsIndirect,
12974 const DebugLoc &DL,
12975 unsigned O) {
12976 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12977 "Expected inlined-at fields to agree");
12978 return new (DbgInfo->getAlloc())
12979 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
12980 Dependencies, IsIndirect, DL, O,
12981 /*IsVariadic=*/false);
12982}
12983
12984/// VReg
12986 Register VReg, bool IsIndirect,
12987 const DebugLoc &DL, unsigned O) {
12988 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12989 "Expected inlined-at fields to agree");
12990 return new (DbgInfo->getAlloc())
12991 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
12992 {}, IsIndirect, DL, O,
12993 /*IsVariadic=*/false);
12994}
12995
12998 ArrayRef<SDNode *> Dependencies,
12999 bool IsIndirect, const DebugLoc &DL,
13000 unsigned O, bool IsVariadic) {
13001 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13002 "Expected inlined-at fields to agree");
13003 return new (DbgInfo->getAlloc())
13004 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13005 DL, O, IsVariadic);
13006}
13007
13009 unsigned OffsetInBits, unsigned SizeInBits,
13010 bool InvalidateDbg) {
13011 SDNode *FromNode = From.getNode();
13012 SDNode *ToNode = To.getNode();
13013 assert(FromNode && ToNode && "Can't modify dbg values");
13014
13015 // PR35338
13016 // TODO: assert(From != To && "Redundant dbg value transfer");
13017 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13018 if (From == To || FromNode == ToNode)
13019 return;
13020
13021 if (!FromNode->getHasDebugValue())
13022 return;
13023
13024 SDDbgOperand FromLocOp =
13025 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13027
13029 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13030 if (Dbg->isInvalidated())
13031 continue;
13032
13033 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13034
13035 // Create a new location ops vector that is equal to the old vector, but
13036 // with each instance of FromLocOp replaced with ToLocOp.
13037 bool Changed = false;
13038 auto NewLocOps = Dbg->copyLocationOps();
13039 std::replace_if(
13040 NewLocOps.begin(), NewLocOps.end(),
13041 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13042 bool Match = Op == FromLocOp;
13043 Changed |= Match;
13044 return Match;
13045 },
13046 ToLocOp);
13047 // Ignore this SDDbgValue if we didn't find a matching location.
13048 if (!Changed)
13049 continue;
13050
13051 DIVariable *Var = Dbg->getVariable();
13052 auto *Expr = Dbg->getExpression();
13053 // If a fragment is requested, update the expression.
13054 if (SizeInBits) {
13055 // When splitting a larger (e.g., sign-extended) value whose
13056 // lower bits are described with an SDDbgValue, do not attempt
13057 // to transfer the SDDbgValue to the upper bits.
13058 if (auto FI = Expr->getFragmentInfo())
13059 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13060 continue;
13061 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13062 SizeInBits);
13063 if (!Fragment)
13064 continue;
13065 Expr = *Fragment;
13066 }
13067
13068 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13069 // Clone the SDDbgValue and move it to To.
13070 SDDbgValue *Clone = getDbgValueList(
13071 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13072 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13073 Dbg->isVariadic());
13074 ClonedDVs.push_back(Clone);
13075
13076 if (InvalidateDbg) {
13077 // Invalidate value and indicate the SDDbgValue should not be emitted.
13078 Dbg->setIsInvalidated();
13079 Dbg->setIsEmitted();
13080 }
13081 }
13082
13083 for (SDDbgValue *Dbg : ClonedDVs) {
13084 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13085 "Transferred DbgValues should depend on the new SDNode");
13086 AddDbgValue(Dbg, false);
13087 }
13088}
13089
13091 if (!N.getHasDebugValue())
13092 return;
13093
13094 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13095 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13096 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13097 return SDDbgOperand::fromNode(Node, ResNo);
13098 };
13099
13101 for (auto *DV : GetDbgValues(&N)) {
13102 if (DV->isInvalidated())
13103 continue;
13104 switch (N.getOpcode()) {
13105 default:
13106 break;
13107 case ISD::ADD: {
13108 SDValue N0 = N.getOperand(0);
13109 SDValue N1 = N.getOperand(1);
13110 if (!isa<ConstantSDNode>(N0)) {
13111 bool RHSConstant = isa<ConstantSDNode>(N1);
13112 uint64_t Offset;
13113 if (RHSConstant)
13114 Offset = N.getConstantOperandVal(1);
13115 // We are not allowed to turn indirect debug values variadic, so
13116 // don't salvage those.
13117 if (!RHSConstant && DV->isIndirect())
13118 continue;
13119
13120 // Rewrite an ADD constant node into a DIExpression. Since we are
13121 // performing arithmetic to compute the variable's *value* in the
13122 // DIExpression, we need to mark the expression with a
13123 // DW_OP_stack_value.
13124 auto *DIExpr = DV->getExpression();
13125 auto NewLocOps = DV->copyLocationOps();
13126 bool Changed = false;
13127 size_t OrigLocOpsSize = NewLocOps.size();
13128 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13129 // We're not given a ResNo to compare against because the whole
13130 // node is going away. We know that any ISD::ADD only has one
13131 // result, so we can assume any node match is using the result.
13132 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13133 NewLocOps[i].getSDNode() != &N)
13134 continue;
13135 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13136 if (RHSConstant) {
13139 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13140 } else {
13141 // Convert to a variadic expression (if not already).
13142 // convertToVariadicExpression() returns a const pointer, so we use
13143 // a temporary const variable here.
13144 const auto *TmpDIExpr =
13148 ExprOps.push_back(NewLocOps.size());
13149 ExprOps.push_back(dwarf::DW_OP_plus);
13150 SDDbgOperand RHS =
13152 NewLocOps.push_back(RHS);
13153 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13154 }
13155 Changed = true;
13156 }
13157 (void)Changed;
13158 assert(Changed && "Salvage target doesn't use N");
13159
13160 bool IsVariadic =
13161 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13162
13163 auto AdditionalDependencies = DV->getAdditionalDependencies();
13164 SDDbgValue *Clone = getDbgValueList(
13165 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13166 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13167 ClonedDVs.push_back(Clone);
13168 DV->setIsInvalidated();
13169 DV->setIsEmitted();
13170 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13171 N0.getNode()->dumprFull(this);
13172 dbgs() << " into " << *DIExpr << '\n');
13173 }
13174 break;
13175 }
13176 case ISD::TRUNCATE: {
13177 SDValue N0 = N.getOperand(0);
13178 TypeSize FromSize = N0.getValueSizeInBits();
13179 TypeSize ToSize = N.getValueSizeInBits(0);
13180
13181 DIExpression *DbgExpression = DV->getExpression();
13182 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13183 auto NewLocOps = DV->copyLocationOps();
13184 bool Changed = false;
13185 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13186 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13187 NewLocOps[i].getSDNode() != &N)
13188 continue;
13189
13190 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13191 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13192 Changed = true;
13193 }
13194 assert(Changed && "Salvage target doesn't use N");
13195 (void)Changed;
13196
13197 SDDbgValue *Clone =
13198 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13199 DV->getAdditionalDependencies(), DV->isIndirect(),
13200 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13201
13202 ClonedDVs.push_back(Clone);
13203 DV->setIsInvalidated();
13204 DV->setIsEmitted();
13205 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13206 dbgs() << " into " << *DbgExpression << '\n');
13207 break;
13208 }
13209 }
13210 }
13211
13212 for (SDDbgValue *Dbg : ClonedDVs) {
13213 assert((!Dbg->getSDNodes().empty() ||
13214 llvm::any_of(Dbg->getLocationOps(),
13215 [&](const SDDbgOperand &Op) {
13216 return Op.getKind() == SDDbgOperand::FRAMEIX;
13217 })) &&
13218 "Salvaged DbgValue should depend on a new SDNode");
13219 AddDbgValue(Dbg, false);
13220 }
13221}
13222
13223/// Creates a SDDbgLabel node.
13225 const DebugLoc &DL, unsigned O) {
13226 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13227 "Expected inlined-at fields to agree");
13228 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13229}
13230
13231namespace {
13232
13233/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13234/// pointed to by a use iterator is deleted, increment the use iterator
13235/// so that it doesn't dangle.
13236///
13237class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13240
13241 void NodeDeleted(SDNode *N, SDNode *E) override {
13242 // Increment the iterator as needed.
13243 while (UI != UE && N == UI->getUser())
13244 ++UI;
13245 }
13246
13247public:
13248 RAUWUpdateListener(SelectionDAG &d,
13251 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13252};
13253
13254} // end anonymous namespace
13255
13256/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13257/// This can cause recursive merging of nodes in the DAG.
13258///
13259/// This version assumes From has a single result value.
13260///
13262 SDNode *From = FromN.getNode();
13263 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13264 "Cannot replace with this method!");
13265 assert(From != To.getNode() && "Cannot replace uses of with self");
13266
13267 // Preserve Debug Values
13268 transferDbgValues(FromN, To);
13269 // Preserve extra info.
13270 copyExtraInfo(From, To.getNode());
13271
13272 // Iterate over all the existing uses of From. New uses will be added
13273 // to the beginning of the use list, which we avoid visiting.
13274 // This specifically avoids visiting uses of From that arise while the
13275 // replacement is happening, because any such uses would be the result
13276 // of CSE: If an existing node looks like From after one of its operands
13277 // is replaced by To, we don't want to replace of all its users with To
13278 // too. See PR3018 for more info.
13279 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13280 RAUWUpdateListener Listener(*this, UI, UE);
13281 while (UI != UE) {
13282 SDNode *User = UI->getUser();
13283
13284 // This node is about to morph, remove its old self from the CSE maps.
13285 RemoveNodeFromCSEMaps(User);
13286
13287 // A user can appear in a use list multiple times, and when this
13288 // happens the uses are usually next to each other in the list.
13289 // To help reduce the number of CSE recomputations, process all
13290 // the uses of this user that we can find this way.
13291 do {
13292 SDUse &Use = *UI;
13293 ++UI;
13294 Use.set(To);
13295 if (To->isDivergent() != From->isDivergent())
13297 } while (UI != UE && UI->getUser() == User);
13298 // Now that we have modified User, add it back to the CSE maps. If it
13299 // already exists there, recursively merge the results together.
13300 AddModifiedNodeToCSEMaps(User);
13301 }
13302
13303 // If we just RAUW'd the root, take note.
13304 if (FromN == getRoot())
13305 setRoot(To);
13306}
13307
13308/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13309/// This can cause recursive merging of nodes in the DAG.
13310///
13311/// This version assumes that for each value of From, there is a
13312/// corresponding value in To in the same position with the same type.
13313///
13315#ifndef NDEBUG
13316 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13317 assert((!From->hasAnyUseOfValue(i) ||
13318 From->getValueType(i) == To->getValueType(i)) &&
13319 "Cannot use this version of ReplaceAllUsesWith!");
13320#endif
13321
13322 // Handle the trivial case.
13323 if (From == To)
13324 return;
13325
13326 // Preserve Debug Info. Only do this if there's a use.
13327 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13328 if (From->hasAnyUseOfValue(i)) {
13329 assert((i < To->getNumValues()) && "Invalid To location");
13330 transferDbgValues(SDValue(From, i), SDValue(To, i));
13331 }
13332 // Preserve extra info.
13333 copyExtraInfo(From, To);
13334
13335 // Iterate over just the existing users of From. See the comments in
13336 // the ReplaceAllUsesWith above.
13337 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13338 RAUWUpdateListener Listener(*this, UI, UE);
13339 while (UI != UE) {
13340 SDNode *User = UI->getUser();
13341
13342 // This node is about to morph, remove its old self from the CSE maps.
13343 RemoveNodeFromCSEMaps(User);
13344
13345 // A user can appear in a use list multiple times, and when this
13346 // happens the uses are usually next to each other in the list.
13347 // To help reduce the number of CSE recomputations, process all
13348 // the uses of this user that we can find this way.
13349 do {
13350 SDUse &Use = *UI;
13351 ++UI;
13352 Use.setNode(To);
13353 if (To->isDivergent() != From->isDivergent())
13355 } while (UI != UE && UI->getUser() == User);
13356
13357 // Now that we have modified User, add it back to the CSE maps. If it
13358 // already exists there, recursively merge the results together.
13359 AddModifiedNodeToCSEMaps(User);
13360 }
13361
13362 // If we just RAUW'd the root, take note.
13363 if (From == getRoot().getNode())
13364 setRoot(SDValue(To, getRoot().getResNo()));
13365}
13366
13367/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13368/// This can cause recursive merging of nodes in the DAG.
13369///
13370/// This version can replace From with any result values. To must match the
13371/// number and types of values returned by From.
13373 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13374 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13375
13376 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13377 // Preserve Debug Info.
13378 transferDbgValues(SDValue(From, i), To[i]);
13379 // Preserve extra info.
13380 copyExtraInfo(From, To[i].getNode());
13381 }
13382
13383 // Iterate over just the existing users of From. See the comments in
13384 // the ReplaceAllUsesWith above.
13385 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13386 RAUWUpdateListener Listener(*this, UI, UE);
13387 while (UI != UE) {
13388 SDNode *User = UI->getUser();
13389
13390 // This node is about to morph, remove its old self from the CSE maps.
13391 RemoveNodeFromCSEMaps(User);
13392
13393 // A user can appear in a use list multiple times, and when this happens the
13394 // uses are usually next to each other in the list. To help reduce the
13395 // number of CSE and divergence recomputations, process all the uses of this
13396 // user that we can find this way.
13397 bool To_IsDivergent = false;
13398 do {
13399 SDUse &Use = *UI;
13400 const SDValue &ToOp = To[Use.getResNo()];
13401 ++UI;
13402 Use.set(ToOp);
13403 if (ToOp.getValueType() != MVT::Other)
13404 To_IsDivergent |= ToOp->isDivergent();
13405 } while (UI != UE && UI->getUser() == User);
13406
13407 if (To_IsDivergent != From->isDivergent())
13409
13410 // Now that we have modified User, add it back to the CSE maps. If it
13411 // already exists there, recursively merge the results together.
13412 AddModifiedNodeToCSEMaps(User);
13413 }
13414
13415 // If we just RAUW'd the root, take note.
13416 if (From == getRoot().getNode())
13417 setRoot(SDValue(To[getRoot().getResNo()]));
13418}
13419
13420/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13421/// uses of other values produced by From.getNode() alone. The Deleted
13422/// vector is handled the same way as for ReplaceAllUsesWith.
13424 // Handle the really simple, really trivial case efficiently.
13425 if (From == To) return;
13426
13427 // Handle the simple, trivial, case efficiently.
13428 if (From.getNode()->getNumValues() == 1) {
13429 ReplaceAllUsesWith(From, To);
13430 return;
13431 }
13432
13433 // Preserve Debug Info.
13434 transferDbgValues(From, To);
13435 copyExtraInfo(From.getNode(), To.getNode());
13436
13437 // Iterate over just the existing users of From. See the comments in
13438 // the ReplaceAllUsesWith above.
13439 SDNode::use_iterator UI = From.getNode()->use_begin(),
13440 UE = From.getNode()->use_end();
13441 RAUWUpdateListener Listener(*this, UI, UE);
13442 while (UI != UE) {
13443 SDNode *User = UI->getUser();
13444 bool UserRemovedFromCSEMaps = false;
13445
13446 // A user can appear in a use list multiple times, and when this
13447 // happens the uses are usually next to each other in the list.
13448 // To help reduce the number of CSE recomputations, process all
13449 // the uses of this user that we can find this way.
13450 do {
13451 SDUse &Use = *UI;
13452
13453 // Skip uses of different values from the same node.
13454 if (Use.getResNo() != From.getResNo()) {
13455 ++UI;
13456 continue;
13457 }
13458
13459 // If this node hasn't been modified yet, it's still in the CSE maps,
13460 // so remove its old self from the CSE maps.
13461 if (!UserRemovedFromCSEMaps) {
13462 RemoveNodeFromCSEMaps(User);
13463 UserRemovedFromCSEMaps = true;
13464 }
13465
13466 ++UI;
13467 Use.set(To);
13468 if (To->isDivergent() != From->isDivergent())
13470 } while (UI != UE && UI->getUser() == User);
13471 // We are iterating over all uses of the From node, so if a use
13472 // doesn't use the specific value, no changes are made.
13473 if (!UserRemovedFromCSEMaps)
13474 continue;
13475
13476 // Now that we have modified User, add it back to the CSE maps. If it
13477 // already exists there, recursively merge the results together.
13478 AddModifiedNodeToCSEMaps(User);
13479 }
13480
13481 // If we just RAUW'd the root, take note.
13482 if (From == getRoot())
13483 setRoot(To);
13484}
13485
13486namespace {
13487
13488/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13489/// to record information about a use.
13490struct UseMemo {
13491 SDNode *User;
13492 unsigned Index;
13493 SDUse *Use;
13494};
13495
13496/// operator< - Sort Memos by User.
13497bool operator<(const UseMemo &L, const UseMemo &R) {
13498 return (intptr_t)L.User < (intptr_t)R.User;
13499}
13500
13501/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13502/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13503/// the node already has been taken care of recursively.
13504class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13505 SmallVectorImpl<UseMemo> &Uses;
13506
13507 void NodeDeleted(SDNode *N, SDNode *E) override {
13508 for (UseMemo &Memo : Uses)
13509 if (Memo.User == N)
13510 Memo.User = nullptr;
13511 }
13512
13513public:
13514 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13515 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13516};
13517
13518} // end anonymous namespace
13519
13520/// Return true if a glue output should propagate divergence information.
13522 switch (Node->getOpcode()) {
13523 case ISD::CopyFromReg:
13524 case ISD::CopyToReg:
13525 return false;
13526 default:
13527 return true;
13528 }
13529
13530 llvm_unreachable("covered opcode switch");
13531}
13532
13534 if (TLI->isSDNodeAlwaysUniform(N)) {
13535 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13536 "Conflicting divergence information!");
13537 return false;
13538 }
13539 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13540 return true;
13541 for (const auto &Op : N->ops()) {
13542 EVT VT = Op.getValueType();
13543
13544 // Skip Chain. It does not carry divergence.
13545 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13546 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13547 return true;
13548 }
13549 return false;
13550}
13551
13553 SmallVector<SDNode *, 16> Worklist(1, N);
13554 do {
13555 N = Worklist.pop_back_val();
13556 bool IsDivergent = calculateDivergence(N);
13557 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13558 N->SDNodeBits.IsDivergent = IsDivergent;
13559 llvm::append_range(Worklist, N->users());
13560 }
13561 } while (!Worklist.empty());
13562}
13563
13564void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13566 Order.reserve(AllNodes.size());
13567 for (auto &N : allnodes()) {
13568 unsigned NOps = N.getNumOperands();
13569 Degree[&N] = NOps;
13570 if (0 == NOps)
13571 Order.push_back(&N);
13572 }
13573 for (size_t I = 0; I != Order.size(); ++I) {
13574 SDNode *N = Order[I];
13575 for (auto *U : N->users()) {
13576 unsigned &UnsortedOps = Degree[U];
13577 if (0 == --UnsortedOps)
13578 Order.push_back(U);
13579 }
13580 }
13581}
13582
13583#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13584void SelectionDAG::VerifyDAGDivergence() {
13585 std::vector<SDNode *> TopoOrder;
13586 CreateTopologicalOrder(TopoOrder);
13587 for (auto *N : TopoOrder) {
13588 assert(calculateDivergence(N) == N->isDivergent() &&
13589 "Divergence bit inconsistency detected");
13590 }
13591}
13592#endif
13593
13594/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13595/// uses of other values produced by From.getNode() alone. The same value
13596/// may appear in both the From and To list. The Deleted vector is
13597/// handled the same way as for ReplaceAllUsesWith.
13599 const SDValue *To,
13600 unsigned Num){
13601 // Handle the simple, trivial case efficiently.
13602 if (Num == 1)
13603 return ReplaceAllUsesOfValueWith(*From, *To);
13604
13605 transferDbgValues(*From, *To);
13606 copyExtraInfo(From->getNode(), To->getNode());
13607
13608 // Read up all the uses and make records of them. This helps
13609 // processing new uses that are introduced during the
13610 // replacement process.
13612 for (unsigned i = 0; i != Num; ++i) {
13613 unsigned FromResNo = From[i].getResNo();
13614 SDNode *FromNode = From[i].getNode();
13615 for (SDUse &Use : FromNode->uses()) {
13616 if (Use.getResNo() == FromResNo) {
13617 UseMemo Memo = {Use.getUser(), i, &Use};
13618 Uses.push_back(Memo);
13619 }
13620 }
13621 }
13622
13623 // Sort the uses, so that all the uses from a given User are together.
13625 RAUOVWUpdateListener Listener(*this, Uses);
13626
13627 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13628 UseIndex != UseIndexEnd; ) {
13629 // We know that this user uses some value of From. If it is the right
13630 // value, update it.
13631 SDNode *User = Uses[UseIndex].User;
13632 // If the node has been deleted by recursive CSE updates when updating
13633 // another node, then just skip this entry.
13634 if (User == nullptr) {
13635 ++UseIndex;
13636 continue;
13637 }
13638
13639 // This node is about to morph, remove its old self from the CSE maps.
13640 RemoveNodeFromCSEMaps(User);
13641
13642 // The Uses array is sorted, so all the uses for a given User
13643 // are next to each other in the list.
13644 // To help reduce the number of CSE recomputations, process all
13645 // the uses of this user that we can find this way.
13646 do {
13647 unsigned i = Uses[UseIndex].Index;
13648 SDUse &Use = *Uses[UseIndex].Use;
13649 ++UseIndex;
13650
13651 Use.set(To[i]);
13652 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13653
13654 // Now that we have modified User, add it back to the CSE maps. If it
13655 // already exists there, recursively merge the results together.
13656 AddModifiedNodeToCSEMaps(User);
13657 }
13658}
13659
13660/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13661/// based on their topological order. It returns the maximum id and a vector
13662/// of the SDNodes* in assigned order by reference.
13664 unsigned DAGSize = 0;
13665
13666 // SortedPos tracks the progress of the algorithm. Nodes before it are
13667 // sorted, nodes after it are unsorted. When the algorithm completes
13668 // it is at the end of the list.
13669 allnodes_iterator SortedPos = allnodes_begin();
13670
13671 // Visit all the nodes. Move nodes with no operands to the front of
13672 // the list immediately. Annotate nodes that do have operands with their
13673 // operand count. Before we do this, the Node Id fields of the nodes
13674 // may contain arbitrary values. After, the Node Id fields for nodes
13675 // before SortedPos will contain the topological sort index, and the
13676 // Node Id fields for nodes At SortedPos and after will contain the
13677 // count of outstanding operands.
13679 checkForCycles(&N, this);
13680 unsigned Degree = N.getNumOperands();
13681 if (Degree == 0) {
13682 // A node with no uses, add it to the result array immediately.
13683 N.setNodeId(DAGSize++);
13684 allnodes_iterator Q(&N);
13685 if (Q != SortedPos)
13686 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13687 assert(SortedPos != AllNodes.end() && "Overran node list");
13688 ++SortedPos;
13689 } else {
13690 // Temporarily use the Node Id as scratch space for the degree count.
13691 N.setNodeId(Degree);
13692 }
13693 }
13694
13695 // Visit all the nodes. As we iterate, move nodes into sorted order,
13696 // such that by the time the end is reached all nodes will be sorted.
13697 for (SDNode &Node : allnodes()) {
13698 SDNode *N = &Node;
13699 checkForCycles(N, this);
13700 // N is in sorted position, so all its uses have one less operand
13701 // that needs to be sorted.
13702 for (SDNode *P : N->users()) {
13703 unsigned Degree = P->getNodeId();
13704 assert(Degree != 0 && "Invalid node degree");
13705 --Degree;
13706 if (Degree == 0) {
13707 // All of P's operands are sorted, so P may sorted now.
13708 P->setNodeId(DAGSize++);
13709 if (P->getIterator() != SortedPos)
13710 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13711 assert(SortedPos != AllNodes.end() && "Overran node list");
13712 ++SortedPos;
13713 } else {
13714 // Update P's outstanding operand count.
13715 P->setNodeId(Degree);
13716 }
13717 }
13718 if (Node.getIterator() == SortedPos) {
13719#ifndef NDEBUG
13721 SDNode *S = &*++I;
13722 dbgs() << "Overran sorted position:\n";
13723 S->dumprFull(this); dbgs() << "\n";
13724 dbgs() << "Checking if this is due to cycles\n";
13725 checkForCycles(this, true);
13726#endif
13727 llvm_unreachable(nullptr);
13728 }
13729 }
13730
13731 assert(SortedPos == AllNodes.end() &&
13732 "Topological sort incomplete!");
13733 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13734 "First node in topological sort is not the entry token!");
13735 assert(AllNodes.front().getNodeId() == 0 &&
13736 "First node in topological sort has non-zero id!");
13737 assert(AllNodes.front().getNumOperands() == 0 &&
13738 "First node in topological sort has operands!");
13739 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13740 "Last node in topologic sort has unexpected id!");
13741 assert(AllNodes.back().use_empty() &&
13742 "Last node in topologic sort has users!");
13743 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13744 return DAGSize;
13745}
13746
13748 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13749 SortedNodes.clear();
13750 // Node -> remaining number of outstanding operands.
13751 DenseMap<const SDNode *, unsigned> RemainingOperands;
13752
13753 // Put nodes without any operands into SortedNodes first.
13754 for (const SDNode &N : allnodes()) {
13755 checkForCycles(&N, this);
13756 unsigned NumOperands = N.getNumOperands();
13757 if (NumOperands == 0)
13758 SortedNodes.push_back(&N);
13759 else
13760 // Record their total number of outstanding operands.
13761 RemainingOperands[&N] = NumOperands;
13762 }
13763
13764 // A node is pushed into SortedNodes when all of its operands (predecessors in
13765 // the graph) are also in SortedNodes.
13766 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13767 const SDNode *N = SortedNodes[i];
13768 for (const SDNode *U : N->users()) {
13769 // HandleSDNode is never part of a DAG and therefore has no entry in
13770 // RemainingOperands.
13771 if (U->getOpcode() == ISD::HANDLENODE)
13772 continue;
13773 unsigned &NumRemOperands = RemainingOperands[U];
13774 assert(NumRemOperands && "Invalid number of remaining operands");
13775 --NumRemOperands;
13776 if (!NumRemOperands)
13777 SortedNodes.push_back(U);
13778 }
13779 }
13780
13781 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13782 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13783 "First node in topological sort is not the entry token");
13784 assert(SortedNodes.front()->getNumOperands() == 0 &&
13785 "First node in topological sort has operands");
13786}
13787
13788/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13789/// value is produced by SD.
13790void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13791 for (SDNode *SD : DB->getSDNodes()) {
13792 if (!SD)
13793 continue;
13794 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13795 SD->setHasDebugValue(true);
13796 }
13797 DbgInfo->add(DB, isParameter);
13798}
13799
13800void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13801
13803 SDValue NewMemOpChain) {
13804 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13805 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13806 // The new memory operation must have the same position as the old load in
13807 // terms of memory dependency. Create a TokenFactor for the old load and new
13808 // memory operation and update uses of the old load's output chain to use that
13809 // TokenFactor.
13810 if (OldChain == NewMemOpChain || OldChain.use_empty())
13811 return NewMemOpChain;
13812
13813 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13814 OldChain, NewMemOpChain);
13815 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13816 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13817 return TokenFactor;
13818}
13819
13821 SDValue NewMemOp) {
13822 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13823 SDValue OldChain = SDValue(OldLoad, 1);
13824 SDValue NewMemOpChain = NewMemOp.getValue(1);
13825 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13826}
13827
13829 Function **OutFunction) {
13830 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13831
13832 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13833 auto *Module = MF->getFunction().getParent();
13834 auto *Function = Module->getFunction(Symbol);
13835
13836 if (OutFunction != nullptr)
13837 *OutFunction = Function;
13838
13839 if (Function != nullptr) {
13840 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13841 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13842 }
13843
13844 std::string ErrorStr;
13845 raw_string_ostream ErrorFormatter(ErrorStr);
13846 ErrorFormatter << "Undefined external symbol ";
13847 ErrorFormatter << '"' << Symbol << '"';
13848 report_fatal_error(Twine(ErrorStr));
13849}
13850
13851//===----------------------------------------------------------------------===//
13852// SDNode Class
13853//===----------------------------------------------------------------------===//
13854
13857 return Const != nullptr && Const->isZero();
13858}
13859
13861 return V.isUndef() || isNullConstant(V);
13862}
13863
13866 return Const != nullptr && Const->isZero() && !Const->isNegative();
13867}
13868
13871 return Const != nullptr && Const->isAllOnes();
13872}
13873
13876 return Const != nullptr && Const->isOne();
13877}
13878
13881 return Const != nullptr && Const->isMinSignedValue();
13882}
13883
13885 SDValue V, unsigned OperandNo,
13886 unsigned Depth) const {
13887 APInt DemandedElts = getDemandAllEltsMask(V);
13888 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13889}
13890
13892 SDValue V, const APInt &DemandedElts,
13893 unsigned OperandNo, unsigned Depth) const {
13894 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13895 // TODO: Target-specific opcodes could be added.
13896 if (V.getValueType().isInteger()) {
13897 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13898 if (Known.isConstant()) {
13899 const APInt &Const = Known.getConstant();
13900 switch (Opcode) {
13901 case ISD::ADD:
13902 case ISD::OR:
13903 case ISD::XOR:
13904 case ISD::UMAX:
13905 return Const.isZero();
13906 case ISD::MUL:
13907 return Const.isOne();
13908 case ISD::AND:
13909 case ISD::UMIN:
13910 return Const.isAllOnes();
13911 case ISD::SMAX:
13912 return Const.isMinSignedValue();
13913 case ISD::SMIN:
13914 return Const.isMaxSignedValue();
13915 case ISD::SUB:
13916 case ISD::SHL:
13917 case ISD::SRA:
13918 case ISD::SRL:
13919 return OperandNo == 1 && Const.isZero();
13920 case ISD::UDIV:
13921 case ISD::SDIV:
13922 return OperandNo == 1 && Const.isOne();
13923 }
13924 }
13925 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13926 switch (Opcode) {
13927 case ISD::FADD:
13928 return ConstFP->isZero() &&
13929 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13930 case ISD::FSUB:
13931 return OperandNo == 1 && ConstFP->isZero() &&
13932 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13933 case ISD::FMUL:
13934 return ConstFP->isOne();
13935 case ISD::FDIV:
13936 return OperandNo == 1 && ConstFP->isOne();
13937 case ISD::FMINNUM:
13938 case ISD::FMAXNUM:
13939 case ISD::FMINIMUMNUM:
13940 case ISD::FMAXIMUMNUM: {
13941 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
13942 // depending on fast-math flags (FMF).
13943 EVT VT = V.getValueType();
13944 const fltSemantics &Semantics = VT.getFltSemantics();
13945 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13946 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13947 : APFloat::getLargest(Semantics);
13948 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
13949 NeutralAF.changeSign();
13950
13951 return ConstFP->isExactlyValue(NeutralAF);
13952 }
13953 case ISD::FMINIMUM:
13954 case ISD::FMAXIMUM: {
13955 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
13956 const APFloat &VAPF = ConstFP->getValueAPF();
13957 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
13958 if (Flags.hasNoInfs())
13959 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
13960 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
13961 }
13962 }
13963 }
13964 return false;
13965}
13966
13968 while (V.getOpcode() == ISD::BITCAST)
13969 V = V.getOperand(0);
13970 return V;
13971}
13972
13974 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
13975 V = V.getOperand(0);
13976 return V;
13977}
13978
13980 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13981 V = V.getOperand(0);
13982 return V;
13983}
13984
13986 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13987 SDValue InVec = V.getOperand(0);
13988 SDValue EltNo = V.getOperand(2);
13989 EVT VT = InVec.getValueType();
13990 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
13991 if (IndexC && VT.isFixedLengthVector() &&
13992 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
13993 !DemandedElts[IndexC->getZExtValue()]) {
13994 V = InVec;
13995 continue;
13996 }
13997 break;
13998 }
13999 return V;
14000}
14001
14003 while (V.getOpcode() == ISD::TRUNCATE)
14004 V = V.getOperand(0);
14005 return V;
14006}
14007
14008bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14009 if (V.getOpcode() != ISD::XOR)
14010 return false;
14011 V = peekThroughBitcasts(V.getOperand(1));
14012 unsigned NumBits = V.getScalarValueSizeInBits();
14013 ConstantSDNode *C =
14014 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14015 return C && (C->getAPIntValue().countr_one() >= NumBits);
14016}
14017
14019 bool AllowTruncation) {
14020 APInt DemandedElts = getDemandAllEltsMask(N);
14021 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14022}
14023
14025 bool AllowUndefs,
14026 bool AllowTruncation) {
14028 return CN;
14029
14030 // SplatVectors can truncate their operands. Ignore that case here unless
14031 // AllowTruncation is set.
14032 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14033 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14034 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14035 EVT CVT = CN->getValueType(0);
14036 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14037 if (AllowTruncation || CVT == VecEltVT)
14038 return CN;
14039 }
14040 }
14041
14043 BitVector UndefElements;
14044 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14045
14046 // BuildVectors can truncate their operands. Ignore that case here unless
14047 // AllowTruncation is set.
14048 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14049 if (CN && (UndefElements.none() || AllowUndefs)) {
14050 EVT CVT = CN->getValueType(0);
14051 EVT NSVT = N.getValueType().getScalarType();
14052 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14053 if (AllowTruncation || (CVT == NSVT))
14054 return CN;
14055 }
14056 }
14057
14058 if (N.getOpcode() == ISD::MERGE_VALUES)
14059 return isConstOrConstSplat(N.getOperand(N.getResNo()), DemandedElts,
14060 AllowUndefs, AllowTruncation);
14061
14062 return nullptr;
14063}
14064
14066 APInt DemandedElts = getDemandAllEltsMask(N);
14067 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14068}
14069
14071 const APInt &DemandedElts,
14072 bool AllowUndefs) {
14074 return CN;
14075
14077 BitVector UndefElements;
14078 ConstantFPSDNode *CN =
14079 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14080 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14081 if (CN && (UndefElements.none() || AllowUndefs))
14082 return CN;
14083 }
14084
14085 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14086 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14087 return CN;
14088
14089 return nullptr;
14090}
14091
14092bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14093 // TODO: may want to use peekThroughBitcast() here.
14094 ConstantSDNode *C =
14095 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14096 return C && C->isZero();
14097}
14098
14099bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14100 ConstantSDNode *C =
14101 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14102 return C && C->isOne();
14103}
14104
14105bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14106 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14107 return C && C->isOne();
14108}
14109
14110bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14112 unsigned BitWidth = N.getScalarValueSizeInBits();
14113 ConstantSDNode *C =
14114 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14115 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14116}
14117
14118bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14120 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14121 return C && C->isZero();
14122}
14123
14124bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14125 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14126 return C && C->isZero();
14127}
14128
14132
14134 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14136 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14137 bool IsVolatile = false;
14138 bool IsNonTemporal = false;
14139 bool IsDereferenceable = true;
14140 bool IsInvariant = true;
14141 for (const MachineMemOperand *MMO : memoperands()) {
14142 IsVolatile |= MMO->isVolatile();
14143 IsNonTemporal |= MMO->isNonTemporal();
14144 IsDereferenceable &= MMO->isDereferenceable();
14145 IsInvariant &= MMO->isInvariant();
14146 }
14147 MemSDNodeBits.IsVolatile = IsVolatile;
14148 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14149 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14150 MemSDNodeBits.IsInvariant = IsInvariant;
14151
14152 // For the single-MMO case, we check here that the size of the memory operand
14153 // fits within the size of the MMO. This is because the MMO might indicate
14154 // only a possible address range instead of specifying the affected memory
14155 // addresses precisely.
14158 getMemOperand()->getSize().getValue())) &&
14159 "Size mismatch!");
14160}
14161
14162namespace {
14163
14164 struct EVTArray {
14165 std::vector<EVT> VTs;
14166
14167 EVTArray() {
14168 VTs.reserve(MVT::VALUETYPE_SIZE);
14169 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14170 VTs.push_back(MVT((MVT::SimpleValueType)i));
14171 }
14172 };
14173
14174} // end anonymous namespace
14175
14176/// getValueTypeList - Return a pointer to the specified value type.
14177///
14178const EVT *SDNode::getValueTypeList(MVT VT) {
14179 static EVTArray SimpleVTArray;
14180
14181 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14182 return &SimpleVTArray.VTs[VT.SimpleTy];
14183}
14184
14185/// hasAnyUseOfValue - Return true if there are any use of the indicated
14186/// value. This method ignores uses of other values defined by this operation.
14187bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14188 assert(Value < getNumValues() && "Bad value!");
14189
14190 for (SDUse &U : uses())
14191 if (U.getResNo() == Value)
14192 return true;
14193
14194 return false;
14195}
14196
14197/// isOnlyUserOf - Return true if this node is the only use of N.
14198bool SDNode::isOnlyUserOf(const SDNode *N) const {
14199 bool Seen = false;
14200 for (const SDNode *User : N->users()) {
14201 if (User == this)
14202 Seen = true;
14203 else
14204 return false;
14205 }
14206
14207 return Seen;
14208}
14209
14210/// Return true if the only users of N are contained in Nodes.
14212 bool Seen = false;
14213 for (const SDNode *User : N->users()) {
14214 if (llvm::is_contained(Nodes, User))
14215 Seen = true;
14216 else
14217 return false;
14218 }
14219
14220 return Seen;
14221}
14222
14223/// Return true if the referenced return value is an operand of N.
14224bool SDValue::isOperandOf(const SDNode *N) const {
14225 return is_contained(N->op_values(), *this);
14226}
14227
14228bool SDNode::isOperandOf(const SDNode *N) const {
14229 return any_of(N->op_values(),
14230 [this](SDValue Op) { return this == Op.getNode(); });
14231}
14232
14233/// reachesChainWithoutSideEffects - Return true if this operand (which must
14234/// be a chain) reaches the specified operand without crossing any
14235/// side-effecting instructions on any chain path. In practice, this looks
14236/// through token factors and non-volatile loads. In order to remain efficient,
14237/// this only looks a couple of nodes in, it does not do an exhaustive search.
14238///
14239/// Note that we only need to examine chains when we're searching for
14240/// side-effects; SelectionDAG requires that all side-effects are represented
14241/// by chains, even if another operand would force a specific ordering. This
14242/// constraint is necessary to allow transformations like splitting loads.
14244 unsigned Depth) const {
14245 if (*this == Dest) return true;
14246
14247 // Don't search too deeply, we just want to be able to see through
14248 // TokenFactor's etc.
14249 if (Depth == 0) return false;
14250
14251 // If this is a token factor, all inputs to the TF happen in parallel.
14252 if (getOpcode() == ISD::TokenFactor) {
14253 // First, try a shallow search.
14254 if (is_contained((*this)->ops(), Dest)) {
14255 // We found the chain we want as an operand of this TokenFactor.
14256 // Essentially, we reach the chain without side-effects if we could
14257 // serialize the TokenFactor into a simple chain of operations with
14258 // Dest as the last operation. This is automatically true if the
14259 // chain has one use: there are no other ordering constraints.
14260 // If the chain has more than one use, we give up: some other
14261 // use of Dest might force a side-effect between Dest and the current
14262 // node.
14263 if (Dest.hasOneUse())
14264 return true;
14265 }
14266 // Next, try a deep search: check whether every operand of the TokenFactor
14267 // reaches Dest.
14268 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14269 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14270 });
14271 }
14272
14273 // Loads don't have side effects, look through them.
14274 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14275 if (Ld->isUnordered())
14276 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14277 }
14278 return false;
14279}
14280
14281bool SDNode::hasPredecessor(const SDNode *N) const {
14284 Worklist.push_back(this);
14285 return hasPredecessorHelper(N, Visited, Worklist);
14286}
14287
14289 this->Flags &= Flags;
14290}
14291
14292SDValue
14294 ArrayRef<ISD::NodeType> CandidateBinOps,
14295 bool AllowPartials) {
14296 // The pattern must end in an extract from index 0.
14297 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14298 !isNullConstant(Extract->getOperand(1)))
14299 return SDValue();
14300
14301 // Match against one of the candidate binary ops.
14302 SDValue Op = Extract->getOperand(0);
14303 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14304 return Op.getOpcode() == unsigned(BinOp);
14305 }))
14306 return SDValue();
14307
14308 // Floating-point reductions may require relaxed constraints on the final step
14309 // of the reduction because they may reorder intermediate operations.
14310 unsigned CandidateBinOp = Op.getOpcode();
14311 if (Op.getValueType().isFloatingPoint()) {
14312 SDNodeFlags Flags = Op->getFlags();
14313 switch (CandidateBinOp) {
14314 case ISD::FADD:
14315 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14316 return SDValue();
14317 break;
14318 default:
14319 llvm_unreachable("Unhandled FP opcode for binop reduction");
14320 }
14321 }
14322
14323 // Matching failed - attempt to see if we did enough stages that a partial
14324 // reduction from a subvector is possible.
14325 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14326 if (!AllowPartials || !Op)
14327 return SDValue();
14328 EVT OpVT = Op.getValueType();
14329 EVT OpSVT = OpVT.getScalarType();
14330 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14331 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14333 return SDValue();
14334 BinOp = (ISD::NodeType)CandidateBinOp;
14335 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14336 };
14337
14338 // At each stage, we're looking for something that looks like:
14339 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14340 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14341 // i32 undef, i32 undef, i32 undef, i32 undef>
14342 // %a = binop <8 x i32> %op, %s
14343 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14344 // we expect something like:
14345 // <4,5,6,7,u,u,u,u>
14346 // <2,3,u,u,u,u,u,u>
14347 // <1,u,u,u,u,u,u,u>
14348 // While a partial reduction match would be:
14349 // <2,3,u,u,u,u,u,u>
14350 // <1,u,u,u,u,u,u,u>
14351 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14352 SDValue PrevOp;
14353 for (unsigned i = 0; i < Stages; ++i) {
14354 unsigned MaskEnd = (1 << i);
14355
14356 if (Op.getOpcode() != CandidateBinOp)
14357 return PartialReduction(PrevOp, MaskEnd);
14358
14359 SDValue Op0 = Op.getOperand(0);
14360 SDValue Op1 = Op.getOperand(1);
14361
14363 if (Shuffle) {
14364 Op = Op1;
14365 } else {
14366 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14367 Op = Op0;
14368 }
14369
14370 // The first operand of the shuffle should be the same as the other operand
14371 // of the binop.
14372 if (!Shuffle || Shuffle->getOperand(0) != Op)
14373 return PartialReduction(PrevOp, MaskEnd);
14374
14375 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14376 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14377 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14378 return PartialReduction(PrevOp, MaskEnd);
14379
14380 PrevOp = Op;
14381 }
14382
14383 // Handle subvector reductions, which tend to appear after the shuffle
14384 // reduction stages.
14385 while (Op.getOpcode() == CandidateBinOp) {
14386 unsigned NumElts = Op.getValueType().getVectorNumElements();
14387 SDValue Op0 = Op.getOperand(0);
14388 SDValue Op1 = Op.getOperand(1);
14389 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14391 Op0.getOperand(0) != Op1.getOperand(0))
14392 break;
14393 SDValue Src = Op0.getOperand(0);
14394 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14395 if (NumSrcElts != (2 * NumElts))
14396 break;
14397 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14398 Op1.getConstantOperandAPInt(1) == NumElts) &&
14399 !(Op1.getConstantOperandAPInt(1) == 0 &&
14400 Op0.getConstantOperandAPInt(1) == NumElts))
14401 break;
14402 Op = Src;
14403 }
14404
14405 BinOp = (ISD::NodeType)CandidateBinOp;
14406 return Op;
14407}
14408
14410 EVT VT = N->getValueType(0);
14411 EVT EltVT = VT.getVectorElementType();
14412 unsigned NE = getMaxRuntimeNumElements(VT);
14413
14414 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14415 reportFatalUsageError("Cannot unroll scalable vector!");
14416
14417 assert(NE && "Nothing to unroll!");
14418 SDLoc dl(N);
14419
14420 // If ResNE is 0, fully unroll the vector op.
14421 if (ResNE == 0)
14422 ResNE = NE;
14423 else if (NE > ResNE)
14424 NE = ResNE;
14425
14426 if (N->getNumValues() == 2) {
14427 SmallVector<SDValue, 8> Scalars0, Scalars1;
14428 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14429 EVT VT1 = N->getValueType(1);
14430 EVT EltVT1 = VT1.getVectorElementType();
14431
14432 unsigned i;
14433 for (i = 0; i != NE; ++i) {
14434 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14435 SDValue Operand = N->getOperand(j);
14436 EVT OperandVT = Operand.getValueType();
14437
14438 // A vector operand; extract a single element.
14439 EVT OperandEltVT = OperandVT.getVectorElementType();
14440 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14441 }
14442
14443 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14444 Scalars0.push_back(EltOp);
14445 Scalars1.push_back(EltOp.getValue(1));
14446 }
14447
14448 for (; i < ResNE; ++i) {
14449 Scalars0.push_back(getUNDEF(EltVT));
14450 Scalars1.push_back(getUNDEF(EltVT1));
14451 }
14452
14454 : ElementCount::getFixed(ResNE);
14455 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14456 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14457 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14458 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14459 return getMergeValues({Vec0, Vec1}, dl);
14460 }
14461
14462 assert(N->getNumValues() == 1 &&
14463 "Can't unroll a vector with multiple results!");
14464
14466 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14467
14468 unsigned i;
14469 for (i= 0; i != NE; ++i) {
14470 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14471 SDValue Operand = N->getOperand(j);
14472 EVT OperandVT = Operand.getValueType();
14473 if (OperandVT.isVector()) {
14474 // A vector operand; extract a single element.
14475 EVT OperandEltVT = OperandVT.getVectorElementType();
14476 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14477 } else {
14478 // A scalar operand; just use it as is.
14479 Operands[j] = Operand;
14480 }
14481 }
14482
14483 switch (N->getOpcode()) {
14484 default: {
14485 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14486 N->getFlags()));
14487 break;
14488 }
14489 case ISD::VSELECT:
14490 Scalars.push_back(
14491 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14492 break;
14493 case ISD::SHL:
14494 case ISD::SRA:
14495 case ISD::SRL:
14496 case ISD::ROTL:
14497 case ISD::ROTR:
14498 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14500 Operands[1])));
14501 break;
14503 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14504 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14505 Operands[0],
14506 getValueType(ExtVT)));
14507 break;
14508 }
14509 case ISD::ADDRSPACECAST: {
14510 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14511 Scalars.push_back(
14512 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14513 ASC->getDestAddressSpace(), ASC->getFlags()));
14514 break;
14515 }
14516 }
14517 }
14518
14519 for (; i < ResNE; ++i)
14520 Scalars.push_back(getUNDEF(EltVT));
14521
14522 EVT VecVT = VT.isScalableVector()
14523 ? VT
14524 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14525 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14526}
14527
14528std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14529 SDNode *N, unsigned ResNE) {
14530 unsigned Opcode = N->getOpcode();
14531 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14532 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14533 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14534 "Expected an overflow opcode");
14535
14536 EVT ResVT = N->getValueType(0);
14537 EVT OvVT = N->getValueType(1);
14538 EVT ResEltVT = ResVT.getVectorElementType();
14539 EVT OvEltVT = OvVT.getVectorElementType();
14540 SDLoc dl(N);
14541
14542 // If ResNE is 0, fully unroll the vector op.
14543 unsigned NE = ResVT.getVectorNumElements();
14544 if (ResNE == 0)
14545 ResNE = NE;
14546 else if (NE > ResNE)
14547 NE = ResNE;
14548
14549 SmallVector<SDValue, 8> LHSScalars;
14550 SmallVector<SDValue, 8> RHSScalars;
14551 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14552 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14553
14554 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14555 SDVTList VTs = getVTList(ResEltVT, SVT);
14556 SmallVector<SDValue, 8> ResScalars;
14557 SmallVector<SDValue, 8> OvScalars;
14558 for (unsigned i = 0; i < NE; ++i) {
14559 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14560 SDValue Ov =
14561 getSelect(dl, OvEltVT, Res.getValue(1),
14562 getBoolConstant(true, dl, OvEltVT, ResVT),
14563 getConstant(0, dl, OvEltVT));
14564
14565 ResScalars.push_back(Res);
14566 OvScalars.push_back(Ov);
14567 }
14568
14569 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14570 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14571
14572 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14573 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14574 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14575 getBuildVector(NewOvVT, dl, OvScalars));
14576}
14577
14580 unsigned Bytes, int Dist,
14581 const SelectionDAG &DAG) {
14582 if (LS->isVolatile() || Base->isVolatile())
14583 return false;
14584 // TODO: probably too restrictive for atomics, revisit
14585 if (!LS->isSimple())
14586 return false;
14587 if (LS->isIndexed() || Base->isIndexed())
14588 return false;
14589 if (LS->getChain() != Base->getChain())
14590 return false;
14591 EVT VT = LS->getMemoryVT();
14592 if (VT.getSizeInBits() / 8 != Bytes)
14593 return false;
14594
14595 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14596 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14597
14598 int64_t Offset = 0;
14599 if (BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14600 return (Dist * (int64_t)Bytes == Offset);
14601 return false;
14602}
14603
14606 unsigned Bytes,
14607 int Dist) const {
14608 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14609}
14610
14613 unsigned Bytes,
14614 int Dist) const {
14615 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14616}
14617
14618/// InferPtrAlignment - Infer alignment of a load / store address. Return
14619/// std::nullopt if it cannot be inferred.
14621 // If this is a GlobalAddress + cst, return the alignment.
14622 const GlobalValue *GV = nullptr;
14623 int64_t GVOffset = 0;
14624 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14625 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14626 KnownBits Known(PtrWidth);
14628 unsigned AlignBits = Known.countMinTrailingZeros();
14629 if (AlignBits)
14630 return commonAlignment(Align::fromLog2(std::min(31U, AlignBits)),
14631 GVOffset);
14632 }
14633
14634 // If this is a direct reference to a stack slot, use information about the
14635 // stack slot's alignment.
14636 int FrameIdx = INT_MIN;
14637 int64_t FrameOffset = 0;
14639 FrameIdx = FI->getIndex();
14640 } else if (isBaseWithConstantOffset(Ptr) &&
14642 // Handle FI+Cst
14643 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14644 FrameOffset = Ptr.getConstantOperandVal(1);
14645 }
14646
14647 if (FrameIdx != INT_MIN) {
14649 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14650 }
14651
14652 return std::nullopt;
14653}
14654
14655/// Split the scalar node with EXTRACT_ELEMENT using the provided
14656/// VTs and return the low/high part.
14657std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14658 const SDLoc &DL,
14659 const EVT &LoVT,
14660 const EVT &HiVT) {
14661 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14662 "Split node must be a scalar type");
14663 SDValue Lo =
14665 SDValue Hi =
14667 return std::make_pair(Lo, Hi);
14668}
14669
14670/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14671/// which is split (or expanded) into two not necessarily identical pieces.
14672std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14673 // Currently all types are split in half.
14674 EVT LoVT, HiVT;
14675 if (!VT.isVector())
14676 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14677 else
14678 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14679
14680 return std::make_pair(LoVT, HiVT);
14681}
14682
14683/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14684/// type, dependent on an enveloping VT that has been split into two identical
14685/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14686std::pair<EVT, EVT>
14688 bool *HiIsEmpty) const {
14689 EVT EltTp = VT.getVectorElementType();
14690 // Examples:
14691 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14692 // custom VL=9 with enveloping VL=8/8 yields 8/1
14693 // custom VL=10 with enveloping VL=8/8 yields 8/2
14694 // etc.
14695 ElementCount VTNumElts = VT.getVectorElementCount();
14696 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14697 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14698 "Mixing fixed width and scalable vectors when enveloping a type");
14699 EVT LoVT, HiVT;
14700 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14701 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14702 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14703 *HiIsEmpty = false;
14704 } else {
14705 // Flag that hi type has zero storage size, but return split envelop type
14706 // (this would be easier if vector types with zero elements were allowed).
14707 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14708 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14709 *HiIsEmpty = true;
14710 }
14711 return std::make_pair(LoVT, HiVT);
14712}
14713
14714/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14715/// low/high part.
14716std::pair<SDValue, SDValue>
14717SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14718 const EVT &HiVT) {
14719 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14720 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14721 "Splitting vector with an invalid mixture of fixed and scalable "
14722 "vector types");
14724 N.getValueType().getVectorMinNumElements() &&
14725 "More vector elements requested than available!");
14726 SDValue Lo, Hi;
14727 Lo = getExtractSubvector(DL, LoVT, N, 0);
14728 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14729 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14730 // IDX with the runtime scaling factor of the result vector type. For
14731 // fixed-width result vectors, that runtime scaling factor is 1.
14733 return std::make_pair(Lo, Hi);
14734}
14735
14736std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14737 const SDLoc &DL) {
14738 // Split the vector length parameter.
14739 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14740 EVT VT = N.getValueType();
14742 "Expecting the mask to be an evenly-sized vector");
14743 SDValue HalfNumElts = getElementCount(
14745 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14746 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14747 return std::make_pair(Lo, Hi);
14748}
14749
14750/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14752 EVT VT = N.getValueType();
14755 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14756}
14757
14760 unsigned Start, unsigned Count,
14761 EVT EltVT) {
14762 EVT VT = Op.getValueType();
14763 if (Count == 0)
14765 if (EltVT == EVT())
14766 EltVT = VT.getVectorElementType();
14767 SDLoc SL(Op);
14768 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14769 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14770 }
14771}
14772
14773// getAddressSpace - Return the address space this GlobalAddress belongs to.
14775 return getGlobal()->getType()->getAddressSpace();
14776}
14777
14780 return Val.MachineCPVal->getType();
14781 return Val.ConstVal->getType();
14782}
14783
14784bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14785 unsigned &SplatBitSize,
14786 bool &HasAnyUndefs,
14787 unsigned MinSplatBits,
14788 bool IsBigEndian) const {
14789 EVT VT = getValueType(0);
14790 assert(VT.isVector() && "Expected a vector type");
14791 unsigned VecWidth = VT.getSizeInBits();
14792 if (MinSplatBits > VecWidth)
14793 return false;
14794
14795 // FIXME: The widths are based on this node's type, but build vectors can
14796 // truncate their operands.
14797 SplatValue = APInt(VecWidth, 0);
14798 SplatUndef = APInt(VecWidth, 0);
14799
14800 // Get the bits. Bits with undefined values (when the corresponding element
14801 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14802 // in SplatValue. If any of the values are not constant, give up and return
14803 // false.
14804 unsigned int NumOps = getNumOperands();
14805 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14806 unsigned EltWidth = VT.getScalarSizeInBits();
14807
14808 for (unsigned j = 0; j < NumOps; ++j) {
14809 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14810 SDValue OpVal = getOperand(i);
14811 unsigned BitPos = j * EltWidth;
14812
14813 if (OpVal.isUndef())
14814 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14815 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14816 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14817 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14818 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14819 else
14820 return false;
14821 }
14822
14823 // The build_vector is all constants or undefs. Find the smallest element
14824 // size that splats the vector.
14825 HasAnyUndefs = (SplatUndef != 0);
14826
14827 // FIXME: This does not work for vectors with elements less than 8 bits.
14828 while (VecWidth > 8) {
14829 // If we can't split in half, stop here.
14830 if (VecWidth & 1)
14831 break;
14832
14833 unsigned HalfSize = VecWidth / 2;
14834 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14835 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14836 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14837 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14838
14839 // If the two halves do not match (ignoring undef bits), stop here.
14840 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14841 MinSplatBits > HalfSize)
14842 break;
14843
14844 SplatValue = HighValue | LowValue;
14845 SplatUndef = HighUndef & LowUndef;
14846
14847 VecWidth = HalfSize;
14848 }
14849
14850 // FIXME: The loop above only tries to split in halves. But if the input
14851 // vector for example is <3 x i16> it wouldn't be able to detect a
14852 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14853 // optimizations. I guess that back in the days when this helper was created
14854 // vectors normally was power-of-2 sized.
14855
14856 SplatBitSize = VecWidth;
14857 return true;
14858}
14859
14861 BitVector *UndefElements) const {
14862 unsigned NumOps = getNumOperands();
14863 if (UndefElements) {
14864 UndefElements->clear();
14865 UndefElements->resize(NumOps);
14866 }
14867 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14868 if (!DemandedElts)
14869 return SDValue();
14870 SDValue Splatted;
14871 for (unsigned i = 0; i != NumOps; ++i) {
14872 if (!DemandedElts[i])
14873 continue;
14874 SDValue Op = getOperand(i);
14875 if (Op.isUndef()) {
14876 if (UndefElements)
14877 (*UndefElements)[i] = true;
14878 } else if (!Splatted) {
14879 Splatted = Op;
14880 } else if (Splatted != Op) {
14881 return SDValue();
14882 }
14883 }
14884
14885 if (!Splatted) {
14886 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14887 assert(getOperand(FirstDemandedIdx).isUndef() &&
14888 "Can only have a splat without a constant for all undefs.");
14889 return getOperand(FirstDemandedIdx);
14890 }
14891
14892 return Splatted;
14893}
14894
14896 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14897 return getSplatValue(DemandedElts, UndefElements);
14898}
14899
14901 SmallVectorImpl<SDValue> &Sequence,
14902 BitVector *UndefElements) const {
14903 unsigned NumOps = getNumOperands();
14904 Sequence.clear();
14905 if (UndefElements) {
14906 UndefElements->clear();
14907 UndefElements->resize(NumOps);
14908 }
14909 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14910 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14911 return false;
14912
14913 // Set the undefs even if we don't find a sequence (like getSplatValue).
14914 if (UndefElements)
14915 for (unsigned I = 0; I != NumOps; ++I)
14916 if (DemandedElts[I] && getOperand(I).isUndef())
14917 (*UndefElements)[I] = true;
14918
14919 // Iteratively widen the sequence length looking for repetitions.
14920 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14921 Sequence.append(SeqLen, SDValue());
14922 for (unsigned I = 0; I != NumOps; ++I) {
14923 if (!DemandedElts[I])
14924 continue;
14925 SDValue &SeqOp = Sequence[I % SeqLen];
14927 if (Op.isUndef()) {
14928 if (!SeqOp)
14929 SeqOp = Op;
14930 continue;
14931 }
14932 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14933 Sequence.clear();
14934 break;
14935 }
14936 SeqOp = Op;
14937 }
14938 if (!Sequence.empty())
14939 return true;
14940 }
14941
14942 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14943 return false;
14944}
14945
14947 BitVector *UndefElements) const {
14948 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14949 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14950}
14951
14954 BitVector *UndefElements) const {
14956 getSplatValue(DemandedElts, UndefElements));
14957}
14958
14961 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14962}
14963
14966 BitVector *UndefElements) const {
14968 getSplatValue(DemandedElts, UndefElements));
14969}
14970
14975
14976int32_t
14978 uint32_t BitWidth) const {
14979 if (ConstantFPSDNode *CN =
14981 bool IsExact;
14982 APSInt IntVal(BitWidth);
14983 const APFloat &APF = CN->getValueAPF();
14984 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14985 APFloat::opOK ||
14986 !IsExact)
14987 return -1;
14988
14989 return IntVal.exactLogBase2();
14990 }
14991 return -1;
14992}
14993
14995 bool IsLittleEndian, unsigned DstEltSizeInBits,
14996 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
14997 // Early-out if this contains anything but Undef/Constant/ConstantFP.
14998 if (!isConstant())
14999 return false;
15000
15001 unsigned NumSrcOps = getNumOperands();
15002 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15003 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15004 "Invalid bitcast scale");
15005
15006 // Extract raw src bits.
15007 SmallVector<APInt> SrcBitElements(NumSrcOps,
15008 APInt::getZero(SrcEltSizeInBits));
15009 BitVector SrcUndeElements(NumSrcOps, false);
15010
15011 for (unsigned I = 0; I != NumSrcOps; ++I) {
15013 if (Op.isUndef()) {
15014 SrcUndeElements.set(I);
15015 continue;
15016 }
15017 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15018 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15019 assert((CInt || CFP) && "Unknown constant");
15020 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15021 : CFP->getValueAPF().bitcastToAPInt();
15022 }
15023
15024 // Recast to dst width.
15025 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15026 SrcBitElements, UndefElements, SrcUndeElements);
15027 return true;
15028}
15029
15030void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15031 unsigned DstEltSizeInBits,
15032 SmallVectorImpl<APInt> &DstBitElements,
15033 ArrayRef<APInt> SrcBitElements,
15034 BitVector &DstUndefElements,
15035 const BitVector &SrcUndefElements) {
15036 unsigned NumSrcOps = SrcBitElements.size();
15037 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15038 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15039 "Invalid bitcast scale");
15040 assert(NumSrcOps == SrcUndefElements.size() &&
15041 "Vector size mismatch");
15042
15043 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15044 DstUndefElements.clear();
15045 DstUndefElements.resize(NumDstOps, false);
15046 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15047
15048 // Concatenate src elements constant bits together into dst element.
15049 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15050 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15051 for (unsigned I = 0; I != NumDstOps; ++I) {
15052 DstUndefElements.set(I);
15053 APInt &DstBits = DstBitElements[I];
15054 for (unsigned J = 0; J != Scale; ++J) {
15055 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15056 if (SrcUndefElements[Idx])
15057 continue;
15058 DstUndefElements.reset(I);
15059 const APInt &SrcBits = SrcBitElements[Idx];
15060 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15061 "Illegal constant bitwidths");
15062 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15063 }
15064 }
15065 return;
15066 }
15067
15068 // Split src element constant bits into dst elements.
15069 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15070 for (unsigned I = 0; I != NumSrcOps; ++I) {
15071 if (SrcUndefElements[I]) {
15072 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15073 continue;
15074 }
15075 const APInt &SrcBits = SrcBitElements[I];
15076 for (unsigned J = 0; J != Scale; ++J) {
15077 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15078 APInt &DstBits = DstBitElements[Idx];
15079 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15080 }
15081 }
15082}
15083
15085 for (const SDValue &Op : op_values()) {
15086 unsigned Opc = Op.getOpcode();
15087 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15088 return false;
15089 }
15090 return true;
15091}
15092
15093std::optional<std::pair<APInt, APInt>>
15095 unsigned NumOps = getNumOperands();
15096 if (NumOps < 2)
15097 return std::nullopt;
15098
15099 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15100 APInt Start, Stride;
15101 int FirstIdx = -1, SecondIdx = -1;
15102
15103 // Find the first two non-undef constant elements to determine Start and
15104 // Stride, then verify all remaining elements match the sequence.
15105 for (unsigned I = 0; I < NumOps; ++I) {
15107 if (Op->isUndef())
15108 continue;
15109 if (!isa<ConstantSDNode>(Op))
15110 return std::nullopt;
15111
15112 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15113 if (FirstIdx < 0) {
15114 FirstIdx = I;
15115 Start = Val;
15116 } else if (SecondIdx < 0) {
15117 SecondIdx = I;
15118 // Compute stride using modular arithmetic. Simple division would handle
15119 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15120 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15121 // Note that modular arithmetic is agnostic to signed/unsigned.
15122 unsigned IdxDiff = I - FirstIdx;
15123 APInt ValDiff = Val - Start;
15124
15125 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15126 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15127 if (ValDiff.countr_zero() < CommonPow2Bits)
15128 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15129 IdxDiff >>= CommonPow2Bits;
15130 ValDiff.lshrInPlace(CommonPow2Bits);
15131
15132 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15133 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15134 // one, but we could try all candidates to handle more cases.
15135 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15136 if (Stride.isZero())
15137 return std::nullopt;
15138
15139 // Step 3: Adjust Start based on the first defined element's index.
15140 Start -= Stride * FirstIdx;
15141 } else {
15142 // Verify this element matches the sequence.
15143 if (Val != Start + Stride * I)
15144 return std::nullopt;
15145 }
15146 }
15147
15148 // Need at least two defined elements.
15149 if (SecondIdx < 0)
15150 return std::nullopt;
15151
15152 return std::make_pair(Start, Stride);
15153}
15154
15156 // Find the first non-undef value in the shuffle mask.
15157 unsigned i, e;
15158 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15159 /* search */;
15160
15161 // If all elements are undefined, this shuffle can be considered a splat
15162 // (although it should eventually get simplified away completely).
15163 if (i == e)
15164 return true;
15165
15166 // Make sure all remaining elements are either undef or the same as the first
15167 // non-undef value.
15168 for (int Idx = Mask[i]; i != e; ++i)
15169 if (Mask[i] >= 0 && Mask[i] != Idx)
15170 return false;
15171 return true;
15172}
15173
15174// Returns true if it is a constant integer BuildVector or constant integer,
15175// possibly hidden by a bitcast.
15177 SDValue N, bool AllowOpaques) const {
15179
15180 if (auto *C = dyn_cast<ConstantSDNode>(N))
15181 return AllowOpaques || !C->isOpaque();
15182
15184 return true;
15185
15186 // Treat a GlobalAddress supporting constant offset folding as a
15187 // constant integer.
15188 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15189 if (GA->getOpcode() == ISD::GlobalAddress &&
15190 TLI->isOffsetFoldingLegal(GA))
15191 return true;
15192
15193 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15194 isa<ConstantSDNode>(N.getOperand(0)))
15195 return true;
15196 return false;
15197}
15198
15199// Returns true if it is a constant float BuildVector or constant float.
15202 return true;
15203
15205 return true;
15206
15207 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15208 isa<ConstantFPSDNode>(N.getOperand(0)))
15209 return true;
15210
15211 return false;
15212}
15213
15214std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15215 ConstantSDNode *Const =
15216 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15217 if (!Const)
15218 return std::nullopt;
15219
15220 EVT VT = N.getValueType();
15221 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15222 switch (TLI->getBooleanContents(VT)) {
15224 if (CVal.isOne())
15225 return true;
15226 if (CVal.isZero())
15227 return false;
15228 return std::nullopt;
15230 if (CVal.isAllOnes())
15231 return true;
15232 if (CVal.isZero())
15233 return false;
15234 return std::nullopt;
15236 return CVal[0];
15237 }
15238 llvm_unreachable("Unknown BooleanContent enum");
15239}
15240
15241void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15242 assert(!Node->OperandList && "Node already has operands");
15244 "too many operands to fit into SDNode");
15245 SDUse *Ops = OperandRecycler.allocate(
15246 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15247
15248 bool IsDivergent = false;
15249 for (unsigned I = 0; I != Vals.size(); ++I) {
15250 Ops[I].setUser(Node);
15251 Ops[I].setInitial(Vals[I]);
15252 EVT VT = Ops[I].getValueType();
15253
15254 // Skip Chain. It does not carry divergence.
15255 if (VT != MVT::Other &&
15256 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15257 Ops[I].getNode()->isDivergent()) {
15258 IsDivergent = true;
15259 }
15260 }
15261 Node->NumOperands = Vals.size();
15262 Node->OperandList = Ops;
15263 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15264 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15265 Node->SDNodeBits.IsDivergent = IsDivergent;
15266 }
15267 checkForCycles(Node);
15268}
15269
15272 size_t Limit = SDNode::getMaxNumOperands();
15273 while (Vals.size() > Limit) {
15274 unsigned SliceIdx = Vals.size() - Limit;
15275 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15276 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15277 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15278 Vals.emplace_back(NewTF);
15279 }
15280 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15281}
15282
15284 EVT VT, SDNodeFlags Flags) {
15285 switch (Opcode) {
15286 default:
15287 return SDValue();
15288 case ISD::ADD:
15289 case ISD::OR:
15290 case ISD::XOR:
15291 case ISD::UMAX:
15292 case ISD::MUL:
15293 case ISD::AND:
15294 case ISD::UMIN:
15295 case ISD::SMAX:
15296 case ISD::SMIN:
15298 VT);
15299 case ISD::FADD:
15300 // If flags allow, prefer positive zero since it's generally cheaper
15301 // to materialize on most targets.
15302 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15303 case ISD::FMUL:
15304 return getConstantFP(1.0, DL, VT);
15305 case ISD::FMINNUM:
15306 case ISD::FMAXNUM:
15307 case ISD::FMINIMUMNUM:
15308 case ISD::FMAXIMUMNUM: {
15309 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15310 // depending on fast-math flags (FMF).
15311 const fltSemantics &Semantics = VT.getFltSemantics();
15312 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15313 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15314 APFloat::getLargest(Semantics);
15315 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15316 NeutralAF.changeSign();
15317
15318 return getConstantFP(NeutralAF, DL, VT);
15319 }
15320 case ISD::FMINIMUM:
15321 case ISD::FMAXIMUM: {
15322 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15323 const fltSemantics &Semantics = VT.getFltSemantics();
15324 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15325 : APFloat::getLargest(Semantics);
15326 if (Opcode == ISD::FMAXIMUM)
15327 NeutralAF.changeSign();
15328
15329 return getConstantFP(NeutralAF, DL, VT);
15330 }
15331
15332 }
15333}
15334
15336 SDValue Acc, SDValue LHS,
15337 SDValue RHS) {
15338 EVT AccVT = Acc.getValueType();
15339 if (AccVT.isFloatingPoint()) {
15340 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15341 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15342 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15343 }
15346 "Unexpected opcode");
15347 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15348 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15349 return getNegative(MLA, DL, AccVT);
15350}
15351
15352/// Helper used to make a call to a library function that has one argument of
15353/// pointer type.
15354///
15355/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15356/// used to get or set floating-point state. They have one argument of pointer
15357/// type, which points to the memory region containing bits of the
15358/// floating-point state. The value returned by such function is ignored in the
15359/// created call.
15360///
15361/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15362/// \param Ptr Pointer used to save/load state.
15363/// \param InChain Ingoing token chain.
15364/// \param Node Node being legalized
15365/// \returns Outgoing chain token.
15367 SDValue InChain, SDNode *Node) {
15368 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15369 RTLIB::LibcallImpl LibcallImpl =
15370 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15371 if (LibcallImpl == RTLIB::Unsupported) {
15372 getContext()->emitError(Twine("no libcall available for ") +
15373 Node->getOperationName(this));
15374 return InChain;
15375 }
15376
15378 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15379 SDValue Callee =
15380 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15382 CLI.setDebugLoc(SDLoc(Node))
15383 .setChain(InChain)
15384 .setLibCallee(Libcalls->getLibcallImplCallingConv(LibcallImpl),
15385 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15386 return TLI->LowerCallTo(CLI).second;
15387}
15388
15390 assert(From && To && "Invalid SDNode; empty source SDValue?");
15391 auto I = SDEI.find(From);
15392 if (I == SDEI.end())
15393 return;
15394
15395 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15396 // the iterator, hence the need to make a copy to prevent a use-after-free.
15397 NodeExtraInfo NEI = I->second;
15398 if (LLVM_LIKELY(!NEI.PCSections)) {
15399 // No deep copy required for the types of extra info set.
15400 //
15401 // FIXME: Investigate if other types of extra info also need deep copy. This
15402 // depends on the types of nodes they can be attached to: if some extra info
15403 // is only ever attached to nodes where a replacement To node is always the
15404 // node where later use and propagation of the extra info has the intended
15405 // semantics, no deep copy is required.
15406 SDEI[To] = std::move(NEI);
15407 return;
15408 }
15409
15410 const SDNode *EntrySDN = getEntryNode().getNode();
15411
15412 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15413 // through the replacement of From with To. Otherwise, replacements of a node
15414 // (From) with more complex nodes (To and its operands) may result in lost
15415 // extra info where the root node (To) is insignificant in further propagating
15416 // and using extra info when further lowering to MIR.
15417 //
15418 // In the first step pre-populate the visited set with the nodes reachable
15419 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15420 // DAG that is not new and should be left untouched.
15421 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15422 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15423 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15424 if (MaxDepth == 0) {
15425 // Remember this node in case we need to increase MaxDepth and continue
15426 // populating FromReach from this node.
15427 Leafs.emplace_back(N);
15428 return;
15429 }
15430 if (!FromReach.insert(N).second)
15431 return;
15432 for (const SDValue &Op : N->op_values())
15433 Self(Self, Op.getNode(), MaxDepth - 1);
15434 };
15435
15436 // Copy extra info to To and all its transitive operands (that are new).
15438 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15439 if (FromReach.contains(N))
15440 return true;
15441 if (!Visited.insert(N).second)
15442 return true;
15443 if (EntrySDN == N)
15444 return false;
15445 for (const SDValue &Op : N->op_values()) {
15446 if (N == To && Op.getNode() == EntrySDN) {
15447 // Special case: New node's operand is the entry node; just need to
15448 // copy extra info to new node.
15449 break;
15450 }
15451 if (!Self(Self, Op.getNode()))
15452 return false;
15453 }
15454 // Copy only if entry node was not reached.
15455 SDEI[N] = std::move(NEI);
15456 return true;
15457 };
15458
15459 // We first try with a lower MaxDepth, assuming that the path to common
15460 // operands between From and To is relatively short. This significantly
15461 // improves performance in the common case. The initial MaxDepth is big
15462 // enough to avoid retry in the common case; the last MaxDepth is large
15463 // enough to avoid having to use the fallback below (and protects from
15464 // potential stack exhaustion from recursion).
15465 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15466 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15467 // StartFrom is the previous (or initial) set of leafs reachable at the
15468 // previous maximum depth.
15470 std::swap(StartFrom, Leafs);
15471 for (const SDNode *N : StartFrom)
15472 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15473 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15474 return;
15475 // This should happen very rarely (reached the entry node).
15476 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15477 assert(!Leafs.empty());
15478 }
15479
15480 // This should not happen - but if it did, that means the subgraph reachable
15481 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15482 // could not visit all reachable common operands. Consequently, we were able
15483 // to reach the entry node.
15484 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15485 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15486 // Best-effort fallback if assertions disabled.
15487 SDEI[To] = std::move(NEI);
15488}
15489
15491 assert(VT.isVector() && "Can only unroll vector types!");
15492 if (VT.isFixedLengthVector())
15493 return VT.getVectorNumElements();
15494
15495 const MachineFunction &MF = getMachineFunction();
15496 const Function &F = MF.getFunction();
15497
15498 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15499 if (MaxVScale.ugt(VScaleUnrollLimit))
15500 return 0;
15501
15502 bool Overflow;
15503 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15504 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15505 if (Overflow)
15506 return 0;
15507
15508 return MaxNElts.getZExtValue();
15509}
15510
15512 ArrayRef<SDValue> Scalars) {
15513 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15514 "Element count mismatch!");
15515 if (VT.isFixedLengthVector())
15516 return getBuildVector(VT, DL, Scalars);
15517
15518 SDValue Vec = getPOISON(VT);
15519 // Iterate in reverse so result remains poison until we encounter a lane that
15520 // exists, after which all lower-numbered lanes must also exist.
15521 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15522 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15523
15524 return Vec;
15525}
15526
15527#ifndef NDEBUG
15528static void checkForCyclesHelper(const SDNode *N,
15531 const llvm::SelectionDAG *DAG) {
15532 // If this node has already been checked, don't check it again.
15533 if (Checked.count(N))
15534 return;
15535
15536 // If a node has already been visited on this depth-first walk, reject it as
15537 // a cycle.
15538 if (!Visited.insert(N).second) {
15539 errs() << "Detected cycle in SelectionDAG\n";
15540 dbgs() << "Offending node:\n";
15541 N->dumprFull(DAG); dbgs() << "\n";
15542 abort();
15543 }
15544
15545 for (const SDValue &Op : N->op_values())
15546 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15547
15548 Checked.insert(N);
15549 Visited.erase(N);
15550}
15551#endif
15552
15554 const llvm::SelectionDAG *DAG,
15555 bool force) {
15556#ifndef NDEBUG
15557 bool check = force;
15558#ifdef EXPENSIVE_CHECKS
15559 check = true;
15560#endif // EXPENSIVE_CHECKS
15561 if (check) {
15562 assert(N && "Checking nonexistent SDNode");
15565 checkForCyclesHelper(N, visited, checked, DAG);
15566 }
15567#endif // !NDEBUG
15568}
15569
15570void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15571 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15572}
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:857
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:613
#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
const SmallVectorImpl< MachineOperand > & Cond
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 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
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1312
void copySign(const APFloat &RHS)
Definition APFloat.h:1406
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6045
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1294
bool isNegative() const
Definition APFloat.h:1583
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1285
bool isFinite() const
Definition APFloat.h:1588
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1303
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
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1330
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
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2093
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
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
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2064
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
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
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 sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1199
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 sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2124
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2138
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1186
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 uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2074
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1774
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
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 sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
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
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2083
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.
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 a use of a float value is insensitive to signed zeros.
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 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:348
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
Changed
#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
@ 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.
@ 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...
@ 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.
@ 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...
@ 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:1558
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:1540
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:227
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:567
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:543
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.
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
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)