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 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1462 const TargetLibraryInfo *LibraryInfo,
1463 const LibcallLoweringInfo *LibcallsInfo,
1464 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1466 FunctionVarLocs const *VarLocs) {
1467 MF = &NewMF;
1468 SDAGISelPass = PassPtr;
1469 ORE = &NewORE;
1472 LibInfo = LibraryInfo;
1473 Libcalls = LibcallsInfo;
1474 Context = &MF->getFunction().getContext();
1475 UA = NewUA;
1476 PSI = PSIin;
1477 BFI = BFIin;
1478 MMI = &MMIin;
1479 FnVarLocs = VarLocs;
1480}
1481
1483 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1484 allnodes_clear();
1485 OperandRecycler.clear(OperandAllocator);
1486 delete DbgInfo;
1487}
1488
1490 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
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 ISD::CondCode Cond, const SDLoc &dl,
2668 SDNodeFlags Flags) {
2669 EVT OpVT = N1.getValueType();
2670
2671 auto GetUndefBooleanConstant = [&]() {
2672 if (VT.getScalarType() == MVT::i1 ||
2673 TLI->getBooleanContents(OpVT) ==
2675 return getUNDEF(VT);
2676 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2677 // so we cannot use getUNDEF(). Return zero instead.
2678 return getConstant(0, dl, VT);
2679 };
2680
2681 // These setcc operations always fold.
2682 switch (Cond) {
2683 default: break;
2684 case ISD::SETFALSE:
2685 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2686 case ISD::SETTRUE:
2687 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2688
2689 case ISD::SETOEQ:
2690 case ISD::SETOGT:
2691 case ISD::SETOGE:
2692 case ISD::SETOLT:
2693 case ISD::SETOLE:
2694 case ISD::SETONE:
2695 case ISD::SETO:
2696 case ISD::SETUO:
2697 case ISD::SETUEQ:
2698 case ISD::SETUNE:
2699 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2700 break;
2701 }
2702
2703 if (OpVT.isInteger()) {
2704 // For EQ and NE, we can always pick a value for the undef to make the
2705 // predicate pass or fail, so we can return undef.
2706 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2707 // icmp eq/ne X, undef -> undef.
2708 if ((N1.isUndef() || N2.isUndef()) &&
2709 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2710 return GetUndefBooleanConstant();
2711
2712 // If both operands are undef, we can return undef for int comparison.
2713 // icmp undef, undef -> undef.
2714 if (N1.isUndef() && N2.isUndef())
2715 return GetUndefBooleanConstant();
2716
2717 // icmp X, X -> true/false
2718 // icmp X, undef -> true/false because undef could be X.
2719 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2720 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2721 }
2722
2724 const APInt &C2 = N2C->getAPIntValue();
2726 const APInt &C1 = N1C->getAPIntValue();
2727
2729 dl, VT, OpVT);
2730 }
2731 }
2732
2733 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2734 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2735
2736 if (N1CFP && N2CFP) {
2737 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2738 switch (Cond) {
2739 default: break;
2740 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2741 return GetUndefBooleanConstant();
2742 [[fallthrough]];
2743 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2744 OpVT);
2745 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2746 return GetUndefBooleanConstant();
2747 [[fallthrough]];
2749 R==APFloat::cmpLessThan, dl, VT,
2750 OpVT);
2751 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2752 return GetUndefBooleanConstant();
2753 [[fallthrough]];
2754 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2755 OpVT);
2756 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2757 return GetUndefBooleanConstant();
2758 [[fallthrough]];
2760 VT, OpVT);
2761 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2762 return GetUndefBooleanConstant();
2763 [[fallthrough]];
2765 R==APFloat::cmpEqual, dl, VT,
2766 OpVT);
2767 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2768 return GetUndefBooleanConstant();
2769 [[fallthrough]];
2771 R==APFloat::cmpEqual, dl, VT, OpVT);
2772 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2773 OpVT);
2774 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2775 OpVT);
2777 R==APFloat::cmpEqual, dl, VT,
2778 OpVT);
2779 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2780 OpVT);
2782 R==APFloat::cmpLessThan, dl, VT,
2783 OpVT);
2785 R==APFloat::cmpUnordered, dl, VT,
2786 OpVT);
2788 VT, OpVT);
2789 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2790 OpVT);
2791 }
2792 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2793 // Ensure that the constant occurs on the RHS.
2795 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2796 return SDValue();
2797 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2798 /*IsSignaling=*/false, Flags);
2799 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2800 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2801 // If an operand is known to be a nan (or undef that could be a nan), we can
2802 // fold it.
2803 // Choosing NaN for the undef will always make unordered comparison succeed
2804 // and ordered comparison fails.
2805 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2806 switch (ISD::getUnorderedFlavor(Cond)) {
2807 default:
2808 llvm_unreachable("Unknown flavor!");
2809 case 0: // Known false.
2810 return getBoolConstant(false, dl, VT, OpVT);
2811 case 1: // Known true.
2812 return getBoolConstant(true, dl, VT, OpVT);
2813 case 2: // Undefined.
2814 return GetUndefBooleanConstant();
2815 }
2816 }
2817
2818 // Could not fold it.
2819 return SDValue();
2820}
2821
2822/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2823/// use this predicate to simplify operations downstream.
2825 unsigned BitWidth = Op.getScalarValueSizeInBits();
2827}
2828
2829// TODO: Should have argument to specify if sign bit of nan is ignorable.
2831 if (Depth >= MaxRecursionDepth)
2832 return false; // Limit search depth.
2833
2834 unsigned Opc = Op.getOpcode();
2835 switch (Opc) {
2836 case ISD::FABS:
2837 return true;
2838 case ISD::AssertNoFPClass: {
2839 FPClassTest NoFPClass =
2840 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2841
2842 const FPClassTest TestMask = fcNan | fcNegative;
2843 return (NoFPClass & TestMask) == TestMask;
2844 }
2845 case ISD::ARITH_FENCE:
2846 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2847 case ISD::FEXP:
2848 case ISD::FEXP2:
2849 case ISD::FEXP10:
2850 return Op->getFlags().hasNoNaNs();
2851 case ISD::FMINNUM:
2852 case ISD::FMINNUM_IEEE:
2853 case ISD::FMINIMUM:
2854 case ISD::FMINIMUMNUM:
2855 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2856 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2857 case ISD::FMAXNUM:
2858 case ISD::FMAXNUM_IEEE:
2859 case ISD::FMAXIMUM:
2860 case ISD::FMAXIMUMNUM:
2861 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2862 // is sufficient.
2863 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2864 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2865 default:
2866 return false;
2867 }
2868
2869 llvm_unreachable("covered opcode switch");
2870}
2871
2872/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2873/// this predicate to simplify operations downstream. Mask is known to be zero
2874/// for bits that V cannot have.
2876 unsigned Depth) const {
2877 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2878}
2879
2880/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2881/// DemandedElts. We use this predicate to simplify operations downstream.
2882/// Mask is known to be zero for bits that V cannot have.
2884 const APInt &DemandedElts,
2885 unsigned Depth) const {
2886 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2887}
2888
2889/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2890/// DemandedElts. We use this predicate to simplify operations downstream.
2892 unsigned Depth /* = 0 */) const {
2893 return computeKnownBits(V, DemandedElts, Depth).isZero();
2894}
2895
2896/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2898 unsigned Depth) const {
2899 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2900}
2901
2903 const APInt &DemandedElts,
2904 unsigned Depth) const {
2905 EVT VT = Op.getValueType();
2906 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2907
2908 unsigned NumElts = VT.getVectorNumElements();
2909 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2910
2911 APInt KnownZeroElements = APInt::getZero(NumElts);
2912 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2913 if (!DemandedElts[EltIdx])
2914 continue; // Don't query elements that are not demanded.
2915 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2916 if (MaskedVectorIsZero(Op, Mask, Depth))
2917 KnownZeroElements.setBit(EltIdx);
2918 }
2919 return KnownZeroElements;
2920}
2921
2922/// isSplatValue - Return true if the vector V has the same value
2923/// across all DemandedElts. For scalable vectors, we don't know the
2924/// number of lanes at compile time. Instead, we use a 1 bit APInt
2925/// to represent a conservative value for all lanes; that is, that
2926/// one bit value is implicitly splatted across all lanes.
2927bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2928 APInt &UndefElts, unsigned Depth) const {
2929 unsigned Opcode = V.getOpcode();
2930 EVT VT = V.getValueType();
2931 assert(VT.isVector() && "Vector type expected");
2932 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2933 "scalable demanded bits are ignored");
2934
2935 if (!DemandedElts)
2936 return false; // No demanded elts, better to assume we don't know anything.
2937
2938 if (Depth >= MaxRecursionDepth)
2939 return false; // Limit search depth.
2940
2941 // Deal with some common cases here that work for both fixed and scalable
2942 // vector types.
2943 switch (Opcode) {
2944 case ISD::SPLAT_VECTOR:
2945 UndefElts = V.getOperand(0).isUndef()
2946 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2947 : APInt(DemandedElts.getBitWidth(), 0);
2948 return true;
2949 case ISD::ADD:
2950 case ISD::SUB:
2951 case ISD::AND:
2952 case ISD::XOR:
2953 case ISD::OR: {
2954 APInt UndefLHS, UndefRHS;
2955 SDValue LHS = V.getOperand(0);
2956 SDValue RHS = V.getOperand(1);
2957 // Only recognize splats with the same demanded undef elements for both
2958 // operands, otherwise we might fail to handle binop-specific undef
2959 // handling.
2960 // e.g. (and undef, 0) -> 0 etc.
2961 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2962 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2963 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2964 UndefElts = UndefLHS | UndefRHS;
2965 return true;
2966 }
2967 return false;
2968 }
2969 case ISD::ABS:
2971 case ISD::TRUNCATE:
2972 case ISD::SIGN_EXTEND:
2973 case ISD::ZERO_EXTEND:
2974 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2975 default:
2976 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2977 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2978 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
2979 Depth);
2980 break;
2981 }
2982
2983 // We don't support other cases than those above for scalable vectors at
2984 // the moment.
2985 if (VT.isScalableVector())
2986 return false;
2987
2988 unsigned NumElts = VT.getVectorNumElements();
2989 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2990 UndefElts = APInt::getZero(NumElts);
2991
2992 switch (Opcode) {
2993 case ISD::BUILD_VECTOR: {
2994 SDValue Scl;
2995 for (unsigned i = 0; i != NumElts; ++i) {
2996 SDValue Op = V.getOperand(i);
2997 if (Op.isUndef()) {
2998 UndefElts.setBit(i);
2999 continue;
3000 }
3001 if (!DemandedElts[i])
3002 continue;
3003 if (Scl && Scl != Op)
3004 return false;
3005 Scl = Op;
3006 }
3007 return true;
3008 }
3009 case ISD::VECTOR_SHUFFLE: {
3010 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3011 APInt DemandedLHS = APInt::getZero(NumElts);
3012 APInt DemandedRHS = APInt::getZero(NumElts);
3013 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3014 for (int i = 0; i != (int)NumElts; ++i) {
3015 int M = Mask[i];
3016 if (M < 0) {
3017 UndefElts.setBit(i);
3018 continue;
3019 }
3020 if (!DemandedElts[i])
3021 continue;
3022 if (M < (int)NumElts)
3023 DemandedLHS.setBit(M);
3024 else
3025 DemandedRHS.setBit(M - NumElts);
3026 }
3027
3028 // If we aren't demanding either op, assume there's no splat.
3029 // If we are demanding both ops, assume there's no splat.
3030 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3031 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3032 return false;
3033
3034 // See if the demanded elts of the source op is a splat or we only demand
3035 // one element, which should always be a splat.
3036 // TODO: Handle source ops splats with undefs.
3037 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3038 APInt SrcUndefs;
3039 return (SrcElts.popcount() == 1) ||
3040 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3041 (SrcElts & SrcUndefs).isZero());
3042 };
3043 if (!DemandedLHS.isZero())
3044 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3045 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3046 }
3048 // Offset the demanded elts by the subvector index.
3049 SDValue Src = V.getOperand(0);
3050 // We don't support scalable vectors at the moment.
3051 if (Src.getValueType().isScalableVector())
3052 return false;
3053 uint64_t Idx = V.getConstantOperandVal(1);
3054 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3055 APInt UndefSrcElts;
3056 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3057 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3058 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3059 return true;
3060 }
3061 break;
3062 }
3066 // Widen the demanded elts by the src element count.
3067 SDValue Src = V.getOperand(0);
3068 // We don't support scalable vectors at the moment.
3069 if (Src.getValueType().isScalableVector())
3070 return false;
3071 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3072 APInt UndefSrcElts;
3073 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3074 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3075 UndefElts = UndefSrcElts.trunc(NumElts);
3076 return true;
3077 }
3078 break;
3079 }
3080 case ISD::BITCAST: {
3081 SDValue Src = V.getOperand(0);
3082 EVT SrcVT = Src.getValueType();
3083 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3084 unsigned BitWidth = VT.getScalarSizeInBits();
3085
3086 // Ignore bitcasts from unsupported types.
3087 // TODO: Add fp support?
3088 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3089 break;
3090
3091 // Bitcast 'small element' vector to 'large element' vector.
3092 if ((BitWidth % SrcBitWidth) == 0) {
3093 // See if each sub element is a splat.
3094 unsigned Scale = BitWidth / SrcBitWidth;
3095 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3096 APInt ScaledDemandedElts =
3097 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3098 for (unsigned I = 0; I != Scale; ++I) {
3099 APInt SubUndefElts;
3100 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3101 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3102 SubDemandedElts &= ScaledDemandedElts;
3103 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3104 return false;
3105 // TODO: Add support for merging sub undef elements.
3106 if (!SubUndefElts.isZero())
3107 return false;
3108 }
3109 return true;
3110 }
3111 break;
3112 }
3113 }
3114
3115 return false;
3116}
3117
3118/// Helper wrapper to main isSplatValue function.
3119bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3120 EVT VT = V.getValueType();
3121 assert(VT.isVector() && "Vector type expected");
3122
3123 APInt UndefElts;
3124 // Since the number of lanes in a scalable vector is unknown at compile time,
3125 // we track one bit which is implicitly broadcast to all lanes. This means
3126 // that all lanes in a scalable vector are considered demanded.
3127 APInt DemandedElts
3129 return isSplatValue(V, DemandedElts, UndefElts) &&
3130 (AllowUndefs || !UndefElts);
3131}
3132
3135
3136 EVT VT = V.getValueType();
3137 unsigned Opcode = V.getOpcode();
3138 switch (Opcode) {
3139 default: {
3140 APInt UndefElts;
3141 // Since the number of lanes in a scalable vector is unknown at compile time,
3142 // we track one bit which is implicitly broadcast to all lanes. This means
3143 // that all lanes in a scalable vector are considered demanded.
3144 APInt DemandedElts
3146
3147 if (isSplatValue(V, DemandedElts, UndefElts)) {
3148 if (VT.isScalableVector()) {
3149 // DemandedElts and UndefElts are ignored for scalable vectors, since
3150 // the only supported cases are SPLAT_VECTOR nodes.
3151 SplatIdx = 0;
3152 } else {
3153 // Handle case where all demanded elements are UNDEF.
3154 if (DemandedElts.isSubsetOf(UndefElts)) {
3155 SplatIdx = 0;
3156 return getUNDEF(VT);
3157 }
3158 SplatIdx = (UndefElts & DemandedElts).countr_one();
3159 }
3160 return V;
3161 }
3162 break;
3163 }
3164 case ISD::SPLAT_VECTOR:
3165 SplatIdx = 0;
3166 return V;
3167 case ISD::VECTOR_SHUFFLE: {
3168 assert(!VT.isScalableVector());
3169 // Check if this is a shuffle node doing a splat.
3170 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3171 // getTargetVShiftNode currently struggles without the splat source.
3172 auto *SVN = cast<ShuffleVectorSDNode>(V);
3173 if (!SVN->isSplat())
3174 break;
3175 int Idx = SVN->getSplatIndex();
3176 int NumElts = V.getValueType().getVectorNumElements();
3177 SplatIdx = Idx % NumElts;
3178 return V.getOperand(Idx / NumElts);
3179 }
3180 }
3181
3182 return SDValue();
3183}
3184
3186 int SplatIdx;
3187 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3188 EVT SVT = SrcVector.getValueType().getScalarType();
3189 EVT LegalSVT = SVT;
3190 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3191 if (!SVT.isInteger())
3192 return SDValue();
3193 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3194 if (LegalSVT.bitsLT(SVT))
3195 return SDValue();
3196 }
3197 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3198 }
3199 return SDValue();
3200}
3201
3202std::optional<ConstantRange>
3204 unsigned Depth) const {
3205 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3206 V.getOpcode() == ISD::SRA) &&
3207 "Unknown shift node");
3208 // Shifting more than the bitwidth is not valid.
3209 unsigned BitWidth = V.getScalarValueSizeInBits();
3210
3211 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3212 const APInt &ShAmt = Cst->getAPIntValue();
3213 if (ShAmt.uge(BitWidth))
3214 return std::nullopt;
3215 return ConstantRange(ShAmt);
3216 }
3217
3218 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3219 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3220 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3221 if (!DemandedElts[i])
3222 continue;
3223 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3224 if (!SA) {
3225 MinAmt = MaxAmt = nullptr;
3226 break;
3227 }
3228 const APInt &ShAmt = SA->getAPIntValue();
3229 if (ShAmt.uge(BitWidth))
3230 return std::nullopt;
3231 if (!MinAmt || MinAmt->ugt(ShAmt))
3232 MinAmt = &ShAmt;
3233 if (!MaxAmt || MaxAmt->ult(ShAmt))
3234 MaxAmt = &ShAmt;
3235 }
3236 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3237 "Failed to find matching min/max shift amounts");
3238 if (MinAmt && MaxAmt)
3239 return ConstantRange(*MinAmt, *MaxAmt + 1);
3240 }
3241
3242 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3243 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3244 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3245 if (KnownAmt.getMaxValue().ult(BitWidth))
3246 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3247
3248 return std::nullopt;
3249}
3250
3251std::optional<unsigned>
3253 unsigned Depth) const {
3254 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3255 V.getOpcode() == ISD::SRA) &&
3256 "Unknown shift node");
3257 if (std::optional<ConstantRange> AmtRange =
3258 getValidShiftAmountRange(V, DemandedElts, Depth))
3259 if (const APInt *ShAmt = AmtRange->getSingleElement())
3260 return ShAmt->getZExtValue();
3261 return std::nullopt;
3262}
3263
3264std::optional<unsigned>
3266 APInt DemandedElts = getDemandAllEltsMask(V);
3267 return getValidShiftAmount(V, DemandedElts, Depth);
3268}
3269
3270std::optional<unsigned>
3272 unsigned Depth) const {
3273 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3274 V.getOpcode() == ISD::SRA) &&
3275 "Unknown shift node");
3276 if (std::optional<ConstantRange> AmtRange =
3277 getValidShiftAmountRange(V, DemandedElts, Depth))
3278 return AmtRange->getUnsignedMin().getZExtValue();
3279 return std::nullopt;
3280}
3281
3282std::optional<unsigned>
3284 APInt DemandedElts = getDemandAllEltsMask(V);
3285 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3286}
3287
3288std::optional<unsigned>
3290 unsigned Depth) const {
3291 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3292 V.getOpcode() == ISD::SRA) &&
3293 "Unknown shift node");
3294 if (std::optional<ConstantRange> AmtRange =
3295 getValidShiftAmountRange(V, DemandedElts, Depth))
3296 return AmtRange->getUnsignedMax().getZExtValue();
3297 return std::nullopt;
3298}
3299
3300std::optional<unsigned>
3302 APInt DemandedElts = getDemandAllEltsMask(V);
3303 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3304}
3305
3306/// Determine which bits of Op are known to be either zero or one and return
3307/// them in Known. For vectors, the known bits are those that are shared by
3308/// every vector element.
3310 APInt DemandedElts = getDemandAllEltsMask(Op);
3311 return computeKnownBits(Op, DemandedElts, Depth);
3312}
3313
3314/// Determine which bits of Op are known to be either zero or one and return
3315/// them in Known. The DemandedElts argument allows us to only collect the known
3316/// bits that are shared by the requested vector elements.
3318 unsigned Depth) const {
3319 unsigned BitWidth = Op.getScalarValueSizeInBits();
3320
3321 KnownBits Known(BitWidth); // Don't know anything.
3322
3323 if (auto OptAPInt = Op->bitcastToAPInt()) {
3324 // We know all of the bits for a constant!
3325 return KnownBits::makeConstant(*std::move(OptAPInt));
3326 }
3327
3328 if (Depth >= MaxRecursionDepth)
3329 return Known; // Limit search depth.
3330
3331 KnownBits Known2;
3332 unsigned NumElts = DemandedElts.getBitWidth();
3333 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3334 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3335 assert((!Op.getValueType().isFixedLengthVector() ||
3336 NumElts == Op.getValueType().getVectorNumElements()) &&
3337 "Unexpected vector size");
3338
3339 if (!DemandedElts)
3340 return Known; // No demanded elts, better to assume we don't know anything.
3341
3342 unsigned Opcode = Op.getOpcode();
3343 switch (Opcode) {
3344 case ISD::FREEZE: {
3345 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3347 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3348 break;
3349 }
3350 case ISD::MERGE_VALUES:
3351 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3352 Depth + 1);
3353 case ISD::SPLAT_VECTOR: {
3354 SDValue SrcOp = Op.getOperand(0);
3355 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3356 "Expected SPLAT_VECTOR implicit truncation");
3357 // Implicitly truncate the bits to match the official semantics of
3358 // SPLAT_VECTOR.
3360 break;
3361 }
3363 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3364 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3365 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3366 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3367 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3368 }
3369 break;
3370 }
3371 case ISD::STEP_VECTOR: {
3372 const APInt &Step = Op.getConstantOperandAPInt(0);
3373
3374 if (Step.isPowerOf2())
3375 Known.Zero.setLowBits(Step.logBase2());
3376
3378
3379 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3380 break;
3381 const APInt MinNumElts =
3382 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3383
3384 bool Overflow;
3385 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3387 .umul_ov(MinNumElts, Overflow);
3388 if (Overflow)
3389 break;
3390
3391 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3392 if (Overflow)
3393 break;
3394
3395 Known.Zero.setHighBits(MaxValue.countl_zero());
3396 break;
3397 }
3398 case ISD::BUILD_VECTOR:
3399 assert(!Op.getValueType().isScalableVector());
3400 // Collect the known bits that are shared by every demanded vector element.
3401 Known.setAllConflict();
3402 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3403 if (!DemandedElts[i])
3404 continue;
3405
3406 SDValue SrcOp = Op.getOperand(i);
3407 if (SrcOp.getOpcode() == ISD::POISON)
3408 continue;
3409
3410 Known2 = computeKnownBits(SrcOp, Depth + 1);
3411
3412 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3413 if (SrcOp.getValueSizeInBits() != BitWidth) {
3414 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3415 "Expected BUILD_VECTOR implicit truncation");
3416 Known2 = Known2.trunc(BitWidth);
3417 }
3418
3419 // Known bits are the values that are shared by every demanded element.
3420 Known = Known.intersectWith(Known2);
3421
3422 // If we don't know any bits, early out.
3423 if (Known.isUnknown())
3424 break;
3425 }
3426
3427 // If every demanded element was poison, we know nothing.
3428 if (Known.hasConflict())
3429 Known.resetAll();
3430 break;
3431 case ISD::VECTOR_COMPRESS: {
3432 SDValue Vec = Op.getOperand(0);
3433 SDValue PassThru = Op.getOperand(2);
3434 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3435 // If we don't know any bits, early out.
3436 if (Known.isUnknown())
3437 break;
3438 Known2 = computeKnownBits(Vec, Depth + 1);
3439 Known = Known.intersectWith(Known2);
3440 break;
3441 }
3442 case ISD::VECTOR_SHUFFLE: {
3443 assert(!Op.getValueType().isScalableVector());
3444 // Collect the known bits that are shared by every vector element referenced
3445 // by the shuffle.
3446 APInt DemandedLHS, DemandedRHS;
3448 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3449 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3450 DemandedLHS, DemandedRHS))
3451 break;
3452
3453 // Known bits are the values that are shared by every demanded element.
3454 Known.setAllConflict();
3455 if (!!DemandedLHS) {
3456 SDValue LHS = Op.getOperand(0);
3457 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3458 Known = Known.intersectWith(Known2);
3459 }
3460 // If we don't know any bits, early out.
3461 if (Known.isUnknown())
3462 break;
3463 if (!!DemandedRHS) {
3464 SDValue RHS = Op.getOperand(1);
3465 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3466 Known = Known.intersectWith(Known2);
3467 }
3468 break;
3469 }
3470 case ISD::VSCALE: {
3472 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3474 break;
3475 }
3476 case ISD::CONCAT_VECTORS: {
3477 if (Op.getValueType().isScalableVector())
3478 break;
3479 // Split DemandedElts and test each of the demanded subvectors.
3480 Known.setAllConflict();
3481 EVT SubVectorVT = Op.getOperand(0).getValueType();
3482 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3483 unsigned NumSubVectors = Op.getNumOperands();
3484 for (unsigned i = 0; i != NumSubVectors; ++i) {
3485 APInt DemandedSub =
3486 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3487 if (!!DemandedSub) {
3488 SDValue Sub = Op.getOperand(i);
3489 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3490 Known = Known.intersectWith(Known2);
3491 }
3492 // If we don't know any bits, early out.
3493 if (Known.isUnknown())
3494 break;
3495 }
3496 break;
3497 }
3498 case ISD::INSERT_SUBVECTOR: {
3499 if (Op.getValueType().isScalableVector())
3500 break;
3501 // Demand any elements from the subvector and the remainder from the src its
3502 // inserted into.
3503 SDValue Src = Op.getOperand(0);
3504 SDValue Sub = Op.getOperand(1);
3505 uint64_t Idx = Op.getConstantOperandVal(2);
3506 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3507 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3508 APInt DemandedSrcElts = DemandedElts;
3509 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3510
3511 Known.setAllConflict();
3512 if (!!DemandedSubElts) {
3513 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3514 if (Known.isUnknown())
3515 break; // early-out.
3516 }
3517 if (!!DemandedSrcElts) {
3518 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3519 Known = Known.intersectWith(Known2);
3520 }
3521 break;
3522 }
3524 // Offset the demanded elts by the subvector index.
3525 SDValue Src = Op.getOperand(0);
3526
3527 APInt DemandedSrcElts;
3528 if (Src.getValueType().isScalableVector())
3529 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3530 else {
3531 uint64_t Idx = Op.getConstantOperandVal(1);
3532 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3533 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3534 }
3535 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3536 break;
3537 }
3538 case ISD::SCALAR_TO_VECTOR: {
3539 if (Op.getValueType().isScalableVector())
3540 break;
3541 // We know about scalar_to_vector as much as we know about it source,
3542 // which becomes the first element of otherwise unknown vector.
3543 if (DemandedElts != 1)
3544 break;
3545
3546 SDValue N0 = Op.getOperand(0);
3547 Known = computeKnownBits(N0, Depth + 1);
3548 if (N0.getValueSizeInBits() != BitWidth)
3549 Known = Known.trunc(BitWidth);
3550
3551 break;
3552 }
3553 case ISD::BITCAST: {
3554 if (Op.getValueType().isScalableVector())
3555 break;
3556
3557 SDValue N0 = Op.getOperand(0);
3558 EVT SubVT = N0.getValueType();
3559 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3560
3561 // Ignore bitcasts from unsupported types.
3562 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3563 break;
3564
3565 // Fast handling of 'identity' bitcasts.
3566 if (BitWidth == SubBitWidth) {
3567 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3568 break;
3569 }
3570
3571 bool IsLE = getDataLayout().isLittleEndian();
3572
3573 // Bitcast 'small element' vector to 'large element' scalar/vector.
3574 if ((BitWidth % SubBitWidth) == 0) {
3575 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3576
3577 // Collect known bits for the (larger) output by collecting the known
3578 // bits from each set of sub elements and shift these into place.
3579 // We need to separately call computeKnownBits for each set of
3580 // sub elements as the knownbits for each is likely to be different.
3581 unsigned SubScale = BitWidth / SubBitWidth;
3582 APInt SubDemandedElts(NumElts * SubScale, 0);
3583 for (unsigned i = 0; i != NumElts; ++i)
3584 if (DemandedElts[i])
3585 SubDemandedElts.setBit(i * SubScale);
3586
3587 for (unsigned i = 0; i != SubScale; ++i) {
3588 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3589 Depth + 1);
3590 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3591 Known.insertBits(Known2, SubBitWidth * Shifts);
3592 }
3593 }
3594
3595 // Bitcast 'large element' scalar/vector to 'small element' vector.
3596 if ((SubBitWidth % BitWidth) == 0) {
3597 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3598
3599 // Collect known bits for the (smaller) output by collecting the known
3600 // bits from the overlapping larger input elements and extracting the
3601 // sub sections we actually care about.
3602 unsigned SubScale = SubBitWidth / BitWidth;
3603 APInt SubDemandedElts =
3604 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3605 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3606
3607 Known.setAllConflict();
3608 for (unsigned i = 0; i != NumElts; ++i)
3609 if (DemandedElts[i]) {
3610 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3611 unsigned Offset = (Shifts % SubScale) * BitWidth;
3612 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3613 // If we don't know any bits, early out.
3614 if (Known.isUnknown())
3615 break;
3616 }
3617 }
3618 break;
3619 }
3620 case ISD::AND:
3621 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3622 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3623
3624 Known &= Known2;
3625 break;
3626 case ISD::OR:
3627 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3628 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3629
3630 Known |= Known2;
3631 break;
3632 case ISD::XOR:
3633 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3634 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3635
3636 Known ^= Known2;
3637 break;
3638 case ISD::MUL: {
3639 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3640 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3641 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3642 // TODO: SelfMultiply can be poison, but not undef.
3643 if (SelfMultiply)
3644 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3645 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3646 Depth + 1);
3647 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3648
3649 // If the multiplication is known not to overflow, the product of a number
3650 // with itself is non-negative. Only do this if we didn't already computed
3651 // the opposite value for the sign bit.
3652 if (Op->getFlags().hasNoSignedWrap() &&
3653 Op.getOperand(0) == Op.getOperand(1) &&
3654 !Known.isNegative())
3655 Known.makeNonNegative();
3656 break;
3657 }
3658 case ISD::MULHU: {
3659 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3660 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3661 Known = KnownBits::mulhu(Known, Known2);
3662 break;
3663 }
3664 case ISD::MULHS: {
3665 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3666 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3667 Known = KnownBits::mulhs(Known, Known2);
3668 break;
3669 }
3670 case ISD::ABDU: {
3671 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3672 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3673 Known = KnownBits::abdu(Known, Known2);
3674 break;
3675 }
3676 case ISD::ABDS: {
3677 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3678 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3679 Known = KnownBits::abds(Known, Known2);
3680 unsigned SignBits1 =
3681 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3682 if (SignBits1 == 1)
3683 break;
3684 unsigned SignBits0 =
3685 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3686 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3687 break;
3688 }
3689 case ISD::UMUL_LOHI: {
3690 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
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 if (Op.getResNo() == 0)
3695 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3696 else
3697 Known = KnownBits::mulhu(Known, Known2);
3698 break;
3699 }
3700 case ISD::SMUL_LOHI: {
3701 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3702 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3703 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3704 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3705 if (Op.getResNo() == 0)
3706 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3707 else
3708 Known = KnownBits::mulhs(Known, Known2);
3709 break;
3710 }
3711 case ISD::AVGFLOORU: {
3712 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3713 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3714 Known = KnownBits::avgFloorU(Known, Known2);
3715 break;
3716 }
3717 case ISD::AVGCEILU: {
3718 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3719 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3720 Known = KnownBits::avgCeilU(Known, Known2);
3721 break;
3722 }
3723 case ISD::AVGFLOORS: {
3724 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3725 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3726 Known = KnownBits::avgFloorS(Known, Known2);
3727 break;
3728 }
3729 case ISD::AVGCEILS: {
3730 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3731 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3732 Known = KnownBits::avgCeilS(Known, Known2);
3733 break;
3734 }
3735 case ISD::SELECT:
3736 case ISD::VSELECT:
3737 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3738 // If we don't know any bits, early out.
3739 if (Known.isUnknown())
3740 break;
3741 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3742
3743 // Only known if known in both the LHS and RHS.
3744 Known = Known.intersectWith(Known2);
3745 break;
3746 case ISD::SELECT_CC:
3747 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3748 // If we don't know any bits, early out.
3749 if (Known.isUnknown())
3750 break;
3751 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3752
3753 // Only known if known in both the LHS and RHS.
3754 Known = Known.intersectWith(Known2);
3755 break;
3756 case ISD::SMULO:
3757 case ISD::UMULO:
3758 if (Op.getResNo() != 1)
3759 break;
3760 // The boolean result conforms to getBooleanContents.
3761 // If we know the result of a setcc has the top bits zero, use this info.
3762 // We know that we have an integer-based boolean since these operations
3763 // are only available for integer.
3764 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3766 BitWidth > 1)
3767 Known.Zero.setBitsFrom(1);
3768 break;
3769 case ISD::SETCC:
3770 case ISD::SETCCCARRY:
3771 case ISD::STRICT_FSETCC:
3772 case ISD::STRICT_FSETCCS: {
3773 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3774 // If we know the result of a setcc has the top bits zero, use this info.
3775 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3777 BitWidth > 1)
3778 Known.Zero.setBitsFrom(1);
3779 break;
3780 }
3781 case ISD::SHL: {
3782 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3783 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3784
3785 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3786 bool NSW = Op->getFlags().hasNoSignedWrap();
3787
3788 bool ShAmtNonZero = Known2.isNonZero();
3789
3790 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3791
3792 // Minimum shift low bits are known zero.
3793 if (std::optional<unsigned> ShMinAmt =
3794 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3795 Known.Zero.setLowBits(*ShMinAmt);
3796 break;
3797 }
3798 case ISD::SRL:
3799 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3800 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3801 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3802 Op->getFlags().hasExact());
3803
3804 // Minimum shift high bits are known zero.
3805 if (std::optional<unsigned> ShMinAmt =
3806 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3807 Known.Zero.setHighBits(*ShMinAmt);
3808 break;
3809 case ISD::SRA:
3810 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3811 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3812 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3813 Op->getFlags().hasExact());
3814 break;
3815 case ISD::ROTL:
3816 case ISD::ROTR:
3817 if (ConstantSDNode *C =
3818 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3819 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3820
3821 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3822
3823 // Canonicalize to ROTR.
3824 if (Opcode == ISD::ROTL && Amt != 0)
3825 Amt = BitWidth - Amt;
3826
3827 Known.Zero = Known.Zero.rotr(Amt);
3828 Known.One = Known.One.rotr(Amt);
3829 }
3830 break;
3831 case ISD::FSHL:
3832 case ISD::FSHR:
3833 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3834 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3835
3836 // For fshl, 0-shift returns the 1st arg.
3837 // For fshr, 0-shift returns the 2nd arg.
3838 if (Amt == 0) {
3839 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3840 DemandedElts, Depth + 1);
3841 break;
3842 }
3843
3844 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3845 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3846 const APInt ShAmt(BitWidth, Amt);
3847 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3848 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3849 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3850 : KnownBits::fshr(Known, Known2, ShAmt);
3851 }
3852 break;
3853 case ISD::SHL_PARTS:
3854 case ISD::SRA_PARTS:
3855 case ISD::SRL_PARTS: {
3856 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3857
3858 // Collect lo/hi source values and concatenate.
3859 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3860 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3861 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3862 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3863 Known = Known2.concat(Known);
3864
3865 // Collect shift amount.
3866 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3867
3868 if (Opcode == ISD::SHL_PARTS)
3869 Known = KnownBits::shl(Known, Known2);
3870 else if (Opcode == ISD::SRA_PARTS)
3871 Known = KnownBits::ashr(Known, Known2);
3872 else // if (Opcode == ISD::SRL_PARTS)
3873 Known = KnownBits::lshr(Known, Known2);
3874
3875 // TODO: Minimum shift low/high bits are known zero.
3876
3877 if (Op.getResNo() == 0)
3878 Known = Known.extractBits(LoBits, 0);
3879 else
3880 Known = Known.extractBits(HiBits, LoBits);
3881 break;
3882 }
3884 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3885 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3886 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3887 break;
3888 }
3889 case ISD::CTTZ:
3890 case ISD::CTTZ_ZERO_POISON: {
3891 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3892 // If we have a known 1, its position is our upper bound.
3893 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3894 unsigned LowBits = llvm::bit_width(PossibleTZ);
3895 Known.Zero.setBitsFrom(LowBits);
3896 break;
3897 }
3898 case ISD::CTLZ:
3899 case ISD::CTLZ_ZERO_POISON: {
3900 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3901 // If we have a known 1, its position is our upper bound.
3902 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3903 unsigned LowBits = llvm::bit_width(PossibleLZ);
3904 Known.Zero.setBitsFrom(LowBits);
3905 break;
3906 }
3907 case ISD::CTLS: {
3908 unsigned MinRedundantSignBits =
3909 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3910 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3912 Known = Range.toKnownBits();
3913 break;
3914 }
3915 case ISD::CTPOP: {
3916 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3917 // If we know some of the bits are zero, they can't be one.
3918 unsigned PossibleOnes = Known2.countMaxPopulation();
3919 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3920 break;
3921 }
3922 case ISD::PARITY: {
3923 // Parity returns 0 everywhere but the LSB.
3924 Known.Zero.setBitsFrom(1);
3925 break;
3926 }
3927 case ISD::PDEP: {
3928 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3929 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3930 Known = KnownBits::pdep(Known2, Known);
3931 break;
3932 }
3933 case ISD::PEXT: {
3934 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3935 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3936 Known = KnownBits::pext(Known2, Known);
3937 break;
3938 }
3939 case ISD::CLMUL: {
3940 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3941 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3942 Known = KnownBits::clmul(Known, Known2);
3943 break;
3944 }
3945 case ISD::MGATHER:
3946 case ISD::MLOAD: {
3947 ISD::LoadExtType ETy =
3948 (Opcode == ISD::MGATHER)
3949 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3950 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3951 if (ETy == ISD::ZEXTLOAD) {
3952 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3953 KnownBits Known0(MemVT.getScalarSizeInBits());
3954 return Known0.zext(BitWidth);
3955 }
3956 break;
3957 }
3958 case ISD::LOAD: {
3960 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3961 if (ISD::isNON_EXTLoad(LD) && Cst) {
3962 // Determine any common known bits from the loaded constant pool value.
3963 Type *CstTy = Cst->getType();
3964 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3965 !Op.getValueType().isScalableVector()) {
3966 // If its a vector splat, then we can (quickly) reuse the scalar path.
3967 // NOTE: We assume all elements match and none are UNDEF.
3968 if (CstTy->isVectorTy()) {
3969 if (const Constant *Splat = Cst->getSplatValue()) {
3970 Cst = Splat;
3971 CstTy = Cst->getType();
3972 }
3973 }
3974 // TODO - do we need to handle different bitwidths?
3975 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3976 // Iterate across all vector elements finding common known bits.
3977 Known.setAllConflict();
3978 for (unsigned i = 0; i != NumElts; ++i) {
3979 if (!DemandedElts[i])
3980 continue;
3981 if (Constant *Elt = Cst->getAggregateElement(i)) {
3982 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3983 const APInt &Value = CInt->getValue();
3984 Known.One &= Value;
3985 Known.Zero &= ~Value;
3986 continue;
3987 }
3988 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3989 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3990 Known.One &= Value;
3991 Known.Zero &= ~Value;
3992 continue;
3993 }
3994 }
3995 Known.One.clearAllBits();
3996 Known.Zero.clearAllBits();
3997 break;
3998 }
3999 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4000 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4001 Known = KnownBits::makeConstant(CInt->getValue());
4002 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4003 Known =
4004 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4005 }
4006 }
4007 }
4008 } else if (Op.getResNo() == 0) {
4009 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4010 KnownBits KnownScalarMemory(ScalarMemorySize);
4011 if (const MDNode *MD = LD->getRanges())
4012 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4013
4014 // Extend the Known bits from memory to the size of the scalar result.
4015 if (ISD::isZEXTLoad(Op.getNode()))
4016 Known = KnownScalarMemory.zext(BitWidth);
4017 else if (ISD::isSEXTLoad(Op.getNode()))
4018 Known = KnownScalarMemory.sext(BitWidth);
4019 else if (ISD::isEXTLoad(Op.getNode()))
4020 Known = KnownScalarMemory.anyext(BitWidth);
4021 else
4022 Known = KnownScalarMemory;
4023 assert(Known.getBitWidth() == BitWidth);
4024 return Known;
4025 }
4026 break;
4027 }
4029 if (Op.getValueType().isScalableVector())
4030 break;
4031 EVT InVT = Op.getOperand(0).getValueType();
4032 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4033 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4034 Known = Known.zext(BitWidth);
4035 break;
4036 }
4037 case ISD::ZERO_EXTEND: {
4038 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4039 Known = Known.zext(BitWidth);
4040 break;
4041 }
4043 if (Op.getValueType().isScalableVector())
4044 break;
4045 EVT InVT = Op.getOperand(0).getValueType();
4046 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4047 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4048 // If the sign bit is known to be zero or one, then sext will extend
4049 // it to the top bits, else it will just zext.
4050 Known = Known.sext(BitWidth);
4051 break;
4052 }
4053 case ISD::SIGN_EXTEND: {
4054 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4055 // If the sign bit is known to be zero or one, then sext will extend
4056 // it to the top bits, else it will just zext.
4057 Known = Known.sext(BitWidth);
4058 break;
4059 }
4061 if (Op.getValueType().isScalableVector())
4062 break;
4063 EVT InVT = Op.getOperand(0).getValueType();
4064 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4065 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4066 Known = Known.anyext(BitWidth);
4067 break;
4068 }
4069 case ISD::ANY_EXTEND: {
4070 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4071 Known = Known.anyext(BitWidth);
4072 break;
4073 }
4074 case ISD::TRUNCATE: {
4075 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4076 Known = Known.trunc(BitWidth);
4077 break;
4078 }
4079 case ISD::TRUNCATE_SSAT_S: {
4080 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4081 Known = Known.truncSSat(BitWidth);
4082 break;
4083 }
4084 case ISD::TRUNCATE_SSAT_U: {
4085 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4086 Known = Known.truncSSatU(BitWidth);
4087 break;
4088 }
4089 case ISD::TRUNCATE_USAT_U: {
4090 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4091 Known = Known.truncUSat(BitWidth);
4092 break;
4093 }
4094 case ISD::AssertZext: {
4095 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4097 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4098 Known.Zero |= (~InMask);
4099 Known.One &= (~Known.Zero);
4100 break;
4101 }
4102 case ISD::AssertAlign: {
4103 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4104 assert(LogOfAlign != 0);
4105
4106 // TODO: Should use maximum with source
4107 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4108 // well as clearing one bits.
4109 Known.Zero.setLowBits(LogOfAlign);
4110 Known.One.clearLowBits(LogOfAlign);
4111 break;
4112 }
4113 case ISD::AssertNoFPClass: {
4114 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4115
4116 FPClassTest NoFPClass =
4117 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4118 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4119 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4120 // Cannot be negative.
4121 Known.makeNonNegative();
4122 }
4123
4124 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4125 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4126 // Cannot be positive.
4127 Known.makeNegative();
4128 }
4129
4130 break;
4131 }
4132 case ISD::FABS:
4133 // fabs clears the sign bit
4134 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4135 Known.makeNonNegative();
4136 break;
4137 case ISD::FGETSIGN:
4138 // All bits are zero except the low bit.
4139 Known.Zero.setBitsFrom(1);
4140 break;
4141 case ISD::ADD: {
4142 SDNodeFlags Flags = Op.getNode()->getFlags();
4143 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4144 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4145 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4147 Op.getOperand(0), DemandedElts,
4149 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4150 Flags.hasNoUnsignedWrap(), SelfAdd);
4151 break;
4152 }
4153 case ISD::SUB: {
4154 SDNodeFlags Flags = Op.getNode()->getFlags();
4155 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4156 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4157 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4158 Flags.hasNoUnsignedWrap());
4159 break;
4160 }
4161 case ISD::USUBO:
4162 case ISD::SSUBO:
4163 case ISD::USUBO_CARRY:
4164 case ISD::SSUBO_CARRY:
4165 if (Op.getResNo() == 1) {
4166 // If we know the result of a setcc has the top bits zero, use this info.
4167 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4169 BitWidth > 1)
4170 Known.Zero.setBitsFrom(1);
4171 break;
4172 }
4173 [[fallthrough]];
4174 case ISD::SUBC: {
4175 assert(Op.getResNo() == 0 &&
4176 "We only compute knownbits for the difference here.");
4177
4178 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4179 KnownBits Borrow(1);
4180 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4181 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4182 // Borrow has bit width 1
4183 Borrow = Borrow.trunc(1);
4184 } else {
4185 Borrow.setAllZero();
4186 }
4187
4188 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4189 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4190 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4191 break;
4192 }
4193 case ISD::UADDO:
4194 case ISD::SADDO:
4195 case ISD::UADDO_CARRY:
4196 case ISD::SADDO_CARRY:
4197 if (Op.getResNo() == 1) {
4198 // If we know the result of a setcc has the top bits zero, use this info.
4199 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4201 BitWidth > 1)
4202 Known.Zero.setBitsFrom(1);
4203 break;
4204 }
4205 [[fallthrough]];
4206 case ISD::ADDC:
4207 case ISD::ADDE: {
4208 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4209
4210 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4211 KnownBits Carry(1);
4212 if (Opcode == ISD::ADDE)
4213 // Can't track carry from glue, set carry to unknown.
4214 Carry.resetAll();
4215 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4216 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4217 // Carry has bit width 1
4218 Carry = Carry.trunc(1);
4219 } else {
4220 Carry.setAllZero();
4221 }
4222
4223 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4224 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4225 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4226 break;
4227 }
4228 case ISD::UDIV: {
4229 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4230 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4231 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4232 break;
4233 }
4234 case ISD::SDIV: {
4235 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4236 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4237 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4238 break;
4239 }
4240 case ISD::SREM: {
4241 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4242 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4243 Known = KnownBits::srem(Known, Known2);
4244 break;
4245 }
4246 case ISD::UREM: {
4247 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4248 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4249 Known = KnownBits::urem(Known, Known2);
4250 break;
4251 }
4252 case ISD::EXTRACT_ELEMENT: {
4253 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4254 const unsigned Index = Op.getConstantOperandVal(1);
4255 const unsigned EltBitWidth = Op.getValueSizeInBits();
4256
4257 // Remove low part of known bits mask
4258 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4259 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4260
4261 // Remove high part of known bit mask
4262 Known = Known.trunc(EltBitWidth);
4263 break;
4264 }
4266 SDValue InVec = Op.getOperand(0);
4267 SDValue EltNo = Op.getOperand(1);
4268 EVT VecVT = InVec.getValueType();
4269 // computeKnownBits not yet implemented for scalable vectors.
4270 if (VecVT.isScalableVector())
4271 break;
4272 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4273 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4274
4275 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4276 // anything about the extended bits.
4277 if (BitWidth > EltBitWidth)
4278 Known = Known.trunc(EltBitWidth);
4279
4280 // If we know the element index, just demand that vector element, else for
4281 // an unknown element index, ignore DemandedElts and demand them all.
4282 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4283 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4284 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4285 DemandedSrcElts =
4286 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4287
4288 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4289 if (BitWidth > EltBitWidth)
4290 Known = Known.anyext(BitWidth);
4291 break;
4292 }
4294 if (Op.getValueType().isScalableVector())
4295 break;
4296
4297 // If we know the element index, split the demand between the
4298 // source vector and the inserted element, otherwise assume we need
4299 // the original demanded vector elements and the value.
4300 SDValue InVec = Op.getOperand(0);
4301 SDValue InVal = Op.getOperand(1);
4302 SDValue EltNo = Op.getOperand(2);
4303 bool DemandedVal = true;
4304 APInt DemandedVecElts = DemandedElts;
4305 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4306 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4307 unsigned EltIdx = CEltNo->getZExtValue();
4308 DemandedVal = !!DemandedElts[EltIdx];
4309 DemandedVecElts.clearBit(EltIdx);
4310 }
4311 Known.setAllConflict();
4312 if (DemandedVal) {
4313 Known2 = computeKnownBits(InVal, Depth + 1);
4314 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4315 }
4316 if (!!DemandedVecElts) {
4317 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4318 Known = Known.intersectWith(Known2);
4319 }
4320 break;
4321 }
4322 case ISD::BITREVERSE: {
4323 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4324 Known = Known2.reverseBits();
4325 break;
4326 }
4327 case ISD::BSWAP: {
4328 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4329 Known = Known2.byteSwap();
4330 break;
4331 }
4332 case ISD::ABS:
4333 case ISD::ABS_MIN_POISON: {
4334 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4335 Known = Known2.abs();
4336 Known.Zero.setHighBits(
4337 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4338 break;
4339 }
4340 case ISD::USUBSAT: {
4341 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4342 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4343 Known = KnownBits::usub_sat(Known, Known2);
4344 break;
4345 }
4346 case ISD::UMIN: {
4347 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4348 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4349 Known = KnownBits::umin(Known, Known2);
4350 break;
4351 }
4352 case ISD::UMAX: {
4353 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4354 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4355 Known = KnownBits::umax(Known, Known2);
4356 break;
4357 }
4358 case ISD::SMIN:
4359 case ISD::SMAX: {
4360 // If we have a clamp pattern, we know that the number of sign bits will be
4361 // the minimum of the clamp min/max range.
4362 bool IsMax = (Opcode == ISD::SMAX);
4363 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4364 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4365 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4366 CstHigh =
4367 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4368 if (CstLow && CstHigh) {
4369 if (!IsMax)
4370 std::swap(CstLow, CstHigh);
4371
4372 const APInt &ValueLow = CstLow->getAPIntValue();
4373 const APInt &ValueHigh = CstHigh->getAPIntValue();
4374 if (ValueLow.sle(ValueHigh)) {
4375 unsigned LowSignBits = ValueLow.getNumSignBits();
4376 unsigned HighSignBits = ValueHigh.getNumSignBits();
4377 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4378 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4379 Known.One.setHighBits(MinSignBits);
4380 break;
4381 }
4382 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4383 Known.Zero.setHighBits(MinSignBits);
4384 break;
4385 }
4386 }
4387 }
4388
4389 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4390 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4391 if (IsMax)
4392 Known = KnownBits::smax(Known, Known2);
4393 else
4394 Known = KnownBits::smin(Known, Known2);
4395
4396 // For SMAX, if CstLow is non-negative we know the result will be
4397 // non-negative and thus all sign bits are 0.
4398 // TODO: There's an equivalent of this for smin with negative constant for
4399 // known ones.
4400 if (IsMax && CstLow) {
4401 const APInt &ValueLow = CstLow->getAPIntValue();
4402 if (ValueLow.isNonNegative()) {
4403 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4404 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4405 }
4406 }
4407
4408 break;
4409 }
4410 case ISD::UINT_TO_FP: {
4411 Known.makeNonNegative();
4412 break;
4413 }
4414 case ISD::SINT_TO_FP: {
4415 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4416 if (Known2.isNonNegative())
4417 Known.makeNonNegative();
4418 else if (Known2.isNegative())
4419 Known.makeNegative();
4420 break;
4421 }
4422 case ISD::FP_TO_UINT_SAT: {
4423 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4424 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4426 break;
4427 }
4428 case ISD::ATOMIC_LOAD: {
4429 // If we are looking at the loaded value.
4430 if (Op.getResNo() == 0) {
4431 auto *AT = cast<AtomicSDNode>(Op);
4432 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4433 KnownBits KnownScalarMemory(ScalarMemorySize);
4434 if (const MDNode *MD = AT->getRanges())
4435 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4436
4437 switch (AT->getExtensionType()) {
4438 case ISD::ZEXTLOAD:
4439 Known = KnownScalarMemory.zext(BitWidth);
4440 break;
4441 case ISD::SEXTLOAD:
4442 Known = KnownScalarMemory.sext(BitWidth);
4443 break;
4444 case ISD::EXTLOAD:
4445 switch (TLI->getExtendForAtomicOps()) {
4446 case ISD::ZERO_EXTEND:
4447 Known = KnownScalarMemory.zext(BitWidth);
4448 break;
4449 case ISD::SIGN_EXTEND:
4450 Known = KnownScalarMemory.sext(BitWidth);
4451 break;
4452 default:
4453 Known = KnownScalarMemory.anyext(BitWidth);
4454 break;
4455 }
4456 break;
4457 case ISD::NON_EXTLOAD:
4458 Known = KnownScalarMemory;
4459 break;
4460 }
4461 assert(Known.getBitWidth() == BitWidth);
4462 }
4463 break;
4464 }
4466 if (Op.getResNo() == 1) {
4467 // The boolean result conforms to getBooleanContents.
4468 // If we know the result of a setcc has the top bits zero, use this info.
4469 // We know that we have an integer-based boolean since these operations
4470 // are only available for integer.
4471 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4473 BitWidth > 1)
4474 Known.Zero.setBitsFrom(1);
4475 break;
4476 }
4477 [[fallthrough]];
4479 case ISD::ATOMIC_SWAP:
4490 case ISD::ATOMIC_LOAD_UMAX: {
4491 // If we are looking at the loaded value.
4492 if (Op.getResNo() == 0) {
4493 auto *AT = cast<AtomicSDNode>(Op);
4494 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4495
4496 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4497 Known.Zero.setBitsFrom(MemBits);
4498 }
4499 break;
4500 }
4501 case ISD::FrameIndex:
4502 case ISD::TargetFrameIndex: {
4503 const MachineFunction &MF = getMachineFunction();
4504 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4505 TLI->computeKnownBitsForStackObjectPointer(
4506 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4507 break;
4508 }
4509
4510 default:
4511 if (Opcode < ISD::BUILTIN_OP_END)
4512 break;
4513 [[fallthrough]];
4517 // Allow the target to implement this method for its nodes.
4518 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4519 break;
4520 }
4521
4522 return Known;
4523}
4524
4525/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4538
4541 // X + 0 never overflow
4542 if (isNullConstant(N1))
4543 return OFK_Never;
4544
4545 // If both operands each have at least two sign bits, the addition
4546 // cannot overflow.
4547 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4548 return OFK_Never;
4549
4550 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4551 return OFK_Sometime;
4552}
4553
4556 // X + 0 never overflow
4557 if (isNullConstant(N1))
4558 return OFK_Never;
4559
4560 // mulhi + 1 never overflow
4561 KnownBits N1Known = computeKnownBits(N1);
4562 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4563 N1Known.getMaxValue().ult(2))
4564 return OFK_Never;
4565
4566 KnownBits N0Known = computeKnownBits(N0);
4567 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4568 N0Known.getMaxValue().ult(2))
4569 return OFK_Never;
4570
4571 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4572 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4573 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4574 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4575}
4576
4579 // X - 0 never overflow
4580 if (isNullConstant(N1))
4581 return OFK_Never;
4582
4583 // If both operands each have at least two sign bits, the subtraction
4584 // cannot overflow.
4585 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4586 return OFK_Never;
4587
4588 KnownBits N0Known = computeKnownBits(N0);
4589 KnownBits N1Known = computeKnownBits(N1);
4590 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4591 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4592 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4593}
4594
4597 // X - 0 never overflow
4598 if (isNullConstant(N1))
4599 return OFK_Never;
4600
4601 ConstantRange N0Range =
4602 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4603 ConstantRange N1Range =
4604 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4605 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4606}
4607
4610 // X * 0 and X * 1 never overflow.
4611 if (isNullConstant(N1) || isOneConstant(N1))
4612 return OFK_Never;
4613
4616 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4617}
4618
4621 // X * 0 and X * 1 never overflow.
4622 if (isNullConstant(N1) || isOneConstant(N1))
4623 return OFK_Never;
4624
4625 // Get the size of the result.
4626 unsigned BitWidth = N0.getScalarValueSizeInBits();
4627
4628 // Sum of the sign bits.
4629 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4630
4631 // If we have enough sign bits, then there's no overflow.
4632 if (SignBits > BitWidth + 1)
4633 return OFK_Never;
4634
4635 if (SignBits == BitWidth + 1) {
4636 // The overflow occurs when the true multiplication of the
4637 // the operands is the minimum negative number.
4638 KnownBits N0Known = computeKnownBits(N0);
4639 KnownBits N1Known = computeKnownBits(N1);
4640 // If one of the operands is non-negative, then there's no
4641 // overflow.
4642 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4643 return OFK_Never;
4644 }
4645
4646 return OFK_Sometime;
4647}
4648
4650 unsigned Depth) const {
4651 APInt DemandedElts = getDemandAllEltsMask(Op);
4652 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4653}
4654
4656 const APInt &DemandedElts,
4657 bool ForSigned,
4658 unsigned Depth) const {
4659 EVT VT = Op.getValueType();
4660 unsigned BitWidth = VT.getScalarSizeInBits();
4661
4662 if (Depth >= MaxRecursionDepth)
4663 return ConstantRange::getFull(BitWidth);
4664
4665 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4666 return ConstantRange(C->getAPIntValue());
4667
4668 unsigned Opcode = Op.getOpcode();
4669 switch (Opcode) {
4670 case ISD::VSCALE: {
4672 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4673 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4674 }
4675 default:
4676 break;
4677 }
4678
4679 return ConstantRange::getFull(BitWidth);
4680}
4681
4684 unsigned Depth) const {
4685 APInt DemandedElts = getDemandAllEltsMask(Op);
4686 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4687 Depth);
4688}
4689
4691 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4692 unsigned Depth) const {
4693 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4695 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4698 return CR1.intersectWith(CR2, RangeType);
4699}
4700
4702 unsigned Depth) const {
4703 APInt DemandedElts = getDemandAllEltsMask(Val);
4704 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4705}
4706
4708 const APInt &DemandedElts,
4709 bool OrZero, unsigned Depth) const {
4710 if (Depth >= MaxRecursionDepth)
4711 return false; // Limit search depth.
4712
4713 EVT OpVT = Val.getValueType();
4714 unsigned BitWidth = OpVT.getScalarSizeInBits();
4715 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4716 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4717 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4718 assert(
4719 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4720 "Unexpected vector size");
4721
4722 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4723 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4724 return (OrZero && V.isZero()) || V.isPowerOf2();
4725 };
4726
4727 // Is the constant a known power of 2 or zero?
4728 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4729 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4730 return true;
4731
4732 switch (Val.getOpcode()) {
4734 SDValue InVec = Val.getOperand(0);
4735 SDValue EltNo = Val.getOperand(1);
4736 EVT VecVT = InVec.getValueType();
4737
4738 // Skip scalable vectors or implicit extensions.
4739 if (VecVT.isScalableVector() ||
4740 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4741 break;
4742
4743 // If we know the element index, just demand that vector element, else for
4744 // an unknown element index, ignore DemandedElts and demand them all.
4745 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4746 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4747 APInt DemandedSrcElts =
4748 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4749 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4750 : APInt::getAllOnes(NumSrcElts);
4751 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4752 }
4753
4754 case ISD::AND: {
4755 // Looking for `x & -x` pattern:
4756 // If x == 0:
4757 // x & -x -> 0
4758 // If x != 0:
4759 // x & -x -> non-zero pow2
4760 // so if we find the pattern return whether we know `x` is non-zero.
4761 SDValue X, Z;
4762 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4763 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4764 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4765 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4766 break;
4767 }
4768
4769 case ISD::SHL: {
4770 // A left-shift of a constant one will have exactly one bit set because
4771 // shifting the bit off the end is undefined.
4772 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4773 if (C && C->getAPIntValue() == 1)
4774 return true;
4775 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4776 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4777 Depth + 1);
4778 }
4779
4780 case ISD::SRL: {
4781 // A logical right-shift of a constant sign-bit will have exactly
4782 // one bit set.
4783 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4784 if (C && C->getAPIntValue().isSignMask())
4785 return true;
4786 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4787 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4788 Depth + 1);
4789 }
4790
4791 case ISD::TRUNCATE:
4792 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4793 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4794 Depth + 1);
4795
4796 case ISD::ROTL:
4797 case ISD::ROTR:
4798 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4799 Depth + 1);
4800 case ISD::BSWAP:
4801 case ISD::BITREVERSE:
4802 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4803 Depth + 1);
4804
4805 case ISD::SMIN:
4806 case ISD::SMAX:
4807 case ISD::UMIN:
4808 case ISD::UMAX:
4809 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4810 Depth + 1) &&
4811 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4812 Depth + 1);
4813
4814 case ISD::SELECT:
4815 case ISD::VSELECT:
4816 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4817 Depth + 1) &&
4818 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4819 Depth + 1);
4820
4821 case ISD::ZERO_EXTEND:
4822 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4823 Depth + 1);
4824
4825 case ISD::VSCALE:
4826 // vscale(power-of-two) is a power-of-two
4827 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4828 Depth + 1);
4829
4830 case ISD::VECTOR_SHUFFLE: {
4832 // Demanded elements with undef shuffle mask elements are unknown
4833 // - we cannot guarantee they are a power of two, so return false.
4834 APInt DemandedLHS, DemandedRHS;
4836 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4837 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4838 DemandedLHS, DemandedRHS))
4839 return false;
4840
4841 // All demanded elements from LHS must be known power of two.
4842 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4843 OrZero, Depth + 1))
4844 return false;
4845
4846 // All demanded elements from RHS must be known power of two.
4847 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4848 OrZero, Depth + 1))
4849 return false;
4850
4851 return true;
4852 }
4853 }
4854
4855 // More could be done here, though the above checks are enough
4856 // to handle some common cases.
4857 return false;
4858}
4859
4861 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4862 return C1->getValueAPF().getExactLog2Abs() >= 0;
4863
4864 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4865 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4866
4867 return false;
4868}
4869
4871 APInt DemandedElts = getDemandAllEltsMask(Op);
4872 return ComputeNumSignBits(Op, DemandedElts, Depth);
4873}
4874
4875unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4876 unsigned Depth) const {
4877 EVT VT = Op.getValueType();
4878 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4879 unsigned VTBits = VT.getScalarSizeInBits();
4880 unsigned NumElts = DemandedElts.getBitWidth();
4881 unsigned Tmp, Tmp2;
4882 unsigned FirstAnswer = 1;
4883
4884 assert((!VT.isScalableVector() || NumElts == 1) &&
4885 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4886
4887 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4888 const APInt &Val = C->getAPIntValue();
4889 return Val.getNumSignBits();
4890 }
4891
4892 if (Depth >= MaxRecursionDepth)
4893 return 1; // Limit search depth.
4894
4895 if (!DemandedElts)
4896 return 1; // No demanded elts, better to assume we don't know anything.
4897
4898 unsigned Opcode = Op.getOpcode();
4899 switch (Opcode) {
4900 default: break;
4901 case ISD::AssertSext:
4902 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4903 return VTBits-Tmp+1;
4904 case ISD::AssertZext:
4905 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4906 return VTBits-Tmp;
4907 case ISD::FREEZE:
4908 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4910 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4911 break;
4912 case ISD::MERGE_VALUES:
4913 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4914 Depth + 1);
4915 case ISD::SPLAT_VECTOR: {
4916 // Check if the sign bits of source go down as far as the truncated value.
4917 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4918 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4919 if (NumSrcSignBits > (NumSrcBits - VTBits))
4920 return NumSrcSignBits - (NumSrcBits - VTBits);
4921 break;
4922 }
4923 case ISD::BUILD_VECTOR:
4924 assert(!VT.isScalableVector());
4925 Tmp = VTBits;
4926 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4927 if (!DemandedElts[i])
4928 continue;
4929
4930 SDValue SrcOp = Op.getOperand(i);
4931 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4932 // for constant nodes to ensure we only look at the sign bits.
4934 APInt T = C->getAPIntValue().trunc(VTBits);
4935 Tmp2 = T.getNumSignBits();
4936 } else {
4937 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4938
4939 if (SrcOp.getValueSizeInBits() != VTBits) {
4940 assert(SrcOp.getValueSizeInBits() > VTBits &&
4941 "Expected BUILD_VECTOR implicit truncation");
4942 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4943 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4944 }
4945 }
4946 Tmp = std::min(Tmp, Tmp2);
4947 }
4948 return Tmp;
4949
4950 case ISD::VECTOR_COMPRESS: {
4951 SDValue Vec = Op.getOperand(0);
4952 SDValue PassThru = Op.getOperand(2);
4953 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
4954 if (Tmp == 1)
4955 return 1;
4956 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
4957 Tmp = std::min(Tmp, Tmp2);
4958 return Tmp;
4959 }
4960
4961 case ISD::VECTOR_SHUFFLE: {
4962 // Collect the minimum number of sign bits that are shared by every vector
4963 // element referenced by the shuffle.
4964 APInt DemandedLHS, DemandedRHS;
4966 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4967 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4968 DemandedLHS, DemandedRHS))
4969 return 1;
4970
4971 Tmp = std::numeric_limits<unsigned>::max();
4972 if (!!DemandedLHS)
4973 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
4974 if (!!DemandedRHS) {
4975 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
4976 Tmp = std::min(Tmp, Tmp2);
4977 }
4978 // If we don't know anything, early out and try computeKnownBits fall-back.
4979 if (Tmp == 1)
4980 break;
4981 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4982 return Tmp;
4983 }
4984
4985 case ISD::BITCAST: {
4986 if (VT.isScalableVector())
4987 break;
4988 SDValue N0 = Op.getOperand(0);
4989 EVT SrcVT = N0.getValueType();
4990 unsigned SrcBits = SrcVT.getScalarSizeInBits();
4991
4992 // Ignore bitcasts from unsupported types..
4993 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
4994 break;
4995
4996 // Fast handling of 'identity' bitcasts.
4997 if (VTBits == SrcBits)
4998 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
4999
5000 bool IsLE = getDataLayout().isLittleEndian();
5001
5002 // Bitcast 'large element' scalar/vector to 'small element' vector.
5003 if ((SrcBits % VTBits) == 0) {
5004 assert(VT.isVector() && "Expected bitcast to vector");
5005
5006 unsigned Scale = SrcBits / VTBits;
5007 APInt SrcDemandedElts =
5008 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5009
5010 // Fast case - sign splat can be simply split across the small elements.
5011 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5012 if (Tmp == SrcBits)
5013 return VTBits;
5014
5015 // Slow case - determine how far the sign extends into each sub-element.
5016 Tmp2 = VTBits;
5017 for (unsigned i = 0; i != NumElts; ++i)
5018 if (DemandedElts[i]) {
5019 unsigned SubOffset = i % Scale;
5020 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5021 SubOffset = SubOffset * VTBits;
5022 if (Tmp <= SubOffset)
5023 return 1;
5024 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5025 }
5026 return Tmp2;
5027 }
5028 break;
5029 }
5030
5032 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5033 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5034 return VTBits - Tmp + 1;
5035 case ISD::SIGN_EXTEND:
5036 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5037 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5039 // Max of the input and what this extends.
5040 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5041 Tmp = VTBits-Tmp+1;
5042 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5043 return std::max(Tmp, Tmp2);
5045 if (VT.isScalableVector())
5046 break;
5047 SDValue Src = Op.getOperand(0);
5048 EVT SrcVT = Src.getValueType();
5049 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5050 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5051 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5052 }
5053 case ISD::SRA:
5054 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5055 // SRA X, C -> adds C sign bits.
5056 if (std::optional<unsigned> ShAmt =
5057 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5058 Tmp = std::min(Tmp + *ShAmt, VTBits);
5059 return Tmp;
5060 case ISD::SHL:
5061 if (std::optional<ConstantRange> ShAmtRange =
5062 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5063 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5064 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5065 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5066 // shifted out, then we can compute the number of sign bits for the
5067 // operand being extended. A future improvement could be to pass along the
5068 // "shifted left by" information in the recursive calls to
5069 // ComputeKnownSignBits. Allowing us to handle this more generically.
5070 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5071 SDValue Ext = Op.getOperand(0);
5072 EVT ExtVT = Ext.getValueType();
5073 SDValue Extendee = Ext.getOperand(0);
5074 EVT ExtendeeVT = Extendee.getValueType();
5075 unsigned SizeDifference =
5076 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5077 if (SizeDifference <= MinShAmt) {
5078 Tmp = SizeDifference +
5079 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5080 if (MaxShAmt < Tmp)
5081 return Tmp - MaxShAmt;
5082 }
5083 }
5084 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5085 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5086 if (MaxShAmt < Tmp)
5087 return Tmp - MaxShAmt;
5088 }
5089 break;
5090 case ISD::AND:
5091 case ISD::OR:
5092 case ISD::XOR: // NOT is handled here.
5093 // Logical binary ops preserve the number of sign bits at the worst.
5094 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5095 if (Tmp != 1) {
5096 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5097 FirstAnswer = std::min(Tmp, Tmp2);
5098 // We computed what we know about the sign bits as our first
5099 // answer. Now proceed to the generic code that uses
5100 // computeKnownBits, and pick whichever answer is better.
5101 }
5102 break;
5103
5104 case ISD::SELECT:
5105 case ISD::VSELECT:
5106 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5107 if (Tmp == 1) return 1; // Early out.
5108 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5109 return std::min(Tmp, Tmp2);
5110 case ISD::SELECT_CC:
5111 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5112 if (Tmp == 1) return 1; // Early out.
5113 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5114 return std::min(Tmp, Tmp2);
5115
5116 case ISD::SMIN:
5117 case ISD::SMAX: {
5118 // If we have a clamp pattern, we know that the number of sign bits will be
5119 // the minimum of the clamp min/max range.
5120 bool IsMax = (Opcode == ISD::SMAX);
5121 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5122 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5123 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5124 CstHigh =
5125 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5126 if (CstLow && CstHigh) {
5127 if (!IsMax)
5128 std::swap(CstLow, CstHigh);
5129 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5130 Tmp = CstLow->getAPIntValue().getNumSignBits();
5131 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5132 return std::min(Tmp, Tmp2);
5133 }
5134 }
5135
5136 // Fallback - just get the minimum number of sign bits of the operands.
5137 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5138 if (Tmp == 1)
5139 return 1; // Early out.
5140 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5141 return std::min(Tmp, Tmp2);
5142 }
5143 case ISD::UMIN:
5144 case ISD::UMAX:
5145 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5146 if (Tmp == 1)
5147 return 1; // Early out.
5148 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5149 return std::min(Tmp, Tmp2);
5150 case ISD::SSUBO_CARRY:
5151 case ISD::USUBO_CARRY:
5152 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5153 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5154 return VTBits;
5155 [[fallthrough]];
5156 case ISD::SADDO:
5157 case ISD::UADDO:
5158 case ISD::SADDO_CARRY:
5159 case ISD::UADDO_CARRY:
5160 case ISD::SSUBO:
5161 case ISD::USUBO:
5162 case ISD::SMULO:
5163 case ISD::UMULO:
5164 if (Op.getResNo() != 1)
5165 break;
5166 // The boolean result conforms to getBooleanContents. Fall through.
5167 // If setcc returns 0/-1, all bits are sign bits.
5168 // We know that we have an integer-based boolean since these operations
5169 // are only available for integer.
5170 if (TLI->getBooleanContents(VT.isVector(), false) ==
5172 return VTBits;
5173 break;
5174 case ISD::SETCC:
5175 case ISD::SETCCCARRY:
5176 case ISD::STRICT_FSETCC:
5177 case ISD::STRICT_FSETCCS: {
5178 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5179 // If setcc returns 0/-1, all bits are sign bits.
5180 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5182 return VTBits;
5183 break;
5184 }
5186 // Semantically similar to icmp ult.
5187 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5189 return VTBits;
5190 break;
5191 case ISD::ROTL:
5192 case ISD::ROTR: {
5193 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5194 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5195 FirstAnswer = SignBitsOps::rot(
5196 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5197 Opcode == ISD::ROTR);
5198 break;
5199 }
5200 case ISD::ADD:
5201 case ISD::ADDC:
5202 // TODO: Move Operand 1 check before Operand 0 check
5203 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5204 if (Tmp == 1) return 1; // Early out.
5205
5206 // Special case decrementing a value (ADD X, -1):
5207 if (ConstantSDNode *CRHS =
5208 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5209 if (CRHS->isAllOnes()) {
5211 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5212
5213 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5214 // sign bits set.
5215 if ((Known.Zero | 1).isAllOnes())
5216 return VTBits;
5217
5218 // If we are subtracting one from a positive number, there is no carry
5219 // out of the result.
5220 if (Known.isNonNegative())
5221 return Tmp;
5222 }
5223
5224 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5225 if (Tmp2 == 1) return 1; // Early out.
5226
5227 // Add can have at most one carry bit. Thus we know that the output
5228 // is, at worst, one more bit than the inputs.
5229 return std::min(Tmp, Tmp2) - 1;
5230 case ISD::SUB:
5231 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5232 if (Tmp2 == 1) return 1; // Early out.
5233
5234 // Handle NEG.
5235 if (ConstantSDNode *CLHS =
5236 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5237 if (CLHS->isZero()) {
5239 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5240 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5241 // sign bits set.
5242 if ((Known.Zero | 1).isAllOnes())
5243 return VTBits;
5244
5245 // If the input is known to be positive (the sign bit is known clear),
5246 // the output of the NEG has the same number of sign bits as the input.
5247 if (Known.isNonNegative())
5248 return Tmp2;
5249
5250 // Otherwise, we treat this like a SUB.
5251 }
5252
5253 // Sub can have at most one carry bit. Thus we know that the output
5254 // is, at worst, one more bit than the inputs.
5255 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5256 if (Tmp == 1) return 1; // Early out.
5257 return std::min(Tmp, Tmp2) - 1;
5258 case ISD::MUL: {
5259 // The output of the Mul can be at most twice the valid bits in the inputs.
5260 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5261 if (SignBitsOp0 == 1)
5262 break;
5263 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5264 if (SignBitsOp1 == 1)
5265 break;
5266 unsigned OutValidBits =
5267 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5268 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5269 }
5270 case ISD::AVGCEILS:
5271 case ISD::AVGFLOORS:
5272 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5273 if (Tmp == 1)
5274 return 1; // Early out.
5275 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5276 return std::min(Tmp, Tmp2);
5277 case ISD::SREM:
5278 // The sign bit is the LHS's sign bit, except when the result of the
5279 // remainder is zero. The magnitude of the result should be less than or
5280 // equal to the magnitude of the LHS. Therefore, the result should have
5281 // at least as many sign bits as the left hand side.
5282 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5283 case ISD::TRUNCATE: {
5284 // Check if the sign bits of source go down as far as the truncated value.
5285 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5286 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5287 if (NumSrcSignBits > (NumSrcBits - VTBits))
5288 return NumSrcSignBits - (NumSrcBits - VTBits);
5289 break;
5290 }
5291 case ISD::EXTRACT_ELEMENT: {
5292 if (VT.isScalableVector())
5293 break;
5294 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5295 const int BitWidth = Op.getValueSizeInBits();
5296 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5297
5298 // Get reverse index (starting from 1), Op1 value indexes elements from
5299 // little end. Sign starts at big end.
5300 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5301
5302 // If the sign portion ends in our element the subtraction gives correct
5303 // result. Otherwise it gives either negative or > bitwidth result
5304 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5305 }
5307 if (VT.isScalableVector())
5308 break;
5309 // If we know the element index, split the demand between the
5310 // source vector and the inserted element, otherwise assume we need
5311 // the original demanded vector elements and the value.
5312 SDValue InVec = Op.getOperand(0);
5313 SDValue InVal = Op.getOperand(1);
5314 SDValue EltNo = Op.getOperand(2);
5315 bool DemandedVal = true;
5316 APInt DemandedVecElts = DemandedElts;
5317 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5318 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5319 unsigned EltIdx = CEltNo->getZExtValue();
5320 DemandedVal = !!DemandedElts[EltIdx];
5321 DemandedVecElts.clearBit(EltIdx);
5322 }
5323 Tmp = std::numeric_limits<unsigned>::max();
5324 if (DemandedVal) {
5325 // TODO - handle implicit truncation of inserted elements.
5326 if (InVal.getScalarValueSizeInBits() != VTBits)
5327 break;
5328 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5329 Tmp = std::min(Tmp, Tmp2);
5330 }
5331 if (!!DemandedVecElts) {
5332 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5333 Tmp = std::min(Tmp, Tmp2);
5334 }
5335 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5336 return Tmp;
5337 }
5339 SDValue InVec = Op.getOperand(0);
5340 SDValue EltNo = Op.getOperand(1);
5341 EVT VecVT = InVec.getValueType();
5342 // ComputeNumSignBits not yet implemented for scalable vectors.
5343 if (VecVT.isScalableVector())
5344 break;
5345 const unsigned BitWidth = Op.getValueSizeInBits();
5346 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5347 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5348
5349 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5350 // anything about sign bits. But if the sizes match we can derive knowledge
5351 // about sign bits from the vector operand.
5352 if (BitWidth != EltBitWidth)
5353 break;
5354
5355 // If we know the element index, just demand that vector element, else for
5356 // an unknown element index, ignore DemandedElts and demand them all.
5357 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5358 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5359 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5360 DemandedSrcElts =
5361 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5362
5363 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5364 }
5366 // Offset the demanded elts by the subvector index.
5367 SDValue Src = Op.getOperand(0);
5368
5369 APInt DemandedSrcElts;
5370 if (Src.getValueType().isScalableVector())
5371 DemandedSrcElts = APInt(1, 1);
5372 else {
5373 uint64_t Idx = Op.getConstantOperandVal(1);
5374 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5375 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5376 }
5377 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5378 }
5379 case ISD::CONCAT_VECTORS: {
5380 if (VT.isScalableVector())
5381 break;
5382 // Determine the minimum number of sign bits across all demanded
5383 // elts of the input vectors. Early out if the result is already 1.
5384 Tmp = std::numeric_limits<unsigned>::max();
5385 EVT SubVectorVT = Op.getOperand(0).getValueType();
5386 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5387 unsigned NumSubVectors = Op.getNumOperands();
5388 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5389 APInt DemandedSub =
5390 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5391 if (!DemandedSub)
5392 continue;
5393 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5394 Tmp = std::min(Tmp, Tmp2);
5395 }
5396 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5397 return Tmp;
5398 }
5399 case ISD::INSERT_SUBVECTOR: {
5400 if (VT.isScalableVector())
5401 break;
5402 // Demand any elements from the subvector and the remainder from the src its
5403 // inserted into.
5404 SDValue Src = Op.getOperand(0);
5405 SDValue Sub = Op.getOperand(1);
5406 uint64_t Idx = Op.getConstantOperandVal(2);
5407 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5408 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5409 APInt DemandedSrcElts = DemandedElts;
5410 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5411
5412 Tmp = std::numeric_limits<unsigned>::max();
5413 if (!!DemandedSubElts) {
5414 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5415 if (Tmp == 1)
5416 return 1; // early-out
5417 }
5418 if (!!DemandedSrcElts) {
5419 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5420 Tmp = std::min(Tmp, Tmp2);
5421 }
5422 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5423 return Tmp;
5424 }
5425 case ISD::LOAD: {
5426 // If we are looking at the loaded value of the SDNode.
5427 if (Op.getResNo() != 0)
5428 break;
5429
5431 if (const MDNode *Ranges = LD->getRanges()) {
5432 if (DemandedElts != 1)
5433 break;
5434
5436 if (VTBits > CR.getBitWidth()) {
5437 switch (LD->getExtensionType()) {
5438 case ISD::SEXTLOAD:
5439 CR = CR.signExtend(VTBits);
5440 break;
5441 case ISD::ZEXTLOAD:
5442 CR = CR.zeroExtend(VTBits);
5443 break;
5444 default:
5445 break;
5446 }
5447 }
5448
5449 if (VTBits != CR.getBitWidth())
5450 break;
5451 return std::min(CR.getSignedMin().getNumSignBits(),
5453 }
5454
5455 unsigned ExtType = LD->getExtensionType();
5456 switch (ExtType) {
5457 default:
5458 break;
5459 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5460 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5461 return VTBits - Tmp + 1;
5462 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5463 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5464 return VTBits - Tmp;
5465 case ISD::NON_EXTLOAD:
5466 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5467 // We only need to handle vectors - computeKnownBits should handle
5468 // scalar cases.
5469 Type *CstTy = Cst->getType();
5470 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5471 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5472 VTBits == CstTy->getScalarSizeInBits()) {
5473 Tmp = VTBits;
5474 for (unsigned i = 0; i != NumElts; ++i) {
5475 if (!DemandedElts[i])
5476 continue;
5477 if (Constant *Elt = Cst->getAggregateElement(i)) {
5478 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5479 const APInt &Value = CInt->getValue();
5480 Tmp = std::min(Tmp, Value.getNumSignBits());
5481 continue;
5482 }
5483 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5484 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5485 Tmp = std::min(Tmp, Value.getNumSignBits());
5486 continue;
5487 }
5488 }
5489 // Unknown type. Conservatively assume no bits match sign bit.
5490 return 1;
5491 }
5492 return Tmp;
5493 }
5494 }
5495 break;
5496 }
5497
5498 break;
5499 }
5502 case ISD::ATOMIC_SWAP:
5514 case ISD::ATOMIC_LOAD: {
5515 auto *AT = cast<AtomicSDNode>(Op);
5516 // If we are looking at the loaded value.
5517 if (Op.getResNo() == 0) {
5518 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5519 if (Tmp == VTBits)
5520 return 1; // early-out
5521
5522 // For atomic_load, prefer to use the extension type.
5523 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5524 switch (AT->getExtensionType()) {
5525 default:
5526 break;
5527 case ISD::SEXTLOAD:
5528 return VTBits - Tmp + 1;
5529 case ISD::ZEXTLOAD:
5530 return VTBits - Tmp;
5531 }
5532 }
5533
5534 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5535 return VTBits - Tmp + 1;
5536 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5537 return VTBits - Tmp;
5538 }
5539 break;
5540 }
5541 }
5542
5543 // Allow the target to implement this method for its nodes.
5544 if (Opcode >= ISD::BUILTIN_OP_END ||
5545 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5546 Opcode == ISD::INTRINSIC_W_CHAIN ||
5547 Opcode == ISD::INTRINSIC_VOID) {
5548 // TODO: This can probably be removed once target code is audited. This
5549 // is here purely to reduce patch size and review complexity.
5550 if (!VT.isScalableVector()) {
5551 unsigned NumBits =
5552 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5553 if (NumBits > 1)
5554 FirstAnswer = std::max(FirstAnswer, NumBits);
5555 }
5556 }
5557
5558 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5559 // use this information.
5560 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5561 return std::max(FirstAnswer, Known.countMinSignBits());
5562}
5563
5565 unsigned Depth) const {
5566 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5567 return Op.getScalarValueSizeInBits() - SignBits + 1;
5568}
5569
5571 const APInt &DemandedElts,
5572 unsigned Depth) const {
5573 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5574 return Op.getScalarValueSizeInBits() - SignBits + 1;
5575}
5576
5578 UndefPoisonKind Kind,
5579 unsigned Depth) const {
5580 // Early out for FREEZE.
5581 if (Op.getOpcode() == ISD::FREEZE)
5582 return true;
5583
5584 APInt DemandedElts = getDemandAllEltsMask(Op);
5585 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5586}
5587
5589 const APInt &DemandedElts,
5590 UndefPoisonKind Kind,
5591 unsigned Depth) const {
5592 unsigned Opcode = Op.getOpcode();
5593
5594 // Early out for FREEZE.
5595 if (Opcode == ISD::FREEZE)
5596 return true;
5597
5598 if (Depth >= MaxRecursionDepth)
5599 return false; // Limit search depth.
5600
5601 if (isIntOrFPConstant(Op))
5602 return true;
5603
5604 switch (Opcode) {
5605 case ISD::CONDCODE:
5606 case ISD::VALUETYPE:
5607 case ISD::FrameIndex:
5609 case ISD::CopyFromReg:
5610 return true;
5611
5612 case ISD::POISON:
5613 return !includesPoison(Kind);
5614
5615 case ISD::UNDEF:
5616 return !includesUndef(Kind);
5617
5618 case ISD::BITCAST: {
5619 SDValue Src = Op.getOperand(0);
5620 EVT SrcVT = Src.getValueType();
5621 EVT DstVT = Op.getValueType();
5622
5623 if (!SrcVT.isVector() || !DstVT.isVector())
5624 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5625
5626 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5627 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5628 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5629 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5630
5631 if (SrcEltBits == DstEltBits)
5632 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5633 Depth + 1);
5634
5635 if (SrcEltBits < DstEltBits) {
5636 if (DstEltBits % SrcEltBits != 0)
5637 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5638
5639 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5640 "Unexpected vector bitcast");
5641 APInt DemandedSrcElts =
5642 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5643 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5644 Depth + 1);
5645 }
5646
5647 if (SrcEltBits % DstEltBits != 0)
5648 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5649
5650 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5651 "Unexpected vector bitcast");
5652 APInt DemandedSrcElts =
5653 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5654 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5655 Depth + 1);
5656 }
5657
5658 case ISD::BUILD_VECTOR:
5659 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5660 // this shouldn't affect the result.
5661 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5662 if (!DemandedElts[i])
5663 continue;
5664 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5665 return false;
5666 }
5667 return true;
5668
5669 case ISD::CONCAT_VECTORS: {
5670 EVT VT = Op.getValueType();
5671 if (!VT.isFixedLengthVector())
5672 break;
5673
5674 EVT SubVT = Op.getOperand(0).getValueType();
5675 unsigned NumSubElts = SubVT.getVectorNumElements();
5676 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5677 APInt DemandedSubElts =
5678 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5679 if (!!DemandedSubElts &&
5680 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5681 Kind, Depth + 1))
5682 return false;
5683 }
5684 return true;
5685 }
5686
5688 SDValue Src = Op.getOperand(0);
5689 if (Src.getValueType().isScalableVector())
5690 break;
5691 uint64_t Idx = Op.getConstantOperandVal(1);
5692 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5693 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5694 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5695 Depth + 1);
5696 }
5697
5698 case ISD::INSERT_SUBVECTOR: {
5699 if (Op.getValueType().isScalableVector())
5700 break;
5701 SDValue Src = Op.getOperand(0);
5702 SDValue Sub = Op.getOperand(1);
5703 uint64_t Idx = Op.getConstantOperandVal(2);
5704 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5705 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5706 APInt DemandedSrcElts = DemandedElts;
5707 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5708
5709 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5710 Sub, DemandedSubElts, Kind, Depth + 1))
5711 return false;
5712 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5713 Src, DemandedSrcElts, Kind, Depth + 1))
5714 return false;
5715 return true;
5716 }
5717
5719 SDValue Src = Op.getOperand(0);
5720 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5721 EVT SrcVT = Src.getValueType();
5722 if (SrcVT.isFixedLengthVector() && IndexC &&
5723 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5724 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5725 IndexC->getZExtValue());
5726 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5727 Depth + 1);
5728 }
5729 break;
5730 }
5731
5733 SDValue InVec = Op.getOperand(0);
5734 SDValue InVal = Op.getOperand(1);
5735 SDValue EltNo = Op.getOperand(2);
5736 EVT VT = InVec.getValueType();
5737 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5738 if (IndexC && VT.isFixedLengthVector() &&
5739 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5740 if (DemandedElts[IndexC->getZExtValue()] &&
5741 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5742 return false;
5743 APInt InVecDemandedElts = DemandedElts;
5744 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5745 if (!!InVecDemandedElts &&
5747 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5748 InVecDemandedElts, Kind, Depth + 1))
5749 return false;
5750 return true;
5751 }
5752 break;
5753 }
5754
5756 // Check upper (known undef) elements.
5757 if (DemandedElts.ugt(1) && includesUndef(Kind))
5758 return false;
5759 // Check element zero.
5760 if (DemandedElts[0] &&
5761 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5762 return false;
5763 return true;
5764
5765 case ISD::SPLAT_VECTOR:
5766 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5767
5768 case ISD::SELECT: {
5769 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5770 /*ConsiderFlags*/ true, Depth) &&
5771 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5772 Depth + 1) &&
5773 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5774 Kind, Depth + 1) &&
5775 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5776 Kind, Depth + 1);
5777 }
5778
5779 case ISD::VECTOR_SHUFFLE: {
5780 APInt DemandedLHS, DemandedRHS;
5781 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5782 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5783 DemandedElts, DemandedLHS, DemandedRHS,
5784 /*AllowUndefElts=*/false))
5785 return false;
5786 if (!DemandedLHS.isZero() &&
5787 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5788 Depth + 1))
5789 return false;
5790 if (!DemandedRHS.isZero() &&
5791 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5792 Depth + 1))
5793 return false;
5794 return true;
5795 }
5796
5797 case ISD::SHL:
5798 case ISD::SRL:
5799 case ISD::SRA:
5800 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5801 // enough to check operand 0 if Op can't create undef/poison.
5802 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5803 /*ConsiderFlags*/ true, Depth) &&
5804 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5805 Kind, Depth + 1);
5806
5807 case ISD::BSWAP:
5808 case ISD::CTPOP:
5809 case ISD::BITREVERSE:
5810 case ISD::AND:
5811 case ISD::OR:
5812 case ISD::XOR:
5813 case ISD::ADD:
5814 case ISD::SUB:
5815 case ISD::MUL:
5816 case ISD::SADDSAT:
5817 case ISD::UADDSAT:
5818 case ISD::SSUBSAT:
5819 case ISD::USUBSAT:
5820 case ISD::SSHLSAT:
5821 case ISD::USHLSAT:
5822 case ISD::SMIN:
5823 case ISD::SMAX:
5824 case ISD::UMIN:
5825 case ISD::UMAX:
5826 case ISD::ZERO_EXTEND:
5827 case ISD::SIGN_EXTEND:
5828 case ISD::ANY_EXTEND:
5829 case ISD::TRUNCATE:
5830 case ISD::VSELECT: {
5831 // If Op can't create undef/poison and none of its operands are undef/poison
5832 // then Op is never undef/poison. A difference from the more common check
5833 // below, outside the switch, is that we handle elementwise operations for
5834 // which the DemandedElts mask is valid for all operands here.
5835 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5836 /*ConsiderFlags*/ true, Depth) &&
5837 all_of(Op->ops(), [&](SDValue V) {
5838 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5839 Depth + 1);
5840 });
5841 }
5842
5843 // TODO: Search for noundef attributes from library functions.
5844
5845 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5846
5847 default:
5848 // Allow the target to implement this method for its nodes.
5849 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5850 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5851 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5852 Op, DemandedElts, *this, Kind, Depth);
5853 break;
5854 }
5855
5856 // If Op can't create undef/poison and none of its operands are undef/poison
5857 // then Op is never undef/poison.
5858 // NOTE: TargetNodes can handle this in themselves in
5859 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5860 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5861 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5862 all_of(Op->ops(), [&](SDValue V) {
5863 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5864 });
5865}
5866
5868 bool ConsiderFlags,
5869 unsigned Depth) const {
5870 APInt DemandedElts = getDemandAllEltsMask(Op);
5871 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5872}
5873
5875 UndefPoisonKind Kind,
5876 bool ConsiderFlags,
5877 unsigned Depth) const {
5878 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5879 return true;
5880
5881 unsigned Opcode = Op.getOpcode();
5882 switch (Opcode) {
5883 case ISD::AssertSext:
5884 case ISD::AssertZext:
5885 case ISD::AssertAlign:
5887 // Assertion nodes can create poison if the assertion fails.
5888 return includesPoison(Kind);
5889
5890 case ISD::FREEZE:
5894 case ISD::SADDSAT:
5895 case ISD::UADDSAT:
5896 case ISD::SSUBSAT:
5897 case ISD::USUBSAT:
5898 case ISD::MULHU:
5899 case ISD::MULHS:
5900 case ISD::AVGFLOORS:
5901 case ISD::AVGFLOORU:
5902 case ISD::AVGCEILS:
5903 case ISD::AVGCEILU:
5904 case ISD::ABDU:
5905 case ISD::ABDS:
5906 case ISD::SMIN:
5907 case ISD::SMAX:
5908 case ISD::SCMP:
5909 case ISD::UMIN:
5910 case ISD::UMAX:
5911 case ISD::UCMP:
5912 case ISD::AND:
5913 case ISD::XOR:
5914 case ISD::ROTL:
5915 case ISD::ROTR:
5916 case ISD::FSHL:
5917 case ISD::FSHR:
5918 case ISD::BSWAP:
5919 case ISD::CTTZ:
5920 case ISD::CTLZ:
5921 case ISD::CTLS:
5922 case ISD::CTPOP:
5923 case ISD::BITREVERSE:
5924 case ISD::PARITY:
5925 case ISD::SIGN_EXTEND:
5926 case ISD::TRUNCATE:
5930 case ISD::BITCAST:
5931 case ISD::BUILD_VECTOR:
5932 case ISD::BUILD_PAIR:
5933 case ISD::SPLAT_VECTOR:
5934 case ISD::FABS:
5935 case ISD::FCEIL:
5936 case ISD::FFLOOR:
5937 case ISD::FTRUNC:
5938 case ISD::FRINT:
5939 case ISD::FNEARBYINT:
5940 case ISD::FROUND:
5941 case ISD::FROUNDEVEN:
5942 return false;
5943
5944 case ISD::ABS:
5945 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
5946 // Different to Intrinsic::abs.
5947 return false;
5949 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
5950 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
5951
5952 case ISD::ADDC:
5953 case ISD::SUBC:
5954 case ISD::ADDE:
5955 case ISD::SUBE:
5956 case ISD::SADDO:
5957 case ISD::SSUBO:
5958 case ISD::SMULO:
5959 case ISD::SADDO_CARRY:
5960 case ISD::SSUBO_CARRY:
5961 case ISD::UADDO:
5962 case ISD::USUBO:
5963 case ISD::UMULO:
5964 case ISD::UADDO_CARRY:
5965 case ISD::USUBO_CARRY:
5966 // No poison on result or overflow flags.
5967 return false;
5968
5969 case ISD::SELECT_CC:
5970 case ISD::SETCC: {
5971 // Integer setcc cannot create undef or poison.
5972 if (Op.getOperand(0).getValueType().isInteger())
5973 return false;
5974
5975 // FP compares are more complicated. They can create poison for nan/infinity
5976 // based on options and flags. The options and flags also cause special
5977 // nonan condition codes to be used. Those condition codes may be preserved
5978 // even if the nonan flag is dropped somewhere.
5979 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
5980 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
5981 return (unsigned)CCCode & 0x10U;
5982 }
5983
5984 case ISD::OR:
5985 case ISD::ZERO_EXTEND:
5986 case ISD::SELECT:
5987 case ISD::VSELECT:
5988 case ISD::ADD:
5989 case ISD::SUB:
5990 case ISD::MUL:
5991 case ISD::FNEG:
5992 case ISD::FADD:
5993 case ISD::FSUB:
5994 case ISD::FMUL:
5995 case ISD::FDIV:
5996 case ISD::FREM:
5997 case ISD::FCOPYSIGN:
5998 case ISD::FMA:
5999 case ISD::FMAD:
6000 case ISD::FMULADD:
6001 case ISD::FP_EXTEND:
6002 case ISD::FMINNUM:
6003 case ISD::FMAXNUM:
6004 case ISD::FMINNUM_IEEE:
6005 case ISD::FMAXNUM_IEEE:
6006 case ISD::FMINIMUM:
6007 case ISD::FMAXIMUM:
6008 case ISD::FMINIMUMNUM:
6009 case ISD::FMAXIMUMNUM:
6015 // No poison except from flags (which is handled above)
6016 return false;
6017
6018 case ISD::SHL:
6019 case ISD::SRL:
6020 case ISD::SRA:
6021 // If the max shift amount isn't in range, then the shift can
6022 // create poison.
6023 return includesPoison(Kind) &&
6024 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6025
6028 // If the amount is zero then the result will be poison.
6029 // TODO: Add isKnownNeverZero DemandedElts handling.
6030 return includesPoison(Kind) &&
6031 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6032
6034 // Check if we demand any upper (undef) elements.
6035 return includesUndef(Kind) && DemandedElts.ugt(1);
6036
6039 // Ensure that the element index is in bounds.
6040 if (includesPoison(Kind)) {
6041 EVT VecVT = Op.getOperand(0).getValueType();
6042 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6043 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6044 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6045 }
6046 return false;
6047 }
6048
6049 case ISD::VECTOR_SHUFFLE: {
6050 // Check for any demanded shuffle element that is undef.
6051 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6052 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6053 if (Elt < 0 && DemandedElts[Idx])
6054 return true;
6055 return false;
6056 }
6057
6059 return false;
6060
6061 default:
6062 // Allow the target to implement this method for its nodes.
6063 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6064 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6065 return TLI->canCreateUndefOrPoisonForTargetNode(
6066 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6067 break;
6068 }
6069
6070 // Be conservative and return true.
6071 return true;
6072}
6073
6074bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6075 unsigned Opcode = Op.getOpcode();
6076 if (Opcode == ISD::OR)
6077 return Op->getFlags().hasDisjoint() ||
6078 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6079 if (Opcode == ISD::XOR)
6080 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6081 return false;
6082}
6083
6085 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6086 (Op.isAnyAdd() || isADDLike(Op));
6087}
6088
6090 FPClassTest InterestedClasses,
6091 unsigned Depth) const {
6092 APInt DemandedElts = getDemandAllEltsMask(Op);
6093 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6094}
6095
6097 const APInt &DemandedElts,
6098 FPClassTest InterestedClasses,
6099 unsigned Depth) const {
6101
6102 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6103 return KnownFPClass(CFP->getValueAPF());
6104
6105 if (Depth >= MaxRecursionDepth)
6106 return Known;
6107
6108 if (Op.getOpcode() == ISD::UNDEF)
6109 return Known;
6110
6111 EVT VT = Op.getValueType();
6112 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6113 assert((!VT.isFixedLengthVector() ||
6114 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6115 "Unexpected vector size");
6116
6117 if (!DemandedElts)
6118 return Known;
6119
6120 unsigned Opcode = Op.getOpcode();
6121 switch (Opcode) {
6122 case ISD::POISON: {
6123 Known.KnownFPClasses = fcNone;
6124 Known.setSignBit(false);
6125 break;
6126 }
6127 case ISD::FNEG: {
6128 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6129 InterestedClasses, Depth + 1);
6130 Known.fneg();
6131 break;
6132 }
6133 case ISD::BUILD_VECTOR: {
6134 assert(!VT.isScalableVector());
6135 bool First = true;
6136 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6137 if (!DemandedElts[I])
6138 continue;
6139
6140 if (First) {
6141 Known =
6142 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6143 First = false;
6144 } else {
6145 Known |=
6146 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6147 }
6148
6149 if (Known.isUnknown())
6150 break;
6151 }
6152 break;
6153 }
6155 SDValue Src = Op.getOperand(0);
6156 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6157 EVT SrcVT = Src.getValueType();
6158 if (SrcVT.isFixedLengthVector() && CIdx) {
6159 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6160 APInt DemandedSrcElts = APInt::getOneBitSet(
6161 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6162 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6163 Depth + 1);
6164 } else {
6165 // Out of bounds index is poison.
6166 Known.KnownFPClasses = fcNone;
6167 }
6168 } else {
6169 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6170 }
6171 break;
6172 }
6173 case ISD::SPLAT_VECTOR: {
6174 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6175 break;
6176 }
6177 case ISD::BITCAST: {
6178 // FIXME: It should not be necessary to check for an elementwise bitcast.
6179 // If a bitcast is not elementwise between vector / scalar types,
6180 // computeKnownBits already splices the known bits of the source elements
6181 // appropriately so as to line up with the bits of the result's demanded
6182 // elements.
6183 EVT SrcVT = Op.getOperand(0).getValueType();
6184 if (VT.isScalableVector() || SrcVT.isScalableVector())
6185 break;
6186 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6187 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6188 if (VTNumElts != SrcVTNumElts)
6189 break;
6190
6191 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6193 break;
6194 }
6195 case ISD::FABS: {
6196 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6197 InterestedClasses, Depth + 1);
6198 Known.fabs();
6199 break;
6200 }
6201 case ISD::FCOPYSIGN: {
6202 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6203 InterestedClasses, Depth + 1);
6204 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6205 InterestedClasses, Depth + 1);
6206 Known.copysign(KnownSign);
6207 break;
6208 }
6209 case ISD::AssertNoFPClass: {
6210 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6211 InterestedClasses, Depth + 1);
6212 FPClassTest AssertedClasses =
6213 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6214 Known.KnownFPClasses &= ~AssertedClasses;
6215 break;
6216 }
6218 SDValue Src = Op.getOperand(0);
6219 EVT SrcVT = Src.getValueType();
6220 if (SrcVT.isFixedLengthVector()) {
6221 unsigned Idx = Op.getConstantOperandVal(1);
6222 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6223
6224 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6225 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6226 Depth + 1);
6227 } else {
6228 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6229 }
6230 break;
6231 }
6232 case ISD::INSERT_SUBVECTOR: {
6233 SDValue BaseVector = Op.getOperand(0);
6234 SDValue SubVector = Op.getOperand(1);
6235 EVT BaseVT = BaseVector.getValueType();
6236 if (BaseVT.isFixedLengthVector()) {
6237 unsigned Idx = Op.getConstantOperandVal(2);
6238 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6239 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6240
6241 APInt DemandedMask =
6242 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6243 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6244 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6245
6246 if (!DemandedSrcElts.isZero())
6247 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6248 InterestedClasses, Depth + 1);
6249 if (!DemandedSubElts.isZero()) {
6251 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6252 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6253 }
6254 } else {
6255 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6256 if (!Known.isUnknown())
6257 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6258 }
6259 break;
6260 }
6261 case ISD::SELECT:
6262 case ISD::VSELECT: {
6263 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6264 // IR-level ValueTracking.
6265 KnownFPClass KnownFalseClass = computeKnownFPClass(
6266 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6267 if (KnownFalseClass.isUnknown())
6268 break;
6269 KnownFPClass KnownTrueClass = computeKnownFPClass(
6270 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6271 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6272 break;
6273 }
6274 default:
6275 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6276 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6277 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6278 Depth);
6279 }
6280 break;
6281 }
6282
6283 return Known;
6284}
6285
6287 unsigned Depth) const {
6288 APInt DemandedElts = getDemandAllEltsMask(Op);
6289 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6290}
6291
6293 bool SNaN, unsigned Depth) const {
6294 assert(!DemandedElts.isZero() && "No demanded elements");
6295
6296 // If we're told that NaNs won't happen, assume they won't.
6297 if (Op->getFlags().hasNoNaNs())
6298 return true;
6299
6300 if (Depth >= MaxRecursionDepth)
6301 return false; // Limit search depth.
6302
6303 unsigned Opcode = Op.getOpcode();
6304 switch (Opcode) {
6305 case ISD::FADD:
6306 case ISD::FSUB:
6307 case ISD::FMUL:
6308 case ISD::FDIV:
6309 case ISD::FREM:
6310 case ISD::FSIN:
6311 case ISD::FCOS:
6312 case ISD::FTAN:
6313 case ISD::FASIN:
6314 case ISD::FACOS:
6315 case ISD::FATAN:
6316 case ISD::FATAN2:
6317 case ISD::FSINH:
6318 case ISD::FCOSH:
6319 case ISD::FTANH:
6320 case ISD::FMA:
6321 case ISD::FMULADD:
6322 case ISD::FMAD: {
6323 if (SNaN)
6324 return true;
6325 // TODO: Need isKnownNeverInfinity
6326 return false;
6327 }
6328 case ISD::FCANONICALIZE:
6329 case ISD::FEXP:
6330 case ISD::FEXP2:
6331 case ISD::FEXP10:
6332 case ISD::FTRUNC:
6333 case ISD::FFLOOR:
6334 case ISD::FCEIL:
6335 case ISD::FROUND:
6336 case ISD::FROUNDEVEN:
6337 case ISD::LROUND:
6338 case ISD::LLROUND:
6339 case ISD::FRINT:
6340 case ISD::LRINT:
6341 case ISD::LLRINT:
6342 case ISD::FNEARBYINT:
6343 case ISD::FLDEXP: {
6344 if (SNaN)
6345 return true;
6346 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6347 }
6348 case ISD::FABS:
6349 case ISD::FNEG:
6350 case ISD::FCOPYSIGN: {
6351 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6352 }
6353 case ISD::SELECT:
6354 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6355 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6356 case ISD::FP_EXTEND:
6357 case ISD::FP_ROUND: {
6358 if (SNaN)
6359 return true;
6360 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6361 }
6362 case ISD::SINT_TO_FP:
6363 case ISD::UINT_TO_FP:
6364 return true;
6365 case ISD::FSQRT: // Need is known positive
6366 case ISD::FLOG:
6367 case ISD::FLOG2:
6368 case ISD::FLOG10:
6369 case ISD::FPOWI:
6370 case ISD::FPOW: {
6371 if (SNaN)
6372 return true;
6373 // TODO: Refine on operand
6374 return false;
6375 }
6376 case ISD::FMINNUM:
6377 case ISD::FMAXNUM:
6378 case ISD::FMINIMUMNUM:
6379 case ISD::FMAXIMUMNUM: {
6380 // Only one needs to be known not-nan, since it will be returned if the
6381 // other ends up being one.
6382 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6383 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6384 }
6385 case ISD::FMINNUM_IEEE:
6386 case ISD::FMAXNUM_IEEE: {
6387 if (SNaN)
6388 return true;
6389 // This can return a NaN if either operand is an sNaN, or if both operands
6390 // are NaN.
6391 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6392 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6393 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6394 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6395 }
6396 case ISD::FMINIMUM:
6397 case ISD::FMAXIMUM: {
6398 // TODO: Does this quiet or return the origina NaN as-is?
6399 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6400 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6401 }
6403 SDValue Src = Op.getOperand(0);
6404 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6405 EVT SrcVT = Src.getValueType();
6406 if (SrcVT.isFixedLengthVector() && Idx &&
6407 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6408 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6409 Idx->getZExtValue());
6410 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6411 }
6412 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6413 }
6415 SDValue Src = Op.getOperand(0);
6416 if (Src.getValueType().isFixedLengthVector()) {
6417 unsigned Idx = Op.getConstantOperandVal(1);
6418 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6419 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6420 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6421 }
6422 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6423 }
6424 case ISD::INSERT_SUBVECTOR: {
6425 SDValue BaseVector = Op.getOperand(0);
6426 SDValue SubVector = Op.getOperand(1);
6427 EVT BaseVectorVT = BaseVector.getValueType();
6428 if (BaseVectorVT.isFixedLengthVector()) {
6429 unsigned Idx = Op.getConstantOperandVal(2);
6430 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6431 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6432
6433 // Clear/Extract the bits at the position where the subvector will be
6434 // inserted.
6435 APInt DemandedMask =
6436 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6437 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6438 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6439
6440 bool NeverNaN = true;
6441 if (!DemandedSrcElts.isZero())
6442 NeverNaN &=
6443 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6444 if (NeverNaN && !DemandedSubElts.isZero())
6445 NeverNaN &=
6446 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6447 return NeverNaN;
6448 }
6449 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6450 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6451 }
6452 case ISD::BUILD_VECTOR: {
6453 unsigned NumElts = Op.getNumOperands();
6454 for (unsigned I = 0; I != NumElts; ++I)
6455 if (DemandedElts[I] &&
6456 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6457 return false;
6458 return true;
6459 }
6460 case ISD::SPLAT_VECTOR:
6461 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6462 case ISD::AssertNoFPClass: {
6463 FPClassTest NoFPClass =
6464 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6465 if ((NoFPClass & fcNan) == fcNan)
6466 return true;
6467 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6468 return true;
6469 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6470 }
6471 default:
6472 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6473 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6474 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6475 Depth);
6476 }
6477 break;
6478 }
6479
6480 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6481 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6482 return Known.isKnownNever(NanMask);
6483}
6484
6486 APInt DemandedElts = getDemandAllEltsMask(Op);
6487 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6488}
6489
6491 const APInt &DemandedElts,
6492 unsigned Depth) const {
6493 assert(!DemandedElts.isZero() && "No demanded elements");
6494 EVT VT = Op.getValueType();
6496 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6497 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6498}
6499
6501 APInt DemandedElts = getDemandAllEltsMask(Op);
6502 return isKnownNeverZero(Op, DemandedElts, Depth);
6503}
6504
6506 unsigned Depth) const {
6507 if (Depth >= MaxRecursionDepth)
6508 return false; // Limit search depth.
6509
6510 EVT OpVT = Op.getValueType();
6511 unsigned BitWidth = OpVT.getScalarSizeInBits();
6512
6513 assert(!Op.getValueType().isFloatingPoint() &&
6514 "Floating point types unsupported - use isKnownNeverLogicalZero");
6515
6516 // If the value is a constant, we can obviously see if it is a zero or not.
6517 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6518 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6519 return !V.isZero();
6520 };
6521
6522 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6523 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6524 return true;
6525
6526 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6527 // some degree.
6528 switch (Op.getOpcode()) {
6529 default:
6530 break;
6531
6533 SDValue InVec = Op.getOperand(0);
6534 SDValue EltNo = Op.getOperand(1);
6535 EVT VecVT = InVec.getValueType();
6536
6537 // Skip scalable vectors or implicit extensions.
6538 if (VecVT.isScalableVector() ||
6539 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6540 break;
6541
6542 // If we know the element index, just demand that vector element, else for
6543 // an unknown element index, ignore DemandedElts and demand them all.
6544 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6545 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6546 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6547 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6548 DemandedSrcElts =
6549 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6550
6551 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6552 }
6553
6554 case ISD::OR:
6555 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6556 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6557
6558 case ISD::VSELECT:
6559 case ISD::SELECT:
6560 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6561 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6562
6563 case ISD::SHL: {
6564 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6565 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6566 KnownBits ValKnown =
6567 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6568 // 1 << X is never zero.
6569 if (ValKnown.One[0])
6570 return true;
6571 // If max shift cnt of known ones is non-zero, result is non-zero.
6572 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6573 .getMaxValue();
6574 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6575 !ValKnown.One.shl(MaxCnt).isZero())
6576 return true;
6577 break;
6578 }
6579
6580 case ISD::VECTOR_SHUFFLE: {
6581 if (Op.getValueType().isScalableVector())
6582 return false;
6583
6584 unsigned NumElts = DemandedElts.getBitWidth();
6585
6586 // All demanded elements from LHS and RHS must be known non-zero.
6587 // Demanded elements with undef shuffle mask elements are unknown.
6588
6589 APInt DemandedLHS, DemandedRHS;
6590 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6591 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6592 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6593 DemandedLHS, DemandedRHS))
6594 return false;
6595
6596 return (!DemandedLHS ||
6597 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6598 (!DemandedRHS ||
6599 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6600 }
6601
6602 case ISD::UADDSAT:
6603 case ISD::UMAX:
6604 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6605 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6606
6607 case ISD::UMIN:
6608 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6609 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6610
6611 // For smin/smax: If either operand is known negative/positive
6612 // respectively we don't need the other to be known at all.
6613 case ISD::SMAX: {
6614 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6615 if (Op1.isStrictlyPositive())
6616 return true;
6617
6618 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6619 if (Op0.isStrictlyPositive())
6620 return true;
6621
6622 if (Op1.isNonZero() && Op0.isNonZero())
6623 return true;
6624
6625 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6626 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6627 }
6628 case ISD::SMIN: {
6629 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6630 if (Op1.isNegative())
6631 return true;
6632
6633 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6634 if (Op0.isNegative())
6635 return true;
6636
6637 if (Op1.isNonZero() && Op0.isNonZero())
6638 return true;
6639
6640 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6641 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6642 }
6643
6644 case ISD::ROTL:
6645 case ISD::ROTR:
6646 case ISD::BITREVERSE:
6647 case ISD::BSWAP:
6648 case ISD::CTPOP:
6649 case ISD::ABS:
6651 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6652
6653 case ISD::SRA:
6654 case ISD::SRL: {
6655 if (Op->getFlags().hasExact())
6656 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6657 KnownBits ValKnown =
6658 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6659 if (ValKnown.isNegative())
6660 return true;
6661 // If max shift cnt of known ones is non-zero, result is non-zero.
6662 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6663 .getMaxValue();
6664 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6665 !ValKnown.One.lshr(MaxCnt).isZero())
6666 return true;
6667 break;
6668 }
6669 case ISD::UDIV:
6670 case ISD::SDIV:
6671 // div exact can only produce a zero if the dividend is zero.
6672 // TODO: For udiv this is also true if Op1 u<= Op0
6673 if (Op->getFlags().hasExact())
6674 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6675 break;
6676
6677 case ISD::ADD:
6678 if (Op->getFlags().hasNoUnsignedWrap())
6679 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6680 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6681 return true;
6682 // TODO: There are a lot more cases we can prove for add.
6683 break;
6684
6685 case ISD::SUB: {
6686 if (isNullConstant(Op.getOperand(0)))
6687 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6688
6689 std::optional<bool> ne = KnownBits::ne(
6690 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6691 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6692 return ne && *ne;
6693 }
6694
6695 case ISD::MUL:
6696 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6697 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6698 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6699 return true;
6700 break;
6701
6702 case ISD::ZERO_EXTEND:
6703 case ISD::SIGN_EXTEND:
6704 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6705 case ISD::VSCALE: {
6707 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6708 ConstantRange CR =
6709 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6710 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6711 return true;
6712 break;
6713 }
6714 }
6715
6716 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6717}
6718
6720 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6721 return !C1->isNegative();
6722
6723 switch (Op.getOpcode()) {
6724 case ISD::FABS:
6725 case ISD::FEXP:
6726 case ISD::FEXP2:
6727 case ISD::FEXP10:
6728 return true;
6729 default:
6730 return false;
6731 }
6732
6733 llvm_unreachable("covered opcode switch");
6734}
6735
6737 assert(Use.getValueType().isFloatingPoint());
6738 const SDNode *User = Use.getUser();
6739 if (User->getFlags().hasNoSignedZeros())
6740 return true;
6741
6742 unsigned OperandNo = Use.getOperandNo();
6743 // Check if this use is insensitive to the sign of zero
6744 switch (User->getOpcode()) {
6745 case ISD::SETCC:
6746 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6747 case ISD::FABS:
6748 // fabs always produces +0.0.
6749 return true;
6750 case ISD::FCOPYSIGN:
6751 // copysign overwrites the sign bit of the first operand.
6752 return OperandNo == 0;
6753 case ISD::FADD:
6754 case ISD::FSUB: {
6755 // Arithmetic with non-zero constants fixes the uncertainty around the
6756 // sign bit.
6757 SDValue Other = User->getOperand(1 - OperandNo);
6759 }
6760 case ISD::FP_TO_SINT:
6761 case ISD::FP_TO_UINT:
6762 // fp-to-int conversions normalize signed zeros.
6763 return true;
6764 default:
6765 return false;
6766 }
6767}
6768
6770 if (Op->getFlags().hasNoSignedZeros())
6771 return true;
6772 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6773 // regression. Ideally, this should be implemented as a demanded-bits
6774 // optimization that stems from the users.
6775 if (Op->use_size() > 2)
6776 return false;
6777 return all_of(Op->uses(),
6778 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6779}
6780
6782 // Check the obvious case.
6783 if (A == B) return true;
6784
6785 // For negative and positive zero.
6788 if (CA->isZero() && CB->isZero()) return true;
6789
6790 // Otherwise they may not be equal.
6791 return false;
6792}
6793
6794// Only bits set in Mask must be negated, other bits may be arbitrary.
6796 if (isBitwiseNot(V, AllowUndefs))
6797 return V.getOperand(0);
6798
6799 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6800 // bits in the non-extended part.
6801 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6802 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6803 return SDValue();
6804 SDValue ExtArg = V.getOperand(0);
6805 if (ExtArg.getScalarValueSizeInBits() >=
6806 MaskC->getAPIntValue().getActiveBits() &&
6807 isBitwiseNot(ExtArg, AllowUndefs) &&
6808 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6809 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6810 return ExtArg.getOperand(0).getOperand(0);
6811 return SDValue();
6812}
6813
6815 // Match masked merge pattern (X & ~M) op (Y & M)
6816 // Including degenerate case (X & ~M) op M
6817 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6818 SDValue Other) {
6819 if (SDValue NotOperand =
6820 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6821 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6822 NotOperand->getOpcode() == ISD::TRUNCATE)
6823 NotOperand = NotOperand->getOperand(0);
6824
6825 if (Other == NotOperand)
6826 return true;
6827 if (Other->getOpcode() == ISD::AND)
6828 return NotOperand == Other->getOperand(0) ||
6829 NotOperand == Other->getOperand(1);
6830 }
6831 return false;
6832 };
6833
6834 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6835 A = A->getOperand(0);
6836
6837 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6838 B = B->getOperand(0);
6839
6840 if (A->getOpcode() == ISD::AND)
6841 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6842 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6843 return false;
6844}
6845
6846// FIXME: unify with llvm::haveNoCommonBitsSet.
6848 assert(A.getValueType() == B.getValueType() &&
6849 "Values must have the same type");
6852 return true;
6855}
6856
6857static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6858 SelectionDAG &DAG) {
6859 if (cast<ConstantSDNode>(Step)->isZero())
6860 return DAG.getConstant(0, DL, VT);
6861
6862 return SDValue();
6863}
6864
6867 SelectionDAG &DAG) {
6868 int NumOps = Ops.size();
6869 assert(NumOps != 0 && "Can't build an empty vector!");
6870 assert(!VT.isScalableVector() &&
6871 "BUILD_VECTOR cannot be used with scalable types");
6872 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6873 "Incorrect element count in BUILD_VECTOR!");
6874
6875 // BUILD_VECTOR of UNDEFs is UNDEF.
6876 bool AllPoison = true;
6877 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6878 AllPoison &= Op.getOpcode() == ISD::POISON;
6879 return Op.isUndef();
6880 }))
6881 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6882
6883 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6884 SDValue IdentitySrc;
6885 bool IsIdentity = true;
6886 for (int i = 0; i != NumOps; ++i) {
6887 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6888 Ops[i].getOperand(0).getValueType() != VT ||
6889 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6890 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6891 Ops[i].getConstantOperandAPInt(1) != i) {
6892 IsIdentity = false;
6893 break;
6894 }
6895 IdentitySrc = Ops[i].getOperand(0);
6896 }
6897 if (IsIdentity)
6898 return IdentitySrc;
6899
6900 return SDValue();
6901}
6902
6903/// Try to simplify vector concatenation to an input value, undef, or build
6904/// vector.
6907 SelectionDAG &DAG) {
6908 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6910 [Ops](SDValue Op) {
6911 return Ops[0].getValueType() == Op.getValueType();
6912 }) &&
6913 "Concatenation of vectors with inconsistent value types!");
6914 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6915 VT.getVectorElementCount() &&
6916 "Incorrect element count in vector concatenation!");
6917
6918 if (Ops.size() == 1)
6919 return Ops[0];
6920
6921 // Concat of UNDEFs is UNDEF.
6922 bool AllPoison = true;
6923 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6924 AllPoison &= Op.getOpcode() == ISD::POISON;
6925 return Op.isUndef();
6926 }))
6927 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6928
6929 // Scan the operands and look for extract operations from a single source
6930 // that correspond to insertion at the same location via this concatenation:
6931 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
6932 SDValue IdentitySrc;
6933 bool IsIdentity = true;
6934 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
6935 SDValue Op = Ops[i];
6936 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
6937 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6938 Op.getOperand(0).getValueType() != VT ||
6939 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
6940 Op.getConstantOperandVal(1) != IdentityIndex) {
6941 IsIdentity = false;
6942 break;
6943 }
6944 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
6945 "Unexpected identity source vector for concat of extracts");
6946 IdentitySrc = Op.getOperand(0);
6947 }
6948 if (IsIdentity) {
6949 assert(IdentitySrc && "Failed to set source vector of extracts");
6950 return IdentitySrc;
6951 }
6952
6953 // The code below this point is only designed to work for fixed width
6954 // vectors, so we bail out for now.
6955 if (VT.isScalableVector())
6956 return SDValue();
6957
6958 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
6959 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
6960 // BUILD_VECTOR.
6961 // FIXME: Add support for SCALAR_TO_VECTOR as well.
6962 EVT SVT = VT.getScalarType();
6964 for (SDValue Op : Ops) {
6965 EVT OpVT = Op.getValueType();
6966 if (Op.getOpcode() == ISD::POISON)
6967 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
6968 else if (Op.getOpcode() == ISD::UNDEF)
6969 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
6970 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
6971 Elts.append(Op->op_begin(), Op->op_end());
6972 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
6973 OpVT.getVectorNumElements() == 1 &&
6974 isNullConstant(Op.getOperand(2)))
6975 Elts.push_back(Op.getOperand(1));
6976 else
6977 return SDValue();
6978 }
6979
6980 // BUILD_VECTOR requires all inputs to be of the same type, find the
6981 // maximum type and extend them all.
6982 for (SDValue Op : Elts)
6983 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
6984
6985 if (SVT.bitsGT(VT.getScalarType())) {
6986 for (SDValue &Op : Elts) {
6987 if (Op.getOpcode() == ISD::POISON)
6988 Op = DAG.getPOISON(SVT);
6989 else if (Op.getOpcode() == ISD::UNDEF)
6990 Op = DAG.getUNDEF(SVT);
6991 else
6992 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
6993 ? DAG.getZExtOrTrunc(Op, DL, SVT)
6994 : DAG.getSExtOrTrunc(Op, DL, SVT);
6995 }
6996 }
6997
6998 SDValue V = DAG.getBuildVector(VT, DL, Elts);
6999 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7000 return V;
7001}
7002
7003/// Gets or creates the specified node.
7004SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7005 SDVTList VTs = getVTList(VT);
7006 SDNodeKey ID(Opcode, VTs, {});
7007 FoldingSetInsertToken InsertToken;
7008 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7009 return SDValue(E, 0);
7010
7011 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7012 CSEMap.insert(N, InsertToken);
7013
7014 InsertNode(N);
7015 SDValue V = SDValue(N, 0);
7016 NewSDValueDbgMsg(V, "Creating new node: ", this);
7017 return V;
7018}
7019
7020SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7021 SDValue N1) {
7022 SDNodeFlags Flags;
7023 if (Inserter)
7024 Flags = Inserter->getFlags();
7025 return getNode(Opcode, DL, VT, N1, Flags);
7026}
7027
7028SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7029 SDValue N1, const SDNodeFlags Flags) {
7030 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7031
7032 // Constant fold unary operations with a vector integer or float operand.
7033 switch (Opcode) {
7034 default:
7035 // FIXME: Entirely reasonable to perform folding of other unary
7036 // operations here as the need arises.
7037 break;
7038 case ISD::FNEG:
7039 case ISD::FABS:
7040 case ISD::FCEIL:
7041 case ISD::FTRUNC:
7042 case ISD::FFLOOR:
7043 case ISD::FP_EXTEND:
7044 case ISD::FP_TO_SINT:
7045 case ISD::FP_TO_UINT:
7046 case ISD::FP_TO_FP16:
7047 case ISD::FP_TO_BF16:
7048 case ISD::TRUNCATE:
7049 case ISD::ANY_EXTEND:
7050 case ISD::ZERO_EXTEND:
7051 case ISD::SIGN_EXTEND:
7052 case ISD::UINT_TO_FP:
7053 case ISD::SINT_TO_FP:
7054 case ISD::FP16_TO_FP:
7055 case ISD::BF16_TO_FP:
7056 case ISD::BITCAST:
7057 case ISD::ABS:
7059 case ISD::BITREVERSE:
7060 case ISD::BSWAP:
7061 case ISD::CTLZ:
7063 case ISD::CTTZ:
7065 case ISD::CTPOP:
7066 case ISD::CTLS:
7067 case ISD::VECREDUCE_ADD:
7072 case ISD::VECREDUCE_MUL:
7073 case ISD::VECREDUCE_AND:
7074 case ISD::VECREDUCE_OR:
7075 case ISD::VECREDUCE_XOR:
7076 case ISD::STEP_VECTOR: {
7077 SDValue Ops = {N1};
7078 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7079 return Fold;
7080 }
7081 }
7082
7083 unsigned OpOpcode = N1.getNode()->getOpcode();
7084 switch (Opcode) {
7085 case ISD::STEP_VECTOR:
7086 assert(VT.isScalableVector() &&
7087 "STEP_VECTOR can only be used with scalable types");
7088 assert(OpOpcode == ISD::TargetConstant &&
7089 VT.getVectorElementType() == N1.getValueType() &&
7090 "Unexpected step operand");
7091 break;
7092 case ISD::FREEZE:
7093 assert(VT == N1.getValueType() && "Unexpected VT!");
7095 return N1;
7096 break;
7097 case ISD::TokenFactor:
7098 case ISD::MERGE_VALUES:
7100 return N1; // Factor, merge or concat of one node? No need.
7101 case ISD::BUILD_VECTOR: {
7102 // Attempt to simplify BUILD_VECTOR.
7103 SDValue Ops[] = {N1};
7104 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7105 return V;
7106 break;
7107 }
7108 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7109 case ISD::FP_EXTEND:
7111 "Invalid FP cast!");
7112 if (N1.getValueType() == VT) return N1; // noop conversion.
7113 assert((!VT.isVector() || VT.getVectorElementCount() ==
7115 "Vector element count mismatch!");
7116 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7117 if (N1.isUndef())
7118 return getUNDEF(VT);
7119 break;
7120 case ISD::FP_TO_SINT:
7121 case ISD::FP_TO_UINT:
7122 if (N1.isUndef())
7123 return getUNDEF(VT);
7124 break;
7125 case ISD::SINT_TO_FP:
7126 case ISD::UINT_TO_FP:
7127 // [us]itofp(undef) = 0, because the result value is bounded.
7128 if (N1.isUndef())
7129 return getConstantFP(0.0, DL, VT);
7130 break;
7131 case ISD::SIGN_EXTEND:
7132 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7133 "Invalid SIGN_EXTEND!");
7134 assert(VT.isVector() == N1.getValueType().isVector() &&
7135 "SIGN_EXTEND result type type should be vector iff the operand "
7136 "type is vector!");
7137 if (N1.getValueType() == VT) return N1; // noop extension
7138 assert((!VT.isVector() || VT.getVectorElementCount() ==
7140 "Vector element count mismatch!");
7141 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7142 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7143 SDNodeFlags Flags;
7144 if (OpOpcode == ISD::ZERO_EXTEND)
7145 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7146 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7147 transferDbgValues(N1, NewVal);
7148 return NewVal;
7149 }
7150
7151 if (OpOpcode == ISD::POISON)
7152 return getPOISON(VT);
7153
7154 if (N1.isUndef())
7155 // sext(undef) = 0, because the top bits will all be the same.
7156 return getConstant(0, DL, VT);
7157
7158 // Skip unnecessary sext_inreg pattern:
7159 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7160 if (OpOpcode == ISD::TRUNCATE) {
7161 SDValue OpOp = N1.getOperand(0);
7162 if (OpOp.getValueType() == VT) {
7163 unsigned NumSignExtBits =
7165 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7166 transferDbgValues(N1, OpOp);
7167 return OpOp;
7168 }
7169 }
7170 }
7171 break;
7172 case ISD::ZERO_EXTEND:
7173 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7174 "Invalid ZERO_EXTEND!");
7175 assert(VT.isVector() == N1.getValueType().isVector() &&
7176 "ZERO_EXTEND result type type should be vector iff the operand "
7177 "type is vector!");
7178 if (N1.getValueType() == VT) return N1; // noop extension
7179 assert((!VT.isVector() || VT.getVectorElementCount() ==
7181 "Vector element count mismatch!");
7182 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7183 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7184 SDNodeFlags Flags;
7185 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7186 SDValue NewVal =
7187 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7188 transferDbgValues(N1, NewVal);
7189 return NewVal;
7190 }
7191
7192 if (OpOpcode == ISD::POISON)
7193 return getPOISON(VT);
7194
7195 if (N1.isUndef())
7196 // zext(undef) = 0, because the top bits will be zero.
7197 return getConstant(0, DL, VT);
7198
7199 // Skip unnecessary zext_inreg pattern:
7200 // (zext (trunc x)) -> x iff the upper bits are known zero.
7201 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7202 // use to recognise zext_inreg patterns.
7203 if (OpOpcode == ISD::TRUNCATE) {
7204 SDValue OpOp = N1.getOperand(0);
7205 if (OpOp.getValueType() == VT) {
7206 if (OpOp.getOpcode() != ISD::AND) {
7209 if (MaskedValueIsZero(OpOp, HiBits)) {
7210 transferDbgValues(N1, OpOp);
7211 return OpOp;
7212 }
7213 }
7214 }
7215 }
7216 break;
7217 case ISD::ANY_EXTEND:
7218 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7219 "Invalid ANY_EXTEND!");
7220 assert(VT.isVector() == N1.getValueType().isVector() &&
7221 "ANY_EXTEND result type type should be vector iff the operand "
7222 "type is vector!");
7223 if (N1.getValueType() == VT) return N1; // noop extension
7224 assert((!VT.isVector() || VT.getVectorElementCount() ==
7226 "Vector element count mismatch!");
7227 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7228
7229 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7230 OpOpcode == ISD::ANY_EXTEND) {
7231 SDNodeFlags Flags;
7232 if (OpOpcode == ISD::ZERO_EXTEND)
7233 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7234 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7235 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7236 }
7237 if (N1.isUndef())
7238 return getUNDEF(VT);
7239
7240 // (ext (trunc x)) -> x
7241 if (OpOpcode == ISD::TRUNCATE) {
7242 SDValue OpOp = N1.getOperand(0);
7243 if (OpOp.getValueType() == VT) {
7244 transferDbgValues(N1, OpOp);
7245 return OpOp;
7246 }
7247 }
7248 break;
7249 case ISD::TRUNCATE:
7250 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7251 "Invalid TRUNCATE!");
7252 assert(VT.isVector() == N1.getValueType().isVector() &&
7253 "TRUNCATE result type type should be vector iff the operand "
7254 "type is vector!");
7255 if (N1.getValueType() == VT) return N1; // noop truncate
7256 assert((!VT.isVector() || VT.getVectorElementCount() ==
7258 "Vector element count mismatch!");
7259 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7260 if (OpOpcode == ISD::TRUNCATE)
7261 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7262 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7263 OpOpcode == ISD::ANY_EXTEND) {
7264 // If the source is smaller than the dest, we still need an extend.
7266 VT.getScalarType())) {
7267 SDNodeFlags Flags;
7268 if (OpOpcode == ISD::ZERO_EXTEND)
7269 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7270 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7271 }
7272 if (N1.getOperand(0).getValueType().bitsGT(VT))
7273 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7274 return N1.getOperand(0);
7275 }
7276 if (N1.isUndef())
7277 return getUNDEF(VT);
7278 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7279 return getVScale(DL, VT,
7281 break;
7285 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7286 assert(N1.getValueType().bitsLE(VT) &&
7287 "The input must be the same size or smaller than the result.");
7290 "The destination vector type must have fewer lanes than the input.");
7291 break;
7292 case ISD::ABS:
7293 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7294 if (N1.isUndef())
7295 return getConstant(0, DL, VT);
7296 break;
7298 assert(VT.isInteger() && VT == N1.getValueType() &&
7299 "Invalid ABS_MIN_POISON!");
7300 if (N1.isUndef())
7301 return getConstant(0, DL, VT);
7302 break;
7303 case ISD::BSWAP:
7304 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7305 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7306 "BSWAP types must be a multiple of 16 bits!");
7307 if (N1.isUndef())
7308 return getUNDEF(VT);
7309 // bswap(bswap(X)) -> X.
7310 if (OpOpcode == ISD::BSWAP)
7311 return N1.getOperand(0);
7312 break;
7313 case ISD::BITREVERSE:
7314 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7315 if (N1.isUndef())
7316 return getUNDEF(VT);
7317 break;
7318 case ISD::BITCAST:
7320 "Cannot BITCAST between types of different sizes!");
7321 if (VT == N1.getValueType()) return N1; // noop conversion.
7322 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7323 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7324 if (N1.isUndef())
7325 return getUNDEF(VT);
7326 break;
7328 assert(VT.isVector() && !N1.getValueType().isVector() &&
7329 (VT.getVectorElementType() == N1.getValueType() ||
7331 N1.getValueType().isInteger() &&
7333 "Illegal SCALAR_TO_VECTOR node!");
7334 if (N1.isUndef())
7335 return getUNDEF(VT);
7336 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7337 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7339 N1.getConstantOperandVal(1) == 0 &&
7340 N1.getOperand(0).getValueType() == VT)
7341 return N1.getOperand(0);
7342 break;
7343 case ISD::FNEG:
7344 // Negation of an unknown bag of bits is still completely undefined.
7345 if (N1.isUndef())
7346 return getUNDEF(VT);
7347
7348 if (OpOpcode == ISD::FNEG) // --X -> X
7349 return N1.getOperand(0);
7350 break;
7351 case ISD::FABS:
7352 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7353 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7354 break;
7355 case ISD::VSCALE:
7356 assert(VT == N1.getValueType() && "Unexpected VT!");
7357 break;
7358 case ISD::CTPOP:
7359 if (N1.getValueType().getScalarType() == MVT::i1)
7360 return N1;
7361 break;
7362 case ISD::CTLZ:
7363 case ISD::CTTZ:
7364 if (N1.getValueType().getScalarType() == MVT::i1)
7365 return getNOT(DL, N1, N1.getValueType());
7366 break;
7367 case ISD::CTLS:
7368 if (N1.getValueType().getScalarType() == MVT::i1)
7369 return getConstant(0, DL, VT);
7370 break;
7371 case ISD::VECREDUCE_ADD:
7372 if (N1.getValueType().getScalarType() == MVT::i1)
7373 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7374 break;
7377 if (N1.getValueType().getScalarType() == MVT::i1)
7378 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7379 break;
7382 if (N1.getValueType().getScalarType() == MVT::i1)
7383 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7384 break;
7385 case ISD::SPLAT_VECTOR:
7386 assert(VT.isVector() && "Wrong return type!");
7387 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7388 // that for now.
7390 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7392 N1.getValueType().isInteger() &&
7394 "Wrong operand type!");
7395 break;
7396 }
7397
7398 SDNode *N;
7399 SDVTList VTs = getVTList(VT);
7400 SDValue Ops[] = {N1};
7401 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7402 SDNodeKey ID(Opcode, VTs, Ops);
7403 FoldingSetInsertToken InsertToken;
7404 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7405 E->intersectFlagsWith(Flags);
7406 return SDValue(E, 0);
7407 }
7408
7409 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7410 N->setFlags(Flags);
7411 createOperands(N, Ops);
7412 CSEMap.insert(N, InsertToken);
7413 } else {
7414 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7415 createOperands(N, Ops);
7416 }
7417
7418 InsertNode(N);
7419 SDValue V = SDValue(N, 0);
7420 NewSDValueDbgMsg(V, "Creating new node: ", this);
7421 return V;
7422}
7423
7424static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7425 switch (Opcode) {
7426 default:
7427 llvm_unreachable("Unexpected integer identity opcode");
7428 case ISD::ADD:
7429 case ISD::OR:
7430 case ISD::XOR:
7431 case ISD::UMAX:
7432 return APInt::getZero(BitWidth);
7433 case ISD::MUL:
7434 return APInt(BitWidth, 1);
7435 case ISD::AND:
7436 case ISD::UMIN:
7438 case ISD::SMAX:
7440 case ISD::SMIN:
7442 }
7443}
7444
7445static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7446 const APInt &C2) {
7447 switch (Opcode) {
7448 case ISD::ADD: return C1 + C2;
7449 case ISD::SUB: return C1 - C2;
7450 case ISD::MUL: return C1 * C2;
7451 case ISD::AND: return C1 & C2;
7452 case ISD::OR: return C1 | C2;
7453 case ISD::XOR: return C1 ^ C2;
7454 case ISD::SHL: return C1 << C2;
7455 case ISD::SRL: return C1.lshr(C2);
7456 case ISD::SRA: return C1.ashr(C2);
7457 case ISD::ROTL: return C1.rotl(C2);
7458 case ISD::ROTR: return C1.rotr(C2);
7459 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7460 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7461 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7462 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7463 case ISD::SADDSAT: return C1.sadd_sat(C2);
7464 case ISD::UADDSAT: return C1.uadd_sat(C2);
7465 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7466 case ISD::USUBSAT: return C1.usub_sat(C2);
7467 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7468 case ISD::USHLSAT: return C1.ushl_sat(C2);
7469 case ISD::UDIV:
7470 if (!C2.getBoolValue())
7471 break;
7472 return C1.udiv(C2);
7473 case ISD::UREM:
7474 if (!C2.getBoolValue())
7475 break;
7476 return C1.urem(C2);
7477 case ISD::SDIV:
7478 if (!C2.getBoolValue())
7479 break;
7480 return C1.sdiv(C2);
7481 case ISD::SREM:
7482 if (!C2.getBoolValue())
7483 break;
7484 return C1.srem(C2);
7485 case ISD::AVGFLOORS:
7486 return APIntOps::avgFloorS(C1, C2);
7487 case ISD::AVGFLOORU:
7488 return APIntOps::avgFloorU(C1, C2);
7489 case ISD::AVGCEILS:
7490 return APIntOps::avgCeilS(C1, C2);
7491 case ISD::AVGCEILU:
7492 return APIntOps::avgCeilU(C1, C2);
7493 case ISD::ABDS:
7494 return APIntOps::abds(C1, C2);
7495 case ISD::ABDU:
7496 return APIntOps::abdu(C1, C2);
7497 case ISD::MULHS:
7498 return APIntOps::mulhs(C1, C2);
7499 case ISD::MULHU:
7500 return APIntOps::mulhu(C1, C2);
7501 case ISD::CLMUL:
7502 return APIntOps::clmul(C1, C2);
7503 case ISD::CLMULR:
7504 return APIntOps::clmulr(C1, C2);
7505 case ISD::CLMULH:
7506 return APIntOps::clmulh(C1, C2);
7507 case ISD::PEXT:
7508 return APIntOps::pext(C1, C2);
7509 case ISD::PDEP:
7510 return APIntOps::pdep(C1, C2);
7511 }
7512 return std::nullopt;
7513}
7514// Handle constant folding with UNDEF.
7515// TODO: Handle more cases.
7516static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7517 bool IsUndef1, const APInt &C2,
7518 bool IsUndef2) {
7519 if (!(IsUndef1 || IsUndef2))
7520 return FoldValue(Opcode, C1, C2);
7521
7522 // Fold and(x, undef) -> 0
7523 // Fold mul(x, undef) -> 0
7524 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7525 return APInt::getZero(C1.getBitWidth());
7526
7527 return std::nullopt;
7528}
7529
7531 const GlobalAddressSDNode *GA,
7532 const SDNode *N2) {
7533 if (GA->getOpcode() != ISD::GlobalAddress)
7534 return SDValue();
7535 if (!TLI->isOffsetFoldingLegal(GA))
7536 return SDValue();
7537 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7538 if (!C2)
7539 return SDValue();
7540 int64_t Offset = C2->getSExtValue();
7541 switch (Opcode) {
7542 case ISD::ADD:
7543 case ISD::PTRADD:
7544 break;
7545 case ISD::SUB: Offset = -uint64_t(Offset); break;
7546 default: return SDValue();
7547 }
7548 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7549 GA->getOffset() + uint64_t(Offset));
7550}
7551
7553 switch (Opcode) {
7554 case ISD::SDIV:
7555 case ISD::UDIV:
7556 case ISD::SREM:
7557 case ISD::UREM: {
7558 // If a divisor is zero/undef or any element of a divisor vector is
7559 // zero/undef, the whole op is undef.
7560 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7561 SDValue Divisor = Ops[1];
7562 if (Divisor.isUndef() || isNullConstant(Divisor))
7563 return true;
7564
7565 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7566 llvm::any_of(Divisor->op_values(),
7567 [](SDValue V) { return V.isUndef() ||
7568 isNullConstant(V); });
7569 // TODO: Handle signed overflow.
7570 }
7571 // TODO: Handle oversized shifts.
7572 default:
7573 return false;
7574 }
7575}
7576
7579 SDNodeFlags Flags) {
7580 // If the opcode is a target-specific ISD node, there's nothing we can
7581 // do here and the operand rules may not line up with the below, so
7582 // bail early.
7583 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7584 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7585 // foldCONCAT_VECTORS in getNode before this is called.
7586 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7587 return SDValue();
7588
7589 unsigned NumOps = Ops.size();
7590 if (NumOps == 0)
7591 return SDValue();
7592
7593 if (isUndef(Opcode, Ops))
7594 return getUNDEF(VT);
7595
7596 // Handle unary special cases.
7597 if (NumOps == 1) {
7598 SDValue N1 = Ops[0];
7599
7600 // Constant fold unary operations with an integer constant operand. Even
7601 // opaque constant will be folded, because the folding of unary operations
7602 // doesn't create new constants with different values. Nevertheless, the
7603 // opaque flag is preserved during folding to prevent future folding with
7604 // other constants.
7605 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7606 const APInt &Val = C->getAPIntValue();
7607 switch (Opcode) {
7608 case ISD::SIGN_EXTEND:
7609 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7610 C->isTargetOpcode(), C->isOpaque());
7611 case ISD::TRUNCATE:
7612 if (C->isOpaque())
7613 break;
7614 [[fallthrough]];
7615 case ISD::ZERO_EXTEND:
7616 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7617 C->isTargetOpcode(), C->isOpaque());
7618 case ISD::ANY_EXTEND:
7619 // Some targets like RISCV prefer to sign extend some types.
7620 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7621 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7622 C->isTargetOpcode(), C->isOpaque());
7623 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7624 C->isTargetOpcode(), C->isOpaque());
7625 case ISD::ABS:
7626 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7627 C->isOpaque());
7629 if (Val.isMinSignedValue())
7630 return getPOISON(VT);
7631 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7632 C->isOpaque());
7633 case ISD::BITREVERSE:
7634 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7635 C->isOpaque());
7636 case ISD::BSWAP:
7637 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7638 C->isOpaque());
7639 case ISD::CTPOP:
7640 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7641 C->isOpaque());
7642 case ISD::CTLZ:
7644 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7645 C->isOpaque());
7646 case ISD::CTTZ:
7648 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7649 C->isOpaque());
7650 case ISD::CTLS:
7651 // CTLS returns the number of extra sign bits so subtract one.
7652 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7653 C->isTargetOpcode(), C->isOpaque());
7654 case ISD::UINT_TO_FP:
7655 case ISD::SINT_TO_FP: {
7657 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7659 return getConstantFP(FPV, DL, VT);
7660 }
7661 case ISD::FP16_TO_FP:
7662 case ISD::BF16_TO_FP: {
7663 bool Ignored;
7664 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7665 : APFloat::BFloat(),
7666 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7667
7668 // This can return overflow, underflow, or inexact; we don't care.
7669 // FIXME need to be more flexible about rounding mode.
7671 &Ignored);
7672 return getConstantFP(FPV, DL, VT);
7673 }
7674 case ISD::STEP_VECTOR:
7675 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7676 return V;
7677 break;
7678 case ISD::BITCAST:
7679 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7680 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7681 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7682 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7683 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7684 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7685 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7686 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7687 break;
7688 }
7689 }
7690
7691 // Constant fold unary operations with a floating point constant operand.
7692 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7693 APFloat V = C->getValueAPF(); // make copy
7694 switch (Opcode) {
7695 case ISD::FNEG:
7696 V.changeSign();
7697 return getConstantFP(V, DL, VT);
7698 case ISD::FABS:
7699 V.clearSign();
7700 return getConstantFP(V, DL, VT);
7701 case ISD::FCEIL: {
7702 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7704 return getConstantFP(V, DL, VT);
7705 return SDValue();
7706 }
7707 case ISD::FTRUNC: {
7708 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7710 return getConstantFP(V, DL, VT);
7711 return SDValue();
7712 }
7713 case ISD::FFLOOR: {
7714 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7716 return getConstantFP(V, DL, VT);
7717 return SDValue();
7718 }
7719 case ISD::FP_EXTEND: {
7720 bool ignored;
7721 // This can return overflow, underflow, or inexact; we don't care.
7722 // FIXME need to be more flexible about rounding mode.
7723 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7724 &ignored);
7725 return getConstantFP(V, DL, VT);
7726 }
7727 case ISD::FP_TO_SINT:
7728 case ISD::FP_TO_UINT: {
7729 bool ignored;
7730 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7731 // FIXME need to be more flexible about rounding mode.
7733 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7734 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7735 break;
7736 return getConstant(IntVal, DL, VT);
7737 }
7738 case ISD::FP_TO_FP16:
7739 case ISD::FP_TO_BF16: {
7740 bool Ignored;
7741 // This can return overflow, underflow, or inexact; we don't care.
7742 // FIXME need to be more flexible about rounding mode.
7743 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7744 : APFloat::BFloat(),
7746 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7747 }
7748 case ISD::BITCAST:
7749 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7750 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7751 VT);
7752 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7753 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7754 VT);
7755 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7756 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7757 VT);
7758 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7759 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7760 break;
7761 }
7762 }
7763
7764 // Early-out if we failed to constant fold a bitcast.
7765 if (Opcode == ISD::BITCAST)
7766 return SDValue();
7767
7768 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7769 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7770 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7771 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7772 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7773 Opcode == ISD::VECREDUCE_AND) &&
7775 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7776 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7777 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7778 for (SDValue Elt : N1->op_values()) {
7779 if (Elt.getOpcode() == ISD::POISON)
7780 return getPOISON(VT);
7781 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7782 return SDValue();
7783 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7784 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7785 assert(Folded &&
7786 "Expected vector reduction base opcode to be foldable");
7787 Acc = *Folded;
7788 }
7789 EVT EltVT = N1.getValueType().getScalarType();
7790 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7791 }
7792 }
7793
7794 // Handle binops special cases.
7795 if (NumOps == 2) {
7796 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7797 return CFP;
7798
7799 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7800 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7801 if (C1->isOpaque() || C2->isOpaque())
7802 return SDValue();
7803
7804 std::optional<APInt> FoldAttempt =
7805 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7806 if (!FoldAttempt)
7807 return SDValue();
7808
7809 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7810 assert((!Folded || !VT.isVector()) &&
7811 "Can't fold vectors ops with scalar operands");
7812 return Folded;
7813 }
7814 }
7815
7816 // fold (add Sym, c) -> Sym+c
7818 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7819 if (TLI->isCommutativeBinOp(Opcode))
7821 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7822
7823 // fold (sext_in_reg c1) -> c2
7824 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7825 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7826
7827 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7828 unsigned FromBits = EVT.getScalarSizeInBits();
7829 Val <<= Val.getBitWidth() - FromBits;
7830 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7831 return getConstant(Val, DL, ConstantVT);
7832 };
7833
7834 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7835 const APInt &Val = C1->getAPIntValue();
7836 return SignExtendInReg(Val, VT);
7837 }
7838
7840 SmallVector<SDValue, 8> ScalarOps;
7841 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7842 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7843 SDValue Op = Ops[0].getOperand(I);
7844 if (Op.isUndef()) {
7845 ScalarOps.push_back(getUNDEF(OpVT));
7846 continue;
7847 }
7848 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7849 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7850 }
7851 return getBuildVector(VT, DL, ScalarOps);
7852 }
7853
7854 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7855 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7856 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7857 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7858 Ops[0].getOperand(0).getValueType()));
7859 }
7860 }
7861
7862 // Handle fshl/fshr special cases.
7863 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7864 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7865 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7866 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7867
7868 if (C1 && C2 && C3) {
7869 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7870 return SDValue();
7871 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7872 &V3 = C3->getAPIntValue();
7873
7874 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7875 : APIntOps::fshr(V1, V2, V3);
7876 return getConstant(FoldedVal, DL, VT);
7877 }
7878 }
7879
7880 // Handle fma/fmad special cases.
7881 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7882 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7883 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7884 Ops[2].getValueType() == VT && "FMA types must match!");
7888 if (C1 && C2 && C3) {
7889 APFloat V1 = C1->getValueAPF();
7890 const APFloat &V2 = C2->getValueAPF();
7891 const APFloat &V3 = C3->getValueAPF();
7892 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7893 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7895 } else
7896 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7897 return getConstantFP(V1, DL, VT);
7898 }
7899 }
7900
7901 // This is for vector folding only from here on.
7902 if (!VT.isVector())
7903 return SDValue();
7904
7905 // Constant fold integer partial reductions with constant BUILD_VECTOR
7906 // operands. The reduction order is deliberately unspecified. Use the same
7907 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
7908 // lane I contributes to accumulator lane I % NumAccElts.
7909 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
7910 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
7911 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
7912 // These nodes have no scalar form, so unsupported cases must not fall
7913 // through to generic per-lane vector folding.
7914 if (!llvm::all_of(Ops, [](SDValue Op) {
7915 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
7916 }))
7917 return SDValue();
7918
7919 unsigned AccEltBits = VT.getScalarSizeInBits();
7920 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
7921 unsigned NumAccElts = VT.getVectorNumElements();
7922 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
7923 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
7924 BitVector PoisonElts(NumAccElts);
7925
7926 for (unsigned I = 0; I != NumAccElts; ++I) {
7927 SDValue Elt = Ops[0].getOperand(I);
7928 if (Elt.getOpcode() == ISD::POISON) {
7929 PoisonElts.set(I);
7930 continue;
7931 }
7932 auto *C = dyn_cast<ConstantSDNode>(Elt);
7933 if (!C || C->isOpaque())
7934 return SDValue();
7935 Results[I] = C->getAPIntValue().trunc(AccEltBits);
7936 }
7937
7938 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
7939 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
7940 for (unsigned I = 0; I != NumInputElts; ++I) {
7941 const unsigned AccIdx = I % NumAccElts;
7942 SDValue LHSElt = Ops[1].getOperand(I);
7943 SDValue RHSElt = Ops[2].getOperand(I);
7944 if (LHSElt.getOpcode() == ISD::POISON ||
7945 RHSElt.getOpcode() == ISD::POISON) {
7946 PoisonElts.set(AccIdx);
7947 continue;
7948 }
7949
7950 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
7951 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
7952 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
7953 return SDValue();
7954
7955 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
7956 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
7957 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
7958 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
7959 Results[AccIdx] += LHSVal * RHSVal;
7960 }
7961
7962 // After type legalization the vector element type may not be a legal
7963 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
7964 // promoted legal scalar type instead, matching the generic per-lane path
7965 // below. Bail out if legalization would narrow the type, since the lane
7966 // value would not fit.
7967 EVT AccEltVT = VT.getVectorElementType();
7968 EVT LegalSVT = AccEltVT;
7969 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
7970 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
7971 if (LegalSVT.bitsLT(AccEltVT))
7972 return SDValue();
7973 }
7974
7975 SmallVector<SDValue, 8> ResultOps;
7976 for (unsigned I = 0; I != NumAccElts; ++I)
7977 ResultOps.push_back(
7978 PoisonElts[I] ? getPOISON(LegalSVT)
7979 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
7980 DL, LegalSVT));
7981 return getBuildVector(VT, DL, ResultOps);
7982 }
7983
7984 ElementCount NumElts = VT.getVectorElementCount();
7985
7986 // See if we can fold through any bitcasted integer ops.
7987 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
7988 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7989 (Ops[0].getOpcode() == ISD::BITCAST ||
7990 Ops[1].getOpcode() == ISD::BITCAST)) {
7993 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7994 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
7995 if (BV1 && BV2 && N1.getValueType().isInteger() &&
7996 N2.getValueType().isInteger()) {
7997 bool IsLE = getDataLayout().isLittleEndian();
7998 unsigned EltBits = VT.getScalarSizeInBits();
7999 SmallVector<APInt> RawBits1, RawBits2;
8000 BitVector UndefElts1, UndefElts2;
8001 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8002 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8003 SmallVector<APInt> RawBits;
8004 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8005 std::optional<APInt> Fold = FoldValueWithUndef(
8006 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8007 if (!Fold)
8008 break;
8009 RawBits.push_back(*Fold);
8010 }
8011 if (RawBits.size() == NumElts.getFixedValue()) {
8012 // We have constant folded, but we might need to cast this again back
8013 // to the original (possibly legalized) type.
8014 EVT BVVT, BVEltVT;
8015 if (N1.getValueType() == VT) {
8016 BVVT = N1.getValueType();
8017 BVEltVT = BV1->getOperand(0).getValueType();
8018 } else {
8019 BVVT = N2.getValueType();
8020 BVEltVT = BV2->getOperand(0).getValueType();
8021 }
8022 unsigned BVEltBits = BVEltVT.getSizeInBits();
8023 SmallVector<APInt> DstBits;
8024 BitVector DstUndefs;
8026 DstBits, RawBits, DstUndefs,
8027 BitVector(RawBits.size(), false));
8028 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8029 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8030 if (DstUndefs[I])
8031 continue;
8032 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8033 }
8034 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8035 }
8036 }
8037 }
8038 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8039 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8040 isa<ConstantSDNode>(N2)) {
8041 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8042 {N1, N2}, Flags))
8043 return getBitcast(VT, Res);
8044 }
8045 }
8046
8047 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8048 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8049 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8050 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8051 APInt RHSVal;
8052 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8053 APInt NewStep = Opcode == ISD::MUL
8054 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8055 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8056 return getStepVector(DL, VT, NewStep);
8057 }
8058 }
8059
8060 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8061 return !Op.getValueType().isVector() ||
8062 Op.getValueType().getVectorElementCount() == NumElts;
8063 };
8064
8065 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8066 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8067 Op.getOpcode() == ISD::BUILD_VECTOR ||
8068 Op.getOpcode() == ISD::SPLAT_VECTOR;
8069 };
8070
8071 // All operands must be vector types with the same number of elements as
8072 // the result type and must be either UNDEF or a build/splat vector
8073 // or UNDEF scalars.
8074 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8075 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8076 return SDValue();
8077
8078 // If we are comparing vectors, then the result needs to be a i1 boolean that
8079 // is then extended back to the legal result type depending on how booleans
8080 // are represented.
8081 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8082 ISD::NodeType ExtendCode =
8083 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8084 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8086
8087 // Find legal integer scalar type for constant promotion and
8088 // ensure that its scalar size is at least as large as source.
8089 EVT LegalSVT = VT.getScalarType();
8090 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8091 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8092 if (LegalSVT.bitsLT(VT.getScalarType()))
8093 return SDValue();
8094 }
8095
8096 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8097 // only have one operand to check. For fixed-length vector types we may have
8098 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8099 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8100
8101 // Constant fold each scalar lane separately.
8102 SmallVector<SDValue, 4> ScalarResults;
8103 for (unsigned I = 0; I != NumVectorElts; I++) {
8104 SmallVector<SDValue, 4> ScalarOps;
8105 for (SDValue Op : Ops) {
8106 EVT InSVT = Op.getValueType().getScalarType();
8107 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8108 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8109 if (Op.isUndef())
8110 ScalarOps.push_back(getUNDEF(InSVT));
8111 else
8112 ScalarOps.push_back(Op);
8113 continue;
8114 }
8115
8116 SDValue ScalarOp =
8117 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8118 EVT ScalarVT = ScalarOp.getValueType();
8119
8120 // Build vector (integer) scalar operands may need implicit
8121 // truncation - do this before constant folding.
8122 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8123 // Don't create illegally-typed nodes unless they're constants or undef
8124 // - if we fail to constant fold we can't guarantee the (dead) nodes
8125 // we're creating will be cleaned up before being visited for
8126 // legalization.
8127 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8128 !isa<ConstantSDNode>(ScalarOp) &&
8129 TLI->getTypeAction(*getContext(), InSVT) !=
8131 return SDValue();
8132 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8133 }
8134
8135 ScalarOps.push_back(ScalarOp);
8136 }
8137
8138 // Constant fold the scalar operands.
8139 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8140
8141 // Scalar folding only succeeded if the result is a constant or UNDEF.
8142 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8143 ScalarResult.getOpcode() != ISD::ConstantFP)
8144 return SDValue();
8145
8146 // Legalize the (integer) scalar constant if necessary. We only do
8147 // this once we know the folding succeeded, since otherwise we would
8148 // get a node with illegal type which has a user.
8149 if (LegalSVT != SVT)
8150 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8151
8152 ScalarResults.push_back(ScalarResult);
8153 }
8154
8155 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8156 : getBuildVector(VT, DL, ScalarResults);
8157 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8158 return V;
8159}
8160
8163 // TODO: Add support for unary/ternary fp opcodes.
8164 if (Ops.size() != 2)
8165 return SDValue();
8166
8167 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8168 // should. That will require dealing with a potentially non-default
8169 // rounding mode, checking the "opStatus" return value from the APFloat
8170 // math calculations, and possibly other variations.
8171 SDValue N1 = Ops[0];
8172 SDValue N2 = Ops[1];
8173 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8174 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8175 if (N1CFP && N2CFP) {
8176 APFloat C1 = N1CFP->getValueAPF(); // make copy
8177 const APFloat &C2 = N2CFP->getValueAPF();
8178 switch (Opcode) {
8179 case ISD::FADD:
8181 return getConstantFP(C1, DL, VT);
8182 case ISD::FSUB:
8184 return getConstantFP(C1, DL, VT);
8185 case ISD::FMUL:
8187 return getConstantFP(C1, DL, VT);
8188 case ISD::FDIV:
8190 return getConstantFP(C1, DL, VT);
8191 case ISD::FREM:
8192 C1.mod(C2);
8193 return getConstantFP(C1, DL, VT);
8194 case ISD::FCOPYSIGN:
8195 C1.copySign(C2);
8196 return getConstantFP(C1, DL, VT);
8197 case ISD::FMINNUM:
8198 return getConstantFP(minnum(C1, C2), DL, VT);
8199 case ISD::FMAXNUM:
8200 return getConstantFP(maxnum(C1, C2), DL, VT);
8201 case ISD::FMINIMUM:
8202 return getConstantFP(minimum(C1, C2), DL, VT);
8203 case ISD::FMAXIMUM:
8204 return getConstantFP(maximum(C1, C2), DL, VT);
8205 case ISD::FMINIMUMNUM:
8206 return getConstantFP(minimumnum(C1, C2), DL, VT);
8207 case ISD::FMAXIMUMNUM:
8208 return getConstantFP(maximumnum(C1, C2), DL, VT);
8209 default: break;
8210 }
8211 }
8212 if (N1CFP && Opcode == ISD::FP_ROUND) {
8213 APFloat C1 = N1CFP->getValueAPF(); // make copy
8214 bool Unused;
8215 // This can return overflow, underflow, or inexact; we don't care.
8216 // FIXME need to be more flexible about rounding mode.
8218 &Unused);
8219 return getConstantFP(C1, DL, VT);
8220 }
8221
8222 switch (Opcode) {
8223 case ISD::FSUB:
8224 // -0.0 - undef --> undef (consistent with "fneg undef")
8225 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8226 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8227 return getUNDEF(VT);
8228 [[fallthrough]];
8229
8230 case ISD::FADD:
8231 case ISD::FMUL:
8232 case ISD::FDIV:
8233 case ISD::FREM:
8234 // If both operands are undef, the result is undef. If 1 operand is undef,
8235 // the result is NaN. This should match the behavior of the IR optimizer.
8236 if (N1.isUndef() && N2.isUndef())
8237 return getUNDEF(VT);
8238 if (N1.isUndef() || N2.isUndef())
8240 }
8241 return SDValue();
8242}
8243
8245 const SDLoc &DL, EVT DstEltVT) {
8246 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8247
8248 // If this is already the right type, we're done.
8249 if (SrcEltVT == DstEltVT)
8250 return SDValue(BV, 0);
8251
8252 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8253 unsigned DstBitSize = DstEltVT.getSizeInBits();
8254
8255 // If this is a conversion of N elements of one type to N elements of another
8256 // type, convert each element. This handles FP<->INT cases.
8257 if (SrcBitSize == DstBitSize) {
8259 for (SDValue Op : BV->op_values()) {
8260 // If the vector element type is not legal, the BUILD_VECTOR operands
8261 // are promoted and implicitly truncated. Make that explicit here.
8262 if (Op.getValueType() != SrcEltVT)
8263 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8264 Ops.push_back(getBitcast(DstEltVT, Op));
8265 }
8266 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8268 return getBuildVector(VT, DL, Ops);
8269 }
8270
8271 // Otherwise, we're growing or shrinking the elements. To avoid having to
8272 // handle annoying details of growing/shrinking FP values, we convert them to
8273 // int first.
8274 if (SrcEltVT.isFloatingPoint()) {
8275 // Convert the input float vector to a int vector where the elements are the
8276 // same sizes.
8277 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8278 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8280 DstEltVT);
8281 return SDValue();
8282 }
8283
8284 // Now we know the input is an integer vector. If the output is a FP type,
8285 // convert to integer first, then to FP of the right size.
8286 if (DstEltVT.isFloatingPoint()) {
8287 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8288 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8290 DstEltVT);
8291 return SDValue();
8292 }
8293
8294 // Okay, we know the src/dst types are both integers of differing types.
8295 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8296
8297 // Extract the constant raw bit data.
8298 BitVector UndefElements;
8299 SmallVector<APInt> RawBits;
8300 bool IsLE = getDataLayout().isLittleEndian();
8301 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8302 return SDValue();
8303
8305 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8306 if (UndefElements[I])
8307 Ops.push_back(getUNDEF(DstEltVT));
8308 else
8309 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8310 }
8311
8312 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8313 return getBuildVector(VT, DL, Ops);
8314}
8315
8317 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8318
8319 // There's no need to assert on a byte-aligned pointer. All pointers are at
8320 // least byte aligned.
8321 if (A == Align(1))
8322 return Val;
8323
8324 SDVTList VTs = getVTList(Val.getValueType());
8325 SDValue Ops[] = {Val};
8326 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8327 ID.AddInteger(A.value());
8328
8329 FoldingSetInsertToken InsertToken;
8330 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8331 return SDValue(E, 0);
8332
8333 auto *N =
8334 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8335 createOperands(N, {Val});
8336
8337 CSEMap.insert(N, InsertToken);
8338 InsertNode(N);
8339
8340 SDValue V(N, 0);
8341 NewSDValueDbgMsg(V, "Creating new node: ", this);
8342 return V;
8343}
8344
8345SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8346 SDValue N1, SDValue N2) {
8347 SDNodeFlags Flags;
8348 if (Inserter)
8349 Flags = Inserter->getFlags();
8350 return getNode(Opcode, DL, VT, N1, N2, Flags);
8351}
8352
8354 SDValue &N2) const {
8355 if (!TLI->isCommutativeBinOp(Opcode))
8356 return;
8357
8358 // Canonicalize:
8359 // binop(const, nonconst) -> binop(nonconst, const)
8362 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8363 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8364 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8365 std::swap(N1, N2);
8366
8367 // Canonicalize:
8368 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8369 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8371 std::swap(N1, N2);
8372}
8373
8374SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8375 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8377 N2.getOpcode() != ISD::DELETED_NODE &&
8378 "Operand is DELETED_NODE!");
8379
8380 canonicalizeCommutativeBinop(Opcode, N1, N2);
8381
8382 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8383 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8384
8385 // Don't allow undefs in vector splats - we might be returning N2 when folding
8386 // to zero etc.
8387 ConstantSDNode *N2CV =
8388 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8389
8390 switch (Opcode) {
8391 default: break;
8392 case ISD::TokenFactor:
8393 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8394 N2.getValueType() == MVT::Other && "Invalid token factor!");
8395 // Fold trivial token factors.
8396 if (N1.getOpcode() == ISD::EntryToken) return N2;
8397 if (N2.getOpcode() == ISD::EntryToken) return N1;
8398 if (N1 == N2) return N1;
8399 break;
8400 case ISD::BUILD_VECTOR: {
8401 // Attempt to simplify BUILD_VECTOR.
8402 SDValue Ops[] = {N1, N2};
8403 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8404 return V;
8405 break;
8406 }
8407 case ISD::CONCAT_VECTORS: {
8408 SDValue Ops[] = {N1, N2};
8409 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8410 return V;
8411 break;
8412 }
8413 case ISD::AND:
8414 assert(VT.isInteger() && "This operator does not apply to FP types!");
8415 assert(N1.getValueType() == N2.getValueType() &&
8416 N1.getValueType() == VT && "Binary operator types must match!");
8417 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8418 // worth handling here.
8419 if (N2CV && N2CV->isZero())
8420 return N2;
8421 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8422 return N1;
8423 break;
8424 case ISD::OR:
8425 case ISD::XOR:
8426 case ISD::ADD:
8427 case ISD::PTRADD:
8428 case ISD::SUB:
8429 assert(VT.isInteger() && "This operator does not apply to FP types!");
8430 assert(N1.getValueType() == N2.getValueType() &&
8431 N1.getValueType() == VT && "Binary operator types must match!");
8432 // The equal operand types requirement is unnecessarily strong for PTRADD.
8433 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8434 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8435 // logic everywhere where PTRADDs may be folded or combined to properly
8436 // support them. If/when we introduce pointer types to the SDAG, we will
8437 // need to relax this constraint.
8438
8439 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8440 // it's worth handling here.
8441 if (N2CV && N2CV->isZero())
8442 return N1;
8443 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8444 VT.getScalarType() == MVT::i1)
8445 return getNode(ISD::XOR, DL, VT, N1, N2);
8446 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8447 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8448 N2.getOpcode() == ISD::VSCALE) {
8449 const APInt &C1 = N1->getConstantOperandAPInt(0);
8450 const APInt &C2 = N2->getConstantOperandAPInt(0);
8451 return getVScale(DL, VT, C1 + C2);
8452 }
8453 break;
8454 case ISD::MUL:
8455 assert(VT.isInteger() && "This operator does not apply to FP types!");
8456 assert(N1.getValueType() == N2.getValueType() &&
8457 N1.getValueType() == VT && "Binary operator types must match!");
8458 if (VT.getScalarType() == MVT::i1)
8459 return getNode(ISD::AND, DL, VT, N1, N2);
8460 if (N2CV && N2CV->isZero())
8461 return N2;
8462 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8463 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8464 const APInt &N2CImm = N2C->getAPIntValue();
8465 return getVScale(DL, VT, MulImm * N2CImm);
8466 }
8467 break;
8468 case ISD::UDIV:
8469 case ISD::UREM:
8470 case ISD::MULHU:
8471 case ISD::MULHS:
8472 case ISD::SDIV:
8473 case ISD::SREM:
8474 case ISD::SADDSAT:
8475 case ISD::SSUBSAT:
8476 case ISD::UADDSAT:
8477 case ISD::USUBSAT:
8478 assert(VT.isInteger() && "This operator does not apply to FP types!");
8479 assert(N1.getValueType() == N2.getValueType() &&
8480 N1.getValueType() == VT && "Binary operator types must match!");
8481 if (VT.getScalarType() == MVT::i1) {
8482 // fold (add_sat x, y) -> (or x, y) for bool types.
8483 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8484 return getNode(ISD::OR, DL, VT, N1, N2);
8485 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8486 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8487 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8488 }
8489 break;
8490 case ISD::SCMP:
8491 case ISD::UCMP:
8492 assert(N1.getValueType() == N2.getValueType() &&
8493 "Types of operands of UCMP/SCMP must match");
8494 assert(N1.getValueType().isVector() == VT.isVector() &&
8495 "Operands and return type of must both be scalars or vectors");
8496 if (VT.isVector())
8499 "Result and operands must have the same number of elements");
8500 break;
8501 case ISD::AVGFLOORS:
8502 case ISD::AVGFLOORU:
8503 case ISD::AVGCEILS:
8504 case ISD::AVGCEILU:
8505 assert(VT.isInteger() && "This operator does not apply to FP types!");
8506 assert(N1.getValueType() == N2.getValueType() &&
8507 N1.getValueType() == VT && "Binary operator types must match!");
8508 break;
8509 case ISD::ABDS:
8510 case ISD::ABDU:
8511 assert(VT.isInteger() && "This operator does not apply to FP types!");
8512 assert(N1.getValueType() == N2.getValueType() &&
8513 N1.getValueType() == VT && "Binary operator types must match!");
8514 if (VT.getScalarType() == MVT::i1)
8515 return getNode(ISD::XOR, DL, VT, N1, N2);
8516 break;
8517 case ISD::SMIN:
8518 case ISD::UMAX:
8519 assert(VT.isInteger() && "This operator does not apply to FP types!");
8520 assert(N1.getValueType() == N2.getValueType() &&
8521 N1.getValueType() == VT && "Binary operator types must match!");
8522 if (VT.getScalarType() == MVT::i1)
8523 return getNode(ISD::OR, DL, VT, N1, N2);
8524 break;
8525 case ISD::SMAX:
8526 case ISD::UMIN:
8527 assert(VT.isInteger() && "This operator does not apply to FP types!");
8528 assert(N1.getValueType() == N2.getValueType() &&
8529 N1.getValueType() == VT && "Binary operator types must match!");
8530 if (VT.getScalarType() == MVT::i1)
8531 return getNode(ISD::AND, DL, VT, N1, N2);
8532 break;
8533 case ISD::FADD:
8534 case ISD::FSUB:
8535 case ISD::FMUL:
8536 case ISD::FDIV:
8537 case ISD::FREM:
8538 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8539 assert(N1.getValueType() == N2.getValueType() &&
8540 N1.getValueType() == VT && "Binary operator types must match!");
8541 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8542 return V;
8543 break;
8544 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8545 assert(N1.getValueType() == VT &&
8548 "Invalid FCOPYSIGN!");
8549 break;
8550 case ISD::SHL:
8551 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8552 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8553 const APInt &ShiftImm = N2C->getAPIntValue();
8554 return getVScale(DL, VT, MulImm << ShiftImm);
8555 }
8556 [[fallthrough]];
8557 case ISD::SRA:
8558 case ISD::SRL:
8559 if (SDValue V = simplifyShift(N1, N2))
8560 return V;
8561 [[fallthrough]];
8562 case ISD::ROTL:
8563 case ISD::ROTR:
8564 case ISD::SSHLSAT:
8565 case ISD::USHLSAT:
8566 assert(VT == N1.getValueType() &&
8567 "Shift operators return type must be the same as their first arg");
8568 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8569 "Shifts only work on integers");
8570 assert((!VT.isVector() || VT == N2.getValueType()) &&
8571 "Vector shift amounts must be in the same as their first arg");
8572 // Verify that the shift amount VT is big enough to hold valid shift
8573 // amounts. This catches things like trying to shift an i1024 value by an
8574 // i8, which is easy to fall into in generic code that uses
8575 // TLI.getShiftAmount().
8578 "Invalid use of small shift amount with oversized value!");
8579
8580 // Always fold shifts of i1 values so the code generator doesn't need to
8581 // handle them. Since we know the size of the shift has to be less than the
8582 // size of the value, the shift/rotate count is guaranteed to be zero.
8583 if (VT == MVT::i1)
8584 return N1;
8585 if (N2CV && N2CV->isZero())
8586 return N1;
8587 break;
8588 case ISD::FP_ROUND:
8590 VT.bitsLE(N1.getValueType()) && N2C &&
8591 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8592 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8593 if (N1.getValueType() == VT) return N1; // noop conversion.
8594 break;
8595 case ISD::IS_FPCLASS: {
8597 "IS_FPCLASS is used for a non-floating type");
8598 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8599 // is.fpclass(poison, mask) -> poison
8600 if (N1.getOpcode() == ISD::POISON)
8601 return getPOISON(VT);
8602 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8603 // If all tests are made, it doesn't matter what the value is.
8604 if ((Mask & fcAllFlags) == fcAllFlags)
8605 return getBoolConstant(true, DL, VT, N1.getValueType());
8606 if ((Mask & fcAllFlags) == 0)
8607 return getBoolConstant(false, DL, VT, N1.getValueType());
8608 break;
8609 }
8610 case ISD::AssertNoFPClass: {
8612 "AssertNoFPClass is used for a non-floating type");
8613 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8614 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8615 assert(llvm::to_underlying(NoFPClass) <=
8617 "FPClassTest value too large");
8618 (void)NoFPClass;
8619 break;
8620 }
8621 case ISD::AssertSext:
8622 case ISD::AssertZext: {
8623 EVT EVT = cast<VTSDNode>(N2)->getVT();
8624 assert(VT == N1.getValueType() && "Not an inreg extend!");
8625 assert(VT.isInteger() && EVT.isInteger() &&
8626 "Cannot *_EXTEND_INREG FP types");
8627 assert(!EVT.isVector() &&
8628 "AssertSExt/AssertZExt type should be the vector element type "
8629 "rather than the vector type!");
8630 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8631 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8632 break;
8633 }
8635 EVT EVT = cast<VTSDNode>(N2)->getVT();
8636 assert(VT == N1.getValueType() && "Not an inreg extend!");
8637 assert(VT.isInteger() && EVT.isInteger() &&
8638 "Cannot *_EXTEND_INREG FP types");
8639 assert(EVT.isVector() == VT.isVector() &&
8640 "SIGN_EXTEND_INREG type should be vector iff the operand "
8641 "type is vector!");
8642 assert((!EVT.isVector() ||
8644 "Vector element counts must match in SIGN_EXTEND_INREG");
8645 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8646 if (EVT == VT) return N1; // Not actually extending
8647 break;
8648 }
8650 case ISD::FP_TO_UINT_SAT: {
8651 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8652 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8653 assert(N1.getValueType().isVector() == VT.isVector() &&
8654 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8655 "vector!");
8656 assert((!VT.isVector() || VT.getVectorElementCount() ==
8658 "Vector element counts must match in FP_TO_*INT_SAT");
8659 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8660 "Type to saturate to must be a scalar.");
8661 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8662 "Not extending!");
8663 break;
8664 }
8667 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8668 element type of the vector.");
8669
8670 // Extract from an undefined value or using an undefined index is undefined.
8671 if (N1.isUndef() || N2.isUndef())
8672 return getUNDEF(VT);
8673
8674 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8675 // vectors. For scalable vectors we will provide appropriate support for
8676 // dealing with arbitrary indices.
8677 if (N2C && N1.getValueType().isFixedLengthVector() &&
8678 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8679 return getPOISON(VT);
8680
8681 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8682 // expanding copies of large vectors from registers. This only works for
8683 // fixed length vectors, since we need to know the exact number of
8684 // elements.
8685 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8687 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8688 return getExtractVectorElt(DL, VT,
8689 N1.getOperand(N2C->getZExtValue() / Factor),
8690 N2C->getZExtValue() % Factor);
8691 }
8692
8693 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8694 // lowering is expanding large vector constants.
8695 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8696 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8699 "BUILD_VECTOR used for scalable vectors");
8700 unsigned Index =
8701 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8702 SDValue Elt = N1.getOperand(Index);
8703
8704 if (VT != Elt.getValueType())
8705 // If the vector element type is not legal, the BUILD_VECTOR operands
8706 // are promoted and implicitly truncated, and the result implicitly
8707 // extended. Make that explicit here.
8708 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8709
8710 return Elt;
8711 }
8712
8713 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8714 // operations are lowered to scalars.
8715 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8716 // If the indices are the same, return the inserted element else
8717 // if the indices are known different, extract the element from
8718 // the original vector.
8719 SDValue N1Op2 = N1.getOperand(2);
8721
8722 if (N1Op2C && N2C) {
8723 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8724 if (VT == N1.getOperand(1).getValueType())
8725 return N1.getOperand(1);
8726 if (VT.isFloatingPoint()) {
8728 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8729 }
8730 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8731 }
8732 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8733 }
8734 }
8735
8736 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8737 // when vector types are scalarized and v1iX is legal.
8738 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8739 // Here we are completely ignoring the extract element index (N2),
8740 // which is fine for fixed width vectors, since any index other than 0
8741 // is undefined anyway. However, this cannot be ignored for scalable
8742 // vectors - in theory we could support this, but we don't want to do this
8743 // without a profitability check.
8744 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8746 N1.getValueType().getVectorNumElements() == 1) {
8747 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8748 N1.getOperand(1));
8749 }
8750 break;
8752 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8753 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8754 (N1.getValueType().isInteger() == VT.isInteger()) &&
8755 N1.getValueType() != VT &&
8756 "Wrong types for EXTRACT_ELEMENT!");
8757
8758 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8759 // 64-bit integers into 32-bit parts. Instead of building the extract of
8760 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8761 if (N1.getOpcode() == ISD::BUILD_PAIR)
8762 return N1.getOperand(N2C->getZExtValue());
8763
8764 // EXTRACT_ELEMENT of a constant int is also very common.
8765 if (N1C) {
8766 unsigned ElementSize = VT.getSizeInBits();
8767 unsigned Shift = ElementSize * N2C->getZExtValue();
8768 const APInt &Val = N1C->getAPIntValue();
8769 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8770 }
8771 break;
8773 EVT N1VT = N1.getValueType();
8774 assert(VT.isVector() && N1VT.isVector() &&
8775 "Extract subvector VTs must be vectors!");
8777 "Extract subvector VTs must have the same element type!");
8778 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8779 "Cannot extract a scalable vector from a fixed length vector!");
8780 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8782 "Extract subvector must be from larger vector to smaller vector!");
8783 assert(N2C && "Extract subvector index must be a constant");
8784 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8785 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8786 N1VT.getVectorMinNumElements()) &&
8787 "Extract subvector overflow!");
8788 assert(N2C->getAPIntValue().getBitWidth() ==
8789 TLI->getVectorIdxWidth(getDataLayout()) &&
8790 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8791 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8792 "Extract index is not a multiple of the output vector length");
8793
8794 // Trivial extraction.
8795 if (VT == N1VT)
8796 return N1;
8797
8798 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8799 if (N1.isUndef())
8800 return getUNDEF(VT);
8801
8802 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8803 // the concat have the same type as the extract.
8804 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8805 VT == N1.getOperand(0).getValueType()) {
8806 unsigned Factor = VT.getVectorMinNumElements();
8807 return N1.getOperand(N2C->getZExtValue() / Factor);
8808 }
8809
8810 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8811 // during shuffle legalization.
8812 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8813 VT == N1.getOperand(1).getValueType())
8814 return N1.getOperand(1);
8815 break;
8816 }
8817 }
8818
8819 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8820 switch (Opcode) {
8821 case ISD::XOR:
8822 case ISD::ADD:
8823 case ISD::PTRADD:
8824 case ISD::SUB:
8826 case ISD::UDIV:
8827 case ISD::SDIV:
8828 case ISD::UREM:
8829 case ISD::SREM:
8830 case ISD::MUL:
8831 case ISD::AND:
8832 case ISD::SSUBSAT:
8833 case ISD::USUBSAT:
8834 case ISD::UMIN:
8835 case ISD::OR:
8836 case ISD::SADDSAT:
8837 case ISD::UADDSAT:
8838 case ISD::UMAX:
8839 case ISD::SMAX:
8840 case ISD::SMIN:
8841 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8842 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8843 }
8844 }
8845
8846 // Canonicalize an UNDEF to the RHS, even over a constant.
8847 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8848 if (TLI->isCommutativeBinOp(Opcode)) {
8849 std::swap(N1, N2);
8850 } else {
8851 switch (Opcode) {
8852 case ISD::PTRADD:
8853 case ISD::SUB:
8854 // fold op(undef, non_undef_arg2) -> undef.
8855 return N1;
8857 case ISD::UDIV:
8858 case ISD::SDIV:
8859 case ISD::UREM:
8860 case ISD::SREM:
8861 case ISD::SSUBSAT:
8862 case ISD::USUBSAT:
8863 // fold op(undef, non_undef_arg2) -> 0.
8864 return getConstant(0, DL, VT);
8865 }
8866 }
8867 }
8868
8869 // Fold a bunch of operators when the RHS is undef.
8870 if (N2.getOpcode() == ISD::UNDEF) {
8871 switch (Opcode) {
8872 case ISD::XOR:
8873 if (N1.getOpcode() == ISD::UNDEF)
8874 // Handle undef ^ undef -> 0 special case. This is a common
8875 // idiom (misuse).
8876 return getConstant(0, DL, VT);
8877 [[fallthrough]];
8878 case ISD::ADD:
8879 case ISD::PTRADD:
8880 case ISD::SUB:
8881 // fold op(arg1, undef) -> undef.
8882 return N2;
8883 case ISD::UDIV:
8884 case ISD::SDIV:
8885 case ISD::UREM:
8886 case ISD::SREM:
8887 // fold op(arg1, undef) -> poison.
8888 return getPOISON(VT);
8889 case ISD::MUL:
8890 case ISD::AND:
8891 case ISD::SSUBSAT:
8892 case ISD::USUBSAT:
8893 case ISD::UMIN:
8894 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8895 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8896 case ISD::OR:
8897 case ISD::SADDSAT:
8898 case ISD::UADDSAT:
8899 case ISD::UMAX:
8900 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8901 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8902 case ISD::SMAX:
8903 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8904 return N1.getOpcode() == ISD::UNDEF
8905 ? N2
8906 : getConstant(
8908 VT);
8909 case ISD::SMIN:
8910 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8911 return N1.getOpcode() == ISD::UNDEF
8912 ? N2
8913 : getConstant(
8915 VT);
8916 }
8917 }
8918
8919 // Perform trivial constant folding.
8920 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
8921 return SV;
8922
8923 // Memoize this node if possible.
8924 SDNode *N;
8925 SDVTList VTs = getVTList(VT);
8926 SDValue Ops[] = {N1, N2};
8927 if (VT != MVT::Glue) {
8928 SDNodeKey ID(Opcode, VTs, Ops);
8929 FoldingSetInsertToken InsertToken;
8930 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
8931 E->intersectFlagsWith(Flags);
8932 return SDValue(E, 0);
8933 }
8934
8935 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8936 N->setFlags(Flags);
8937 createOperands(N, Ops);
8938 CSEMap.insert(N, InsertToken);
8939 } else {
8940 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8941 createOperands(N, Ops);
8942 }
8943
8944 InsertNode(N);
8945 SDValue V = SDValue(N, 0);
8946 NewSDValueDbgMsg(V, "Creating new node: ", this);
8947 return V;
8948}
8949
8950SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8951 SDValue N1, SDValue N2, SDValue N3) {
8952 SDNodeFlags Flags;
8953 if (Inserter)
8954 Flags = Inserter->getFlags();
8955 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
8956}
8957
8958SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8959 SDValue N1, SDValue N2, SDValue N3,
8960 const SDNodeFlags Flags) {
8962 N2.getOpcode() != ISD::DELETED_NODE &&
8963 N3.getOpcode() != ISD::DELETED_NODE &&
8964 "Operand is DELETED_NODE!");
8965 // Perform various simplifications.
8966 switch (Opcode) {
8967 case ISD::BUILD_VECTOR: {
8968 // Attempt to simplify BUILD_VECTOR.
8969 SDValue Ops[] = {N1, N2, N3};
8970 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8971 return V;
8972 break;
8973 }
8974 case ISD::CONCAT_VECTORS: {
8975 SDValue Ops[] = {N1, N2, N3};
8976 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8977 return V;
8978 break;
8979 }
8980 case ISD::SETCC: {
8981 assert(VT.isInteger() && "SETCC result type must be an integer!");
8982 assert(N1.getValueType() == N2.getValueType() &&
8983 "SETCC operands must have the same type!");
8984 assert(VT.isVector() == N1.getValueType().isVector() &&
8985 "SETCC type should be vector iff the operand type is vector!");
8986 assert((!VT.isVector() || VT.getVectorElementCount() ==
8988 "SETCC vector element counts must match!");
8989 // Use FoldSetCC to simplify SETCC's.
8990 if (SDValue V =
8991 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
8992 return V;
8993 break;
8994 }
8995 case ISD::SELECT:
8996 case ISD::VSELECT:
8997 if (SDValue V = simplifySelect(N1, N2, N3))
8998 return V;
8999 break;
9001 llvm_unreachable("should use getVectorShuffle constructor!");
9003 if (isNullConstant(N3))
9004 return N1;
9005 break;
9007 if (isNullConstant(N3))
9008 return N2;
9009 break;
9011 assert(VT.isVector() && VT == N1.getValueType() &&
9012 "INSERT_VECTOR_ELT vector type mismatch");
9014 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9015 assert((!VT.isFloatingPoint() ||
9016 VT.getVectorElementType() == N2.getValueType()) &&
9017 "INSERT_VECTOR_ELT fp scalar type mismatch");
9018 assert((!VT.isInteger() ||
9020 "INSERT_VECTOR_ELT int scalar size mismatch");
9021
9022 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9023 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9024 // for scalable vectors where we will generate appropriate code to
9025 // deal with out-of-bounds cases correctly.
9026 if (N3C && VT.isFixedLengthVector() &&
9027 N3C->getZExtValue() >= VT.getVectorNumElements())
9028 return getUNDEF(VT);
9029
9030 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9031 if (N3.isUndef())
9032 return getUNDEF(VT);
9033
9034 // If inserting poison, just use the input vector.
9035 if (N2.getOpcode() == ISD::POISON)
9036 return N1;
9037
9038 // Inserting undef into undef/poison is still undef.
9039 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9040 return getUNDEF(VT);
9041
9042 // If the inserted element is an UNDEF, just use the input vector.
9043 // But not if skipping the insert could make the result more poisonous.
9044 if (N2.isUndef()) {
9045 if (N3C && VT.isFixedLengthVector()) {
9046 APInt EltMask =
9047 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9048 if (isGuaranteedNotToBePoison(N1, EltMask))
9049 return N1;
9050 } else if (isGuaranteedNotToBePoison(N1))
9051 return N1;
9052 }
9053 break;
9054 }
9055 case ISD::INSERT_SUBVECTOR: {
9056 // If inserting poison, just use the input vector,
9057 if (N2.getOpcode() == ISD::POISON)
9058 return N1;
9059
9060 // Inserting undef into undef/poison is still undef.
9061 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9062 return getUNDEF(VT);
9063
9064 EVT N2VT = N2.getValueType();
9065 assert(VT == N1.getValueType() &&
9066 "Dest and insert subvector source types must match!");
9067 assert(VT.isVector() && N2VT.isVector() &&
9068 "Insert subvector VTs must be vectors!");
9070 "Insert subvector VTs must have the same element type!");
9071 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9072 "Cannot insert a scalable vector into a fixed length vector!");
9073 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9075 "Insert subvector must be from smaller vector to larger vector!");
9077 "Insert subvector index must be constant");
9078 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9079 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9081 "Insert subvector overflow!");
9083 TLI->getVectorIdxWidth(getDataLayout()) &&
9084 "Constant index for INSERT_SUBVECTOR has an invalid size");
9085
9086 // Trivial insertion.
9087 if (VT == N2VT)
9088 return N2;
9089
9090 // If this is an insert of an extracted vector into an undef/poison vector,
9091 // we can just use the input to the extract. But not if skipping the
9092 // extract+insert could make the result more poisonous.
9093 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9094 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9095 if (N1.getOpcode() == ISD::POISON)
9096 return N2.getOperand(0);
9097 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9098 unsigned LoBit = N3->getAsZExtVal();
9099 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9100 APInt EltMask =
9101 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9102 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9103 return N2.getOperand(0);
9104 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9105 return N2.getOperand(0);
9106 }
9107
9108 // If the inserted subvector is UNDEF, just use the input vector.
9109 // But not if skipping the insert could make the result more poisonous.
9110 if (N2.isUndef()) {
9111 if (VT.isFixedLengthVector()) {
9112 unsigned LoBit = N3->getAsZExtVal();
9113 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9114 APInt EltMask =
9115 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9116 if (isGuaranteedNotToBePoison(N1, EltMask))
9117 return N1;
9118 } else if (isGuaranteedNotToBePoison(N1))
9119 return N1;
9120 }
9121 break;
9122 }
9123 case ISD::BITCAST:
9124 // Fold bit_convert nodes from a type to themselves.
9125 if (N1.getValueType() == VT)
9126 return N1;
9127 break;
9128 case ISD::VECTOR_COMPRESS: {
9129 [[maybe_unused]] EVT VecVT = N1.getValueType();
9130 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9131 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9132 assert(VT == VecVT && "Vector and result type don't match.");
9133 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9134 "All inputs must be vectors.");
9135 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9137 "Vector and mask must have same number of elements.");
9138
9139 if (N1.isUndef() || N2.isUndef())
9140 return N3;
9141
9142 break;
9143 }
9148 [[maybe_unused]] EVT AccVT = N1.getValueType();
9149 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9150 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9151 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9152 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9153 "node to have the same type!");
9154 assert(VT.isVector() && VT == AccVT &&
9155 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9156 "the same type as its result!");
9158 AccVT.getVectorElementCount()) &&
9159 "Expected the element count of the second and third operands of the "
9160 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9161 "element count of the first operand and the result!");
9163 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9164 "node to have an element type which is the same as or smaller than "
9165 "the element type of the first operand and result!");
9166 break;
9167 }
9168 }
9169
9170 // Perform trivial constant folding for arithmetic operators.
9171 switch (Opcode) {
9175 case ISD::FMA:
9176 case ISD::FMAD:
9177 case ISD::SETCC:
9178 case ISD::FSHL:
9179 case ISD::FSHR:
9180 if (SDValue SV =
9181 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9182 return SV;
9183 break;
9184 }
9185
9186 // Memoize node if it doesn't produce a glue result.
9187 SDNode *N;
9188 SDVTList VTs = getVTList(VT);
9189 SDValue Ops[] = {N1, N2, N3};
9190 if (VT != MVT::Glue) {
9191 SDNodeKey ID(Opcode, VTs, Ops);
9192 FoldingSetInsertToken InsertToken;
9193 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9194 E->intersectFlagsWith(Flags);
9195 return SDValue(E, 0);
9196 }
9197
9198 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9199 N->setFlags(Flags);
9200 createOperands(N, Ops);
9201 CSEMap.insert(N, InsertToken);
9202 } else {
9203 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9204 createOperands(N, Ops);
9205 }
9206
9207 InsertNode(N);
9208 SDValue V = SDValue(N, 0);
9209 NewSDValueDbgMsg(V, "Creating new node: ", this);
9210 return V;
9211}
9212
9213SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9214 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9215 const SDNodeFlags Flags) {
9216 SDValue Ops[] = { N1, N2, N3, N4 };
9217 return getNode(Opcode, DL, VT, Ops, Flags);
9218}
9219
9220SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9221 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9222 SDNodeFlags Flags;
9223 if (Inserter)
9224 Flags = Inserter->getFlags();
9225 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9226}
9227
9228SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9229 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9230 SDValue N5, const SDNodeFlags Flags) {
9231 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9232 return getNode(Opcode, DL, VT, Ops, Flags);
9233}
9234
9235SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9236 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9237 SDValue N5) {
9238 SDNodeFlags Flags;
9239 if (Inserter)
9240 Flags = Inserter->getFlags();
9241 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9242}
9243
9244/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9245/// the incoming stack arguments to be loaded from the stack.
9247 SmallVector<SDValue, 8> ArgChains;
9248
9249 // Include the original chain at the beginning of the list. When this is
9250 // used by target LowerCall hooks, this helps legalize find the
9251 // CALLSEQ_BEGIN node.
9252 ArgChains.push_back(Chain);
9253
9254 // Add a chain value for each stack argument.
9255 for (SDNode *U : getEntryNode().getNode()->users())
9256 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9257 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9258 if (FI->getIndex() < 0)
9259 ArgChains.push_back(SDValue(L, 1));
9260
9261 // Build a tokenfactor for all the chains.
9262 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9263}
9264
9265/// getMemsetValue - Vectorized representation of the memset value
9266/// operand.
9268 const SDLoc &dl) {
9269 assert(!Value.isUndef());
9270
9271 unsigned NumBits = VT.getScalarSizeInBits();
9273 assert(C->getAPIntValue().getBitWidth() == 8);
9274 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9275 if (VT.isInteger()) {
9276 bool IsOpaque = VT.getSizeInBits() > 64 ||
9277 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9278 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9279 }
9280 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9281 }
9282
9283 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9284 EVT IntVT = VT.getScalarType();
9285 if (!IntVT.isInteger())
9286 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9287
9288 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9289 if (NumBits > 8) {
9290 // Use a multiplication with 0x010101... to extend the input to the
9291 // required length.
9292 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9293 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9294 DAG.getConstant(Magic, dl, IntVT));
9295 }
9296
9297 if (VT != Value.getValueType() && !VT.isInteger())
9298 Value = DAG.getBitcast(VT.getScalarType(), Value);
9299 if (VT != Value.getValueType())
9300 Value = DAG.getSplatBuildVector(VT, dl, Value);
9301
9302 return Value;
9303}
9304
9305/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9306/// used when a memcpy is turned into a memset when the source is a constant
9307/// string ptr.
9309 const TargetLowering &TLI,
9310 const ConstantDataArraySlice &Slice) {
9311 // Handle vector with all elements zero.
9312 if (Slice.Array == nullptr) {
9313 if (VT.isInteger())
9314 return DAG.getConstant(0, dl, VT);
9315 return DAG.getNode(ISD::BITCAST, dl, VT,
9316 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9317 }
9318
9319 assert(!VT.isVector() && "Can't handle vector type here!");
9320 unsigned NumVTBits = VT.getSizeInBits();
9321 unsigned NumVTBytes = NumVTBits / 8;
9322 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9323
9324 APInt Val(NumVTBits, 0);
9325 if (DAG.getDataLayout().isLittleEndian()) {
9326 for (unsigned i = 0; i != NumBytes; ++i)
9327 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9328 } else {
9329 for (unsigned i = 0; i != NumBytes; ++i)
9330 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9331 }
9332
9333 // If the "cost" of materializing the integer immediate is less than the cost
9334 // of a load, then it is cost effective to turn the load into the immediate.
9335 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9336 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9337 return DAG.getConstant(Val, dl, VT);
9338 return SDValue();
9339}
9340
9342 const SDLoc &DL,
9343 const SDNodeFlags Flags) {
9344 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9345 return getMemBasePlusOffset(Base, Index, DL, Flags);
9346}
9347
9349 const SDLoc &DL,
9350 const SDNodeFlags Flags) {
9351 assert(Offset.getValueType().isInteger());
9352 EVT BasePtrVT = Ptr.getValueType();
9353 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9354 BasePtrVT))
9355 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9356 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9357 SDNodeFlags AddFlags = Flags;
9358 AddFlags.setInBounds(false);
9359 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9360}
9361
9362/// Returns true if memcpy source is constant data.
9364 uint64_t SrcDelta = 0;
9365 GlobalAddressSDNode *G = nullptr;
9366 if (Src.getOpcode() == ISD::GlobalAddress)
9368 else if (Src->isAnyAdd() &&
9369 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9370 Src.getOperand(1).getOpcode() == ISD::Constant) {
9371 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9372 SrcDelta = Src.getConstantOperandVal(1);
9373 }
9374 if (!G)
9375 return false;
9376
9377 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9378 SrcDelta + G->getOffset());
9379}
9380
9382 SelectionDAG &DAG) {
9383 // On Darwin, -Os means optimize for size without hurting performance, so
9384 // only really optimize for size when -Oz (MinSize) is used.
9386 return MF.getFunction().hasMinSize();
9387 return DAG.shouldOptForSize();
9388}
9389
9391 SmallVector<SDValue, 32> &OutChains, unsigned From,
9392 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9393 SmallVector<SDValue, 16> &OutStoreChains) {
9394 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9395 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9396 SmallVector<SDValue, 16> GluedLoadChains;
9397 for (unsigned i = From; i < To; ++i) {
9398 OutChains.push_back(OutLoadChains[i]);
9399 GluedLoadChains.push_back(OutLoadChains[i]);
9400 }
9401
9402 // Chain for all loads.
9403 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9404 GluedLoadChains);
9405
9406 for (unsigned i = From; i < To; ++i) {
9407 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9408 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9409 ST->getBasePtr(), ST->getMemoryVT(),
9410 ST->getMemOperand());
9411 OutChains.push_back(NewStore);
9412 }
9413}
9414
9415static SDValue
9417 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9418 Align SrcAlign, bool isVol, bool AlwaysInline,
9419 MachinePointerInfo DstPtrInfo,
9420 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9421 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9422 const MDNode *SrcMemCacheHint) {
9423 // Turn a memcpy of undef to nop.
9424 // FIXME: We need to honor volatile even is Src is undef.
9425 if (Src.isUndef())
9426 return Chain;
9427
9428 // Expand memcpy to a series of load and store ops if the size operand falls
9429 // below a certain threshold.
9430 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9431 // rather than maybe a humongous number of loads and stores.
9432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9433 const DataLayout &DL = DAG.getDataLayout();
9434 LLVMContext &C = *DAG.getContext();
9435 std::vector<EVT> MemOps;
9436 bool DstAlignCanChange = false;
9438 MachineFrameInfo &MFI = MF.getFrameInfo();
9439 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9441 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9442 DstAlignCanChange = true;
9443 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9445 // If marked as volatile, perform a copy even when marked as constant.
9446 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9447 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9448 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9449 const MemOp Op = isZeroConstant
9450 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9451 /*IsZeroMemset*/ true, isVol)
9452 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9453 SrcAlign, isVol, CopyFromConstant);
9454 if (!TLI.findOptimalMemOpLowering(
9455 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9456 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9457 return SDValue();
9458
9459 if (DstAlignCanChange) {
9460 Type *Ty = MemOps[0].getTypeForEVT(C);
9461 Align NewDstAlign = DL.getABITypeAlign(Ty);
9462
9463 // Don't promote to an alignment that would require dynamic stack
9464 // realignment which may conflict with optimizations such as tail call
9465 // optimization.
9467 if (!TRI->hasStackRealignment(MF))
9468 if (MaybeAlign StackAlign = DL.getStackAlignment())
9469 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9470
9471 if (NewDstAlign > DstAlign) {
9472 // Give the stack frame object a larger alignment if needed.
9473 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9474 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9475 DstAlign = NewDstAlign;
9476 }
9477 }
9478
9479 // Prepare AAInfo for loads/stores after lowering this memcpy.
9480 AAMDNodes NewAAInfo = AAInfo;
9481 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9482
9483 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9484 bool isConstant =
9485 BatchAA && SrcVal &&
9486 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9487
9488 MachineMemOperand::Flags MMOFlags =
9490 SmallVector<SDValue, 16> OutLoadChains;
9491 SmallVector<SDValue, 16> OutStoreChains;
9492 SmallVector<SDValue, 32> OutChains;
9493 unsigned NumMemOps = MemOps.size();
9494 uint64_t SrcOff = 0, DstOff = 0;
9495 for (unsigned i = 0; i != NumMemOps; ++i) {
9496 EVT VT = MemOps[i];
9497 unsigned VTSize = VT.getSizeInBits() / 8;
9499
9500 if (VTSize > Size) {
9501 // Issuing an unaligned load / store pair that overlaps with the previous
9502 // pair. Adjust the offset accordingly.
9503 assert(i == NumMemOps-1 && i != 0);
9504 SrcOff -= VTSize - Size;
9505 DstOff -= VTSize - Size;
9506 }
9507
9508 if (CopyFromConstant &&
9509 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9510 // It's unlikely a store of a vector immediate can be done in a single
9511 // instruction. It would require a load from a constantpool first.
9512 // We only handle zero vectors here.
9513 // FIXME: Handle other cases where store of vector immediate is done in
9514 // a single instruction.
9515 ConstantDataArraySlice SubSlice;
9516 if (SrcOff < Slice.Length) {
9517 SubSlice = Slice;
9518 SubSlice.move(SrcOff);
9519 } else {
9520 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9521 SubSlice.Array = nullptr;
9522 SubSlice.Offset = 0;
9523 SubSlice.Length = VTSize;
9524 }
9525 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9526 if (Value.getNode()) {
9527 Store = DAG.getStore(
9528 Chain, dl, Value,
9529 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9530 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9531 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9532 OutChains.push_back(Store);
9533 }
9534 }
9535
9536 if (!Store.getNode()) {
9537 // The type might not be legal for the target. This should only happen
9538 // if the type is smaller than a legal type, as on PPC, so the right
9539 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9540 // to Load/Store if NVT==VT.
9541 // FIXME does the case above also need this?
9542 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9543 assert(NVT.bitsGE(VT));
9544
9545 bool isDereferenceable =
9546 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9547 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9548 if (isDereferenceable)
9550 if (isConstant)
9551 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9552
9553 Value = DAG.getExtLoad(
9554 ISD::EXTLOAD, dl, NVT, Chain,
9555 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9556 SrcPtrInfo.getWithOffset(SrcOff), VT,
9557 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9558 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9559 OutLoadChains.push_back(Value.getValue(1));
9560
9561 Store = DAG.getTruncStore(
9562 Chain, dl, Value,
9563 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9564 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9565 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9566 OutStoreChains.push_back(Store);
9567 }
9568 SrcOff += VTSize;
9569 DstOff += VTSize;
9570 Size -= VTSize;
9571 }
9572
9573 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9575 unsigned NumLdStInMemcpy = OutStoreChains.size();
9576
9577 if (NumLdStInMemcpy) {
9578 // It may be that memcpy might be converted to memset if it's memcpy
9579 // of constants. In such a case, we won't have loads and stores, but
9580 // just stores. In the absence of loads, there is nothing to gang up.
9581 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9582 // If target does not care, just leave as it.
9583 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9584 OutChains.push_back(OutLoadChains[i]);
9585 OutChains.push_back(OutStoreChains[i]);
9586 }
9587 } else {
9588 // Ld/St less than/equal limit set by target.
9589 if (NumLdStInMemcpy <= GluedLdStLimit) {
9590 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9591 NumLdStInMemcpy, OutLoadChains,
9592 OutStoreChains);
9593 } else {
9594 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9595 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9596 unsigned GlueIter = 0;
9597
9598 // Residual ld/st.
9599 if (RemainingLdStInMemcpy) {
9601 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9602 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9603 }
9604
9605 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9606 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9607 GlueIter - GluedLdStLimit;
9608 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9609 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9610 OutLoadChains, OutStoreChains);
9611 GlueIter += GluedLdStLimit;
9612 }
9613 }
9614 }
9615 }
9616 return DAG.getTokenFactor(dl, OutChains);
9617}
9618
9620 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9621 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9622 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9623 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9624 // Turn a memmove of undef to nop.
9625 // FIXME: We need to honor volatile even is Src is undef.
9626 if (Src.isUndef())
9627 return Chain;
9628
9629 // Expand memmove to a series of load and store ops if the size operand falls
9630 // below a certain threshold.
9631 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9632 const DataLayout &DL = DAG.getDataLayout();
9633 LLVMContext &C = *DAG.getContext();
9634 std::vector<EVT> MemOps;
9635 bool DstAlignCanChange = false;
9637 MachineFrameInfo &MFI = MF.getFrameInfo();
9638 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9640 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9641 DstAlignCanChange = true;
9642 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9643 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9644 if (!TLI.findOptimalMemOpLowering(
9645 C, MemOps, Limit,
9646 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9647 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9648 MF.getFunction().getAttributes(), nullptr))
9649 return SDValue();
9650
9651 if (DstAlignCanChange) {
9652 Type *Ty = MemOps[0].getTypeForEVT(C);
9653 Align NewDstAlign = DL.getABITypeAlign(Ty);
9654
9655 // Don't promote to an alignment that would require dynamic stack
9656 // realignment which may conflict with optimizations such as tail call
9657 // optimization.
9659 if (!TRI->hasStackRealignment(MF))
9660 if (MaybeAlign StackAlign = DL.getStackAlignment())
9661 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9662
9663 if (NewDstAlign > DstAlign) {
9664 // Give the stack frame object a larger alignment if needed.
9665 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9666 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9667 DstAlign = NewDstAlign;
9668 }
9669 }
9670
9671 // Prepare AAInfo for loads/stores after lowering this memmove.
9672 AAMDNodes NewAAInfo = AAInfo;
9673 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9674
9675 MachineMemOperand::Flags MMOFlags =
9677 uint64_t SrcOff = 0;
9678 SmallVector<SDValue, 8> LoadValues;
9679 SmallVector<SDValue, 8> LoadChains;
9680 SmallVector<SDValue, 8> OutChains;
9681 unsigned NumMemOps = MemOps.size();
9682 for (unsigned i = 0; i < NumMemOps; i++) {
9683 EVT VT = MemOps[i];
9684 unsigned VTSize = VT.getSizeInBits() / 8;
9685 SDValue Value;
9686 bool IsOverlapping = false;
9687
9688 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9689 // Issuing an unaligned load / store pair that overlaps with the previous
9690 // pair. Adjust the offset accordingly.
9691 SrcOff = Size - VTSize;
9692 IsOverlapping = true;
9693 }
9694
9695 // Calculate the actual alignment at the current offset. The alignment at
9696 // SrcOff may be lower than the base alignment, especially when using
9697 // overlapping loads.
9698 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9699 if (IsOverlapping) {
9700 // Verify that the target allows misaligned memory accesses at the
9701 // adjusted offset when using overlapping loads.
9702 unsigned Fast;
9703 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9704 SrcAlignAtOffset, MMOFlags,
9705 &Fast) ||
9706 !Fast) {
9707 // This should have been caught by findOptimalMemOpLowering, but verify
9708 // here for safety.
9709 return SDValue();
9710 }
9711 }
9712
9713 bool isDereferenceable =
9714 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9715 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9716 if (isDereferenceable)
9718 Value =
9719 DAG.getLoad(VT, dl, Chain,
9720 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9721 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9722 SrcMMOFlags, NewAAInfo);
9723 LoadValues.push_back(Value);
9724 LoadChains.push_back(Value.getValue(1));
9725 SrcOff += VTSize;
9726 }
9727 Chain = DAG.getTokenFactor(dl, LoadChains);
9728 OutChains.clear();
9729 uint64_t DstOff = 0;
9730 for (unsigned i = 0; i < NumMemOps; i++) {
9731 EVT VT = MemOps[i];
9732 unsigned VTSize = VT.getSizeInBits() / 8;
9733 SDValue Store;
9734 bool IsOverlapping = false;
9735
9736 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9737 // Issuing an unaligned load / store pair that overlaps with the previous
9738 // pair. Adjust the offset accordingly.
9739 DstOff = Size - VTSize;
9740 IsOverlapping = true;
9741 }
9742
9743 // Calculate the actual alignment at the current offset. The alignment at
9744 // DstOff may be lower than the base alignment, especially when using
9745 // overlapping stores.
9746 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9747 if (IsOverlapping) {
9748 // Verify that the target allows misaligned memory accesses at the
9749 // adjusted offset when using overlapping stores.
9750 unsigned Fast;
9751 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9752 DstAlignAtOffset, MMOFlags,
9753 &Fast) ||
9754 !Fast) {
9755 // This should have been caught by findOptimalMemOpLowering, but verify
9756 // here for safety.
9757 return SDValue();
9758 }
9759 }
9760 Store = DAG.getStore(
9761 Chain, dl, LoadValues[i],
9762 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9763 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9764 NewAAInfo);
9765 OutChains.push_back(Store);
9766 DstOff += VTSize;
9767 }
9768
9769 return DAG.getTokenFactor(dl, OutChains);
9770}
9771
9772/// Lower the call to 'memset' intrinsic function into a series of store
9773/// operations.
9774///
9775/// \param DAG Selection DAG where lowered code is placed.
9776/// \param dl Link to corresponding IR location.
9777/// \param Chain Control flow dependency.
9778/// \param Dst Pointer to destination memory location.
9779/// \param Src Value of byte to write into the memory.
9780/// \param Size Number of bytes to write.
9781/// \param Alignment Alignment of the destination in bytes.
9782/// \param isVol True if destination is volatile.
9783/// \param AlwaysInline Makes sure no function call is generated.
9784/// \param DstPtrInfo IR information on the memory pointer.
9785/// \returns New head in the control flow, if lowering was successful, empty
9786/// SDValue otherwise.
9787///
9788/// The function tries to replace 'llvm.memset' intrinsic with several store
9789/// operations and value calculation code. This is usually profitable for small
9790/// memory size or when the semantic requires inlining.
9792 SDValue Chain, SDValue Dst, SDValue Src,
9793 uint64_t Size, Align Alignment, bool isVol,
9794 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9795 const AAMDNodes &AAInfo) {
9796 // Turn a memset of undef to nop.
9797 // FIXME: We need to honor volatile even is Src is undef.
9798 if (Src.isUndef())
9799 return Chain;
9800
9801 // Expand memset to a series of load/store ops if the size operand
9802 // falls below a certain threshold.
9803 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9804 std::vector<EVT> MemOps;
9805 bool DstAlignCanChange = false;
9806 LLVMContext &C = *DAG.getContext();
9808 MachineFrameInfo &MFI = MF.getFrameInfo();
9809 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9811 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9812 DstAlignCanChange = true;
9813 bool IsZeroVal = isNullConstant(Src);
9814 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9815
9816 EVT LargestVT;
9817 if (!TLI.findOptimalMemOpLowering(
9818 C, MemOps, Limit,
9819 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9820 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
9821 &LargestVT))
9822 return SDValue();
9823
9824 if (DstAlignCanChange) {
9825 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9826 const DataLayout &DL = DAG.getDataLayout();
9827 Align NewAlign = DL.getABITypeAlign(Ty);
9828
9829 // Don't promote to an alignment that would require dynamic stack
9830 // realignment which may conflict with optimizations such as tail call
9831 // optimization.
9833 if (!TRI->hasStackRealignment(MF))
9834 if (MaybeAlign StackAlign = DL.getStackAlignment())
9835 NewAlign = std::min(NewAlign, *StackAlign);
9836
9837 if (NewAlign > Alignment) {
9838 // Give the stack frame object a larger alignment if needed.
9839 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9840 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9841 Alignment = NewAlign;
9842 }
9843 }
9844
9845 SmallVector<SDValue, 8> OutChains;
9846 uint64_t DstOff = 0;
9847 unsigned NumMemOps = MemOps.size();
9848
9849 // Find the largest store and generate the bit pattern for it.
9850 // If target didn't set LargestVT, compute it from MemOps.
9851 if (!LargestVT.isSimple()) {
9852 LargestVT = MemOps[0];
9853 for (unsigned i = 1; i < NumMemOps; i++)
9854 if (MemOps[i].bitsGT(LargestVT))
9855 LargestVT = MemOps[i];
9856 }
9857 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9858
9859 // Prepare AAInfo for loads/stores after lowering this memset.
9860 AAMDNodes NewAAInfo = AAInfo;
9861 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9862
9863 for (unsigned i = 0; i < NumMemOps; i++) {
9864 EVT VT = MemOps[i];
9865 unsigned VTSize = VT.getSizeInBits() / 8;
9866 // The target should specify store types that exactly cover the memset size
9867 // (with the last store potentially being oversized for overlapping stores).
9868 assert(Size > 0 && "Target specified more stores than needed in "
9869 "findOptimalMemOpLowering");
9870 if (VTSize > Size) {
9871 // Issuing an unaligned load / store pair that overlaps with the previous
9872 // pair. Adjust the offset accordingly.
9873 assert(i == NumMemOps-1 && i != 0);
9874 DstOff -= VTSize - Size;
9875 }
9876
9877 // If this store is smaller than the largest store see whether we can get
9878 // the smaller value for free with a truncate or extract vector element and
9879 // then store.
9880 SDValue Value = MemSetValue;
9881 if (VT.bitsLT(LargestVT)) {
9882 unsigned Index;
9883 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9884 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9885 if (!LargestVT.isVector() && !VT.isVector() &&
9886 TLI.isTruncateFree(LargestVT, VT))
9887 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9888 else if (LargestVT.isVector() && !VT.isVector() &&
9890 LargestVT.getTypeForEVT(*DAG.getContext()),
9891 VT.getSizeInBits(), Index) &&
9892 TLI.isTypeLegal(SVT) &&
9893 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9894 // Target which can combine store(extractelement VectorTy, Idx) can get
9895 // the smaller value for free.
9896 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9897 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9898 } else
9899 Value = getMemsetValue(Src, VT, DAG, dl);
9900 }
9901 assert(Value.getValueType() == VT && "Value with wrong type.");
9902 SDValue Store = DAG.getStore(
9903 Chain, dl, Value,
9904 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9905 DstPtrInfo.getWithOffset(DstOff), Alignment,
9907 NewAAInfo);
9908 OutChains.push_back(Store);
9909 DstOff += VT.getSizeInBits() / 8;
9910 // For oversized overlapping stores, only subtract the remaining bytes.
9911 // For normal stores, subtract the full store size.
9912 if (VTSize > Size) {
9913 Size = 0;
9914 } else {
9915 Size -= VTSize;
9916 }
9917 }
9918
9919 // After processing all stores, Size should be exactly 0. Any remaining bytes
9920 // indicate a bug in the target's findOptimalMemOpLowering implementation.
9921 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
9922 "stores that exactly cover the memset size");
9923
9924 return DAG.getTokenFactor(dl, OutChains);
9925}
9926
9928 unsigned AS) {
9929 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
9930 // pointer operands can be losslessly bitcasted to pointers of address space 0
9931 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
9932 report_fatal_error("cannot lower memory intrinsic in address space " +
9933 Twine(AS));
9934 }
9935}
9936
9938 const SelectionDAG *SelDAG,
9939 bool AllowReturnsFirstArg) {
9940 if (!CI || !CI->isTailCall())
9941 return false;
9942 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
9943 // helper symbol we lower to.
9944 return isInTailCallPosition(*CI, SelDAG->getTarget(),
9945 AllowReturnsFirstArg &&
9947}
9948
9949static std::pair<SDValue, SDValue>
9952 const CallInst *CI, RTLIB::Libcall Call,
9953 SelectionDAG *DAG, const TargetLowering *TLI) {
9954 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
9955
9956 if (LCImpl == RTLIB::Unsupported)
9957 return {};
9958
9960 bool IsTailCall =
9961 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
9962 // Lowering doesn't support tail calling inside a function with
9963 // a swifterror argument yet.
9964 !DAG->hasSwiftErrorArg();
9965 SDValue Callee =
9966 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
9967
9968 CLI.setDebugLoc(dl)
9969 .setChain(Chain)
9971 CI->getType(), Callee, std::move(Args))
9972 .setTailCall(IsTailCall);
9973
9974 return TLI->LowerCallTo(CLI);
9975}
9976
9977std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
9978 const SDLoc &dl, SDValue S1,
9979 SDValue S2,
9980 const CallInst *CI) {
9982 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
9983 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
9984 RTLIB::STRCMP, this, TLI);
9985}
9986
9987std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
9988 const SDLoc &dl, SDValue S1,
9989 SDValue S2,
9990 const CallInst *CI) {
9992 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
9993 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
9994 RTLIB::STRSTR, this, TLI);
9995}
9996
9997std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
9998 const SDLoc &dl,
9999 SDValue Dst, SDValue Src,
10001 const CallInst *CI) {
10003
10005 {Dst, PT},
10006 {Src, PT},
10009 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10010 RTLIB::MEMCCPY, this, TLI);
10011}
10012
10013std::pair<SDValue, SDValue>
10015 SDValue Mem1, SDValue Size, const CallInst *CI) {
10018 {Mem0, PT},
10019 {Mem1, PT},
10021 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10022 RTLIB::MEMCMP, this, TLI);
10023}
10024
10025std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10026 const SDLoc &dl,
10027 SDValue Dst, SDValue Src,
10028 const CallInst *CI) {
10030 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10031 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10032 RTLIB::STRCPY, this, TLI);
10033}
10034
10035std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10036 const SDLoc &dl,
10037 SDValue Src,
10038 const CallInst *CI) {
10039 // Emit a library call.
10042 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10043 RTLIB::STRLEN, this, TLI);
10044}
10045
10047 return TLI->supportSwiftError() &&
10048 MF->getFunction().getAttributes().hasAttrSomewhere(
10049 Attribute::SwiftError);
10050}
10051
10053 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10054 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10055 const CallInst *CI, std::optional<bool> OverrideTailCall,
10056 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10057 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10058 // Check to see if we should lower the memcpy to loads and stores first.
10059 // For cases within the target-specified limits, this is the best choice.
10060 const MDNode *DstMemCacheHint =
10061 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10062 const MDNode *SrcMemCacheHint =
10063 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10064
10066 if (ConstantSize) {
10067 // Memcpy with size zero? Just return the original chain.
10068 if (ConstantSize->isZero())
10069 return Chain;
10070
10072 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10073 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10074 DstMemCacheHint, SrcMemCacheHint);
10075 if (Result.getNode())
10076 return Result;
10077 }
10078
10079 // Then check to see if we should lower the memcpy with target-specific
10080 // code. If the target chooses to do this, this is the next best.
10081 if (TSI) {
10082 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10083 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10084 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10085 if (Result.getNode())
10086 return Result;
10087 }
10088
10089 // If we really need inline code and the target declined to provide it,
10090 // use a (potentially long) sequence of loads and stores.
10091 if (AlwaysInline) {
10092 assert(ConstantSize && "AlwaysInline requires a constant size!");
10094 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10095 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10096 DstMemCacheHint, SrcMemCacheHint);
10097 }
10098
10101
10102 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10103 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10104 // respect volatile, so they may do things like read or write memory
10105 // beyond the given memory regions. But fixing this isn't easy, and most
10106 // people don't care.
10107
10108 // Emit a library call.
10111 Args.emplace_back(Dst, PtrTy);
10112 Args.emplace_back(Src, PtrTy);
10113 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10114 // FIXME: pass in SDLoc
10116 bool IsTailCall = false;
10117 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10118
10119 if (OverrideTailCall.has_value()) {
10120 IsTailCall = *OverrideTailCall;
10121 } else {
10122 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10123 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10124 }
10125 // Lowering doesn't support tail calling inside a function with a
10126 // swifterror argument yet.
10127 IsTailCall &= !hasSwiftErrorArg();
10128
10129 CLI.setDebugLoc(dl)
10130 .setChain(Chain)
10131 .setLibCallee(
10132 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10133 Dst.getValueType().getTypeForEVT(*getContext()),
10134 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10135 std::move(Args))
10137 .setTailCall(IsTailCall);
10138
10139 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10140 return CallResult.second;
10141}
10142
10144 SDValue Dst, SDValue Src, SDValue Size,
10145 Type *SizeTy, unsigned ElemSz,
10146 bool isTailCall,
10147 MachinePointerInfo DstPtrInfo,
10148 MachinePointerInfo SrcPtrInfo) {
10149 // Lowering doesn't support tail calling inside a function with a
10150 // swifterror argument yet.
10151 isTailCall &= !hasSwiftErrorArg();
10152
10153 // Emit a library call.
10156 Args.emplace_back(Dst, ArgTy);
10157 Args.emplace_back(Src, ArgTy);
10158 Args.emplace_back(Size, SizeTy);
10159
10160 RTLIB::Libcall LibraryCall =
10162 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10163 if (LibcallImpl == RTLIB::Unsupported)
10164 report_fatal_error("Unsupported element size");
10165
10167 CLI.setDebugLoc(dl)
10168 .setChain(Chain)
10169 .setLibCallee(
10170 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10172 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10173 std::move(Args))
10175 .setTailCall(isTailCall);
10176
10177 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10178 return CallResult.second;
10179}
10180
10182 SDValue Src, SDValue Size, Align DstAlign,
10183 Align SrcAlign, bool isVol, const CallInst *CI,
10184 std::optional<bool> OverrideTailCall,
10185 MachinePointerInfo DstPtrInfo,
10186 MachinePointerInfo SrcPtrInfo,
10187 const AAMDNodes &AAInfo,
10188 BatchAAResults *BatchAA) {
10189 // Check to see if we should lower the memmove to loads and stores first.
10190 // For cases within the target-specified limits, this is the best choice.
10192 if (ConstantSize) {
10193 // Memmove with size zero? Just return the original chain.
10194 if (ConstantSize->isZero())
10195 return Chain;
10196
10198 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10199 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10200 if (Result.getNode())
10201 return Result;
10202 }
10203
10204 // Then check to see if we should lower the memmove with target-specific
10205 // code. If the target chooses to do this, this is the next best.
10206 if (TSI) {
10207 SDValue Result = TSI->EmitTargetCodeForMemmove(
10208 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10209 SrcPtrInfo);
10210 if (Result.getNode())
10211 return Result;
10212 }
10213
10216
10217 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10218 // not be safe. See memcpy above for more details.
10219
10220 // Emit a library call.
10223 Args.emplace_back(Dst, PtrTy);
10224 Args.emplace_back(Src, PtrTy);
10225 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10226 // FIXME: pass in SDLoc
10228
10229 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10230
10231 bool IsTailCall = false;
10232 if (OverrideTailCall.has_value()) {
10233 IsTailCall = *OverrideTailCall;
10234 } else {
10235 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10236 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10237 }
10238 // Lowering doesn't support tail calling inside a function with a
10239 // swifterror argument yet.
10240 IsTailCall &= !hasSwiftErrorArg();
10241
10242 CLI.setDebugLoc(dl)
10243 .setChain(Chain)
10244 .setLibCallee(
10245 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10246 Dst.getValueType().getTypeForEVT(*getContext()),
10247 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10248 std::move(Args))
10250 .setTailCall(IsTailCall);
10251
10252 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10253 return CallResult.second;
10254}
10255
10257 SDValue Dst, SDValue Src, SDValue Size,
10258 Type *SizeTy, unsigned ElemSz,
10259 bool isTailCall,
10260 MachinePointerInfo DstPtrInfo,
10261 MachinePointerInfo SrcPtrInfo) {
10262 // Lowering doesn't support tail calling inside a function with a
10263 // swifterror argument yet.
10264 isTailCall &= !hasSwiftErrorArg();
10265
10266 // Emit a library call.
10269 Args.emplace_back(Dst, IntPtrTy);
10270 Args.emplace_back(Src, IntPtrTy);
10271 Args.emplace_back(Size, SizeTy);
10272
10273 RTLIB::Libcall LibraryCall =
10275 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10276 if (LibcallImpl == RTLIB::Unsupported)
10277 report_fatal_error("Unsupported element size");
10278
10280 CLI.setDebugLoc(dl)
10281 .setChain(Chain)
10282 .setLibCallee(
10283 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10285 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10286 std::move(Args))
10288 .setTailCall(isTailCall);
10289
10290 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10291 return CallResult.second;
10292}
10293
10295 SDValue Src, SDValue Size, Align Alignment,
10296 bool isVol, bool AlwaysInline,
10297 const CallInst *CI,
10298 MachinePointerInfo DstPtrInfo,
10299 const AAMDNodes &AAInfo) {
10300 // Check to see if we should lower the memset to stores first.
10301 // For cases within the target-specified limits, this is the best choice.
10303 if (ConstantSize) {
10304 // Memset with size zero? Just return the original chain.
10305 if (ConstantSize->isZero())
10306 return Chain;
10307
10308 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10309 ConstantSize->getZExtValue(), Alignment,
10310 isVol, false, DstPtrInfo, AAInfo);
10311
10312 if (Result.getNode())
10313 return Result;
10314 }
10315
10316 // Then check to see if we should lower the memset with target-specific
10317 // code. If the target chooses to do this, this is the next best.
10318 if (TSI) {
10319 SDValue Result = TSI->EmitTargetCodeForMemset(
10320 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10321 if (Result.getNode())
10322 return Result;
10323 }
10324
10325 // If we really need inline code and the target declined to provide it,
10326 // use a (potentially long) sequence of loads and stores.
10327 if (AlwaysInline) {
10328 assert(ConstantSize && "AlwaysInline requires a constant size!");
10329 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10330 ConstantSize->getZExtValue(), Alignment,
10331 isVol, true, DstPtrInfo, AAInfo);
10332 assert(Result &&
10333 "getMemsetStores must return a valid sequence when AlwaysInline");
10334 return Result;
10335 }
10336
10338
10339 // Emit a library call.
10340 auto &Ctx = *getContext();
10341 const auto& DL = getDataLayout();
10342
10344 // FIXME: pass in SDLoc
10345 CLI.setDebugLoc(dl).setChain(Chain);
10346
10347 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10348 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10349
10350 // If zeroing out and bzero is present, use it.
10351 if (UseBZero) {
10353 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10354 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10355 CLI.setLibCallee(
10356 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10357 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10358 } else {
10359 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10360
10362 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10363 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
10364 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10365 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10366 Dst.getValueType().getTypeForEVT(Ctx),
10367 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10368 std::move(Args));
10369 }
10370
10371 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10372 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10373
10374 // If we're going to use bzero, make sure not to tail call unless the
10375 // subsequent return doesn't need a value, as bzero doesn't return the first
10376 // arg unlike memset.
10377 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10378 bool IsTailCall = CI && CI->isTailCall() &&
10380 ReturnsFirstArg && LowersToMemset) &&
10381 // Lowering doesn't support tail calling inside a function
10382 // with a swifterror argument yet.
10384 CLI.setDiscardResult().setTailCall(IsTailCall);
10385
10386 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10387 return CallResult.second;
10388}
10389
10392 Type *SizeTy, unsigned ElemSz,
10393 bool isTailCall,
10394 MachinePointerInfo DstPtrInfo) {
10395 // Lowering doesn't support tail calling inside a function with a
10396 // swifterror argument yet.
10397 isTailCall &= !hasSwiftErrorArg();
10398
10399 // Emit a library call.
10401 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10402 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
10403 Args.emplace_back(Size, SizeTy);
10404
10405 RTLIB::Libcall LibraryCall =
10407 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10408 if (LibcallImpl == RTLIB::Unsupported)
10409 report_fatal_error("Unsupported element size");
10410
10412 CLI.setDebugLoc(dl)
10413 .setChain(Chain)
10414 .setLibCallee(
10415 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10417 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10418 std::move(Args))
10420 .setTailCall(isTailCall);
10421
10422 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10423 return CallResult.second;
10424}
10425
10426SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10428 MachineMemOperand *MMO,
10429 ISD::LoadExtType ExtType) {
10430 SDNodeKey ID(Opcode, VTList, Ops);
10431 ID.AddInteger(MemVT.getRawBits());
10432 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10433 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10434 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10435 ID.AddInteger(MMO->getFlags());
10436 FoldingSetInsertToken InsertToken;
10437 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10438 E->refineAlignment(MMO);
10439 E->refineMMOMetadata(MMO);
10440 return SDValue(E, 0);
10441 }
10442
10443 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10444 VTList, MemVT, MMO, ExtType);
10445 createOperands(N, Ops);
10446
10447 CSEMap.insert(N, InsertToken);
10448 InsertNode(N);
10449 SDValue V(N, 0);
10450 NewSDValueDbgMsg(V, "Creating new node: ", this);
10451 return V;
10452}
10453
10455 EVT MemVT, SDVTList VTs, SDValue Chain,
10456 SDValue Ptr, SDValue Cmp, SDValue Swp,
10457 MachineMemOperand *MMO) {
10458 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10460 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10461
10462 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10463 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10464}
10465
10466SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10467 SDValue Chain, SDValue Ptr, SDValue Val,
10468 MachineMemOperand *MMO) {
10469 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10470 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10471 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10472 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10473 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10474 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10475 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10476 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10477 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10478 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10479 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10480 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10481 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10482 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10483 Opcode == ISD::ATOMIC_STORE) &&
10484 "Invalid Atomic Op");
10485
10486 EVT VT = Val.getValueType();
10487
10488 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10489 getVTList(VT, MVT::Other);
10490 SDValue Ops[] = {Chain, Ptr, Val};
10491 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10492}
10493
10495 EVT MemVT, EVT VT, SDValue Chain,
10496 SDValue Ptr, MachineMemOperand *MMO) {
10497 SDVTList VTs = getVTList(VT, MVT::Other);
10498 SDValue Ops[] = {Chain, Ptr};
10499 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10500}
10501
10502/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10504 if (Ops.size() == 1)
10505 return Ops[0];
10506
10508 VTs.reserve(Ops.size());
10509 for (const SDValue &Op : Ops)
10510 VTs.push_back(Op.getValueType());
10511 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10512}
10513
10515 SDValue Chain, const SDLoc &dl) {
10516 SmallVector<SDValue, 4> RetValues;
10517 RetValues.reserve(ResultTypes.size());
10518 for (EVT VT : ResultTypes)
10519 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10520 return getMergeValues(RetValues, dl);
10521}
10522
10524 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10525 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10527 const AAMDNodes &AAInfo) {
10528 if (Size.hasValue() && !Size.getValue())
10530
10532 MachineMemOperand *MMO =
10533 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10534
10535 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10536}
10537
10539 SDVTList VTList,
10540 ArrayRef<SDValue> Ops, EVT MemVT,
10541 MachineMemOperand *MMO) {
10542 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10543}
10544
10546 SDVTList VTList,
10547 ArrayRef<SDValue> Ops, EVT MemVT,
10549 assert(!MMOs.empty() && "Must have at least one MMO");
10550 assert(
10551 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10552 Opcode == ISD::PREFETCH ||
10553 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10554 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10555 "Opcode is not a memory-accessing opcode!");
10556
10558 if (MMOs.size() == 1) {
10559 MemRefs = MMOs[0];
10560 } else {
10561 // Allocate: [size_t count][MMO*][MMO*]...
10562 size_t AllocSize =
10563 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10564 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10565 size_t *CountPtr = static_cast<size_t *>(Buffer);
10566 *CountPtr = MMOs.size();
10567 MachineMemOperand **Array =
10568 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10569 llvm::copy(MMOs, Array);
10570 MemRefs = Array;
10571 }
10572
10573 // Memoize the node unless it returns a glue result.
10575 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10576 SDNodeKey ID(Opcode, VTList, Ops);
10577 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10578 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10579 ID.AddInteger(MemVT.getRawBits());
10580 for (const MachineMemOperand *MMO : MMOs) {
10581 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10582 ID.AddInteger(MMO->getFlags());
10583 }
10584 FoldingSetInsertToken InsertToken;
10585 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10586 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10587 return SDValue(E, 0);
10588 }
10589
10590 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10591 VTList, MemVT, MemRefs);
10592 createOperands(N, Ops);
10593 CSEMap.insert(N, InsertToken);
10594 } else {
10595 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10596 VTList, MemVT, MemRefs);
10597 createOperands(N, Ops);
10598 }
10599 InsertNode(N);
10600 SDValue V(N, 0);
10601 NewSDValueDbgMsg(V, "Creating new node: ", this);
10602 return V;
10603}
10604
10606 SDValue Chain, int FrameIndex) {
10607 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10608 const auto VTs = getVTList(MVT::Other);
10609 SDValue Ops[2] = {
10610 Chain,
10611 getFrameIndex(FrameIndex,
10612 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10613 true)};
10614
10615 SDNodeKey ID(Opcode, VTs, Ops);
10616 FoldingSetInsertToken InsertToken;
10617 if (SDNode *E = lookupNode(ID, dl, InsertToken))
10618 return SDValue(E, 0);
10619
10620 LifetimeSDNode *N =
10621 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10622 createOperands(N, Ops);
10623 CSEMap.insert(N, InsertToken);
10624 InsertNode(N);
10625 SDValue V(N, 0);
10626 NewSDValueDbgMsg(V, "Creating new node: ", this);
10627 return V;
10628}
10629
10631 uint64_t Guid, uint64_t Index,
10632 uint32_t Attr) {
10633 const unsigned Opcode = ISD::PSEUDO_PROBE;
10634 const auto VTs = getVTList(MVT::Other);
10635 SDValue Ops[] = {Chain};
10636 SDNodeKey ID(Opcode, VTs, Ops);
10637 ID.AddInteger(Guid);
10638 ID.AddInteger(Index);
10639 ID.AddInteger(Attr);
10640 FoldingSetInsertToken InsertToken;
10641 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
10642 return SDValue(E, 0);
10643
10644 auto *N = newSDNode<PseudoProbeSDNode>(
10645 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10646 createOperands(N, Ops);
10647 CSEMap.insert(N, InsertToken);
10648 InsertNode(N);
10649 SDValue V(N, 0);
10650 NewSDValueDbgMsg(V, "Creating new node: ", this);
10651 return V;
10652}
10653
10654/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10655/// MachinePointerInfo record from it. This is particularly useful because the
10656/// code generator has many cases where it doesn't bother passing in a
10657/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10659 SelectionDAG &DAG, SDValue Ptr,
10660 int64_t Offset = 0) {
10661 // If this is FI+Offset, we can model it.
10662 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10664 FI->getIndex(), Offset);
10665
10666 // If this is (FI+Offset1)+Offset2, we can model it.
10667 if (Ptr.getOpcode() != ISD::ADD ||
10670 return Info;
10671
10672 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10674 DAG.getMachineFunction(), FI,
10675 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10676}
10677
10678/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10679/// MachinePointerInfo record from it. This is particularly useful because the
10680/// code generator has many cases where it doesn't bother passing in a
10681/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10683 SelectionDAG &DAG, SDValue Ptr,
10684 SDValue OffsetOp) {
10685 // If the 'Offset' value isn't a constant, we can't handle this.
10687 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10688 if (OffsetOp.isUndef())
10689 return InferPointerInfo(Info, DAG, Ptr);
10690 return Info;
10691}
10692
10694 EVT VT, const SDLoc &dl, SDValue Chain,
10695 SDValue Ptr, SDValue Offset,
10696 MachinePointerInfo PtrInfo, EVT MemVT,
10697 Align Alignment,
10698 MachineMemOperand::Flags MMOFlags,
10699 const MMOMetadata &Metadata) {
10700 assert(Chain.getValueType() == MVT::Other &&
10701 "Invalid chain type");
10702
10703 MMOFlags |= MachineMemOperand::MOLoad;
10704 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10705 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10706 // clients.
10707 if (PtrInfo.V.isNull())
10708 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10709
10710 TypeSize Size = MemVT.getStoreSize();
10712 MachineMemOperand *MMO =
10713 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10714 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10715}
10716
10718 EVT VT, const SDLoc &dl, SDValue Chain,
10719 SDValue Ptr, SDValue Offset, EVT MemVT,
10720 MachineMemOperand *MMO) {
10721 if (VT == MemVT) {
10722 ExtType = ISD::NON_EXTLOAD;
10723 } else if (ExtType == ISD::NON_EXTLOAD) {
10724 assert(VT == MemVT && "Non-extending load from different memory type!");
10725 } else {
10726 // Extending load.
10727 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10728 "Should only be an extending load, not truncating!");
10729 assert(VT.isInteger() == MemVT.isInteger() &&
10730 "Cannot convert from FP to Int or Int -> FP!");
10731 assert(VT.isVector() == MemVT.isVector() &&
10732 "Cannot use an ext load to convert to or from a vector!");
10733 assert((!VT.isVector() ||
10735 "Cannot use an ext load to change the number of vector elements!");
10736 }
10737
10738 assert((!MMO->getRanges() ||
10740 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10741 MemVT.isInteger())) &&
10742 "Range metadata and load type must match!");
10743
10744 bool Indexed = AM != ISD::UNINDEXED;
10745 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10746 "Unindexed load with an offset!");
10747
10748 SDVTList VTs = Indexed ?
10749 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10750 SDValue Ops[] = { Chain, Ptr, Offset };
10751 SDNodeKey ID(ISD::LOAD, VTs, Ops);
10752 ID.AddInteger(MemVT.getRawBits());
10753 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
10754 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
10755 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10756 ID.AddInteger(MMO->getFlags());
10757 FoldingSetInsertToken InsertToken;
10758 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
10759 E->refineAlignment(MMO);
10760 E->refineMMOMetadata(MMO);
10761 return SDValue(E, 0);
10762 }
10763 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10764 ExtType, MemVT, MMO);
10765 createOperands(N, Ops);
10766
10767 CSEMap.insert(N, InsertToken);
10768 InsertNode(N);
10769 SDValue V(N, 0);
10770 NewSDValueDbgMsg(V, "Creating new node: ", this);
10771 return V;
10772}
10773
10775 SDValue Ptr, MachinePointerInfo PtrInfo,
10776 MaybeAlign Alignment,
10777 MachineMemOperand::Flags MMOFlags,
10778 const MMOMetadata &Metadata) {
10780 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10781 PtrInfo, VT, Alignment, MMOFlags, Metadata);
10782}
10783
10785 SDValue Ptr, MachineMemOperand *MMO) {
10787 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10788 VT, MMO);
10789}
10790
10792 EVT VT, SDValue Chain, SDValue Ptr,
10793 MachinePointerInfo PtrInfo, EVT MemVT,
10794 MaybeAlign Alignment,
10795 MachineMemOperand::Flags MMOFlags,
10796 const MMOMetadata &Metadata) {
10798 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
10799 MemVT, Alignment, MMOFlags, Metadata);
10800}
10801
10803 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
10804 MachineMemOperand *MMO) {
10806 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
10807 MemVT, MMO);
10808}
10809
10813 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
10814 assert(LD->getOffset().getOpcode() == ISD::POISON &&
10815 "Load is already a indexed load!");
10816 // Don't propagate the invariant or dereferenceable flags.
10817 auto MMOFlags =
10818 LD->getMemOperand()->getFlags() &
10820 return getLoad(
10821 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
10822 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
10823 MMOFlags,
10824 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
10825}
10826
10828 SDValue Ptr, MachinePointerInfo PtrInfo,
10829 Align Alignment,
10830 MachineMemOperand::Flags MMOFlags,
10831 const MMOMetadata &Metadata) {
10832 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10833
10834 MMOFlags |= MachineMemOperand::MOStore;
10835 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10836 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10837
10838 if (PtrInfo.V.isNull())
10839 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10840
10843 MachineMemOperand *MMO =
10844 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10845 return getStore(Chain, dl, Val, Ptr, MMO);
10846}
10847
10849 SDValue Ptr, MachineMemOperand *MMO) {
10851 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
10853}
10854
10856 SDValue Ptr, SDValue Offset, EVT SVT,
10858 bool IsTruncating) {
10859 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10860 EVT VT = Val.getValueType();
10861 if (VT == SVT) {
10862 IsTruncating = false;
10863 } else if (!IsTruncating) {
10864 assert(VT == SVT && "No-truncating store from different memory type!");
10865 } else {
10867 "Should only be a truncating store, not extending!");
10868 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10869 assert(VT.isVector() == SVT.isVector() &&
10870 "Cannot use trunc store to convert to or from a vector!");
10871 assert((!VT.isVector() ||
10873 "Cannot use trunc store to change the number of vector elements!");
10874 }
10875
10876 bool Indexed = AM != ISD::UNINDEXED;
10877 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10878 "Unindexed store with an offset!");
10879 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10880 : getVTList(MVT::Other);
10881 SDValue Ops[] = {Chain, Val, Ptr, Offset};
10882 SDNodeKey ID(ISD::STORE, VTs, Ops);
10883 ID.AddInteger(SVT.getRawBits());
10884 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
10885 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
10886 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10887 ID.AddInteger(MMO->getFlags());
10888 FoldingSetInsertToken InsertToken;
10889 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10890 cast<StoreSDNode>(E)->refineAlignment(MMO);
10891 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
10892 return SDValue(E, 0);
10893 }
10894 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10895 IsTruncating, SVT, MMO);
10896 createOperands(N, Ops);
10897
10898 CSEMap.insert(N, InsertToken);
10899 InsertNode(N);
10900 SDValue V(N, 0);
10901 NewSDValueDbgMsg(V, "Creating new node: ", this);
10902 return V;
10903}
10904
10906 SDValue Ptr, SDValue Offset,
10907 MachinePointerInfo PtrInfo, EVT SVT,
10908 Align Alignment,
10909 MachineMemOperand::Flags MMOFlags,
10910 const MMOMetadata &Metadata) {
10911 assert(Chain.getValueType() == MVT::Other &&
10912 "Invalid chain type");
10913
10914 MMOFlags |= MachineMemOperand::MOStore;
10915 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10916 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10917
10918 if (PtrInfo.V.isNull())
10919 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10920
10922 MachineMemOperand *MMO = MF.getMachineMemOperand(
10923 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
10924 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
10925}
10926
10928 SDValue Ptr, MachinePointerInfo PtrInfo,
10929 EVT SVT, Align Alignment,
10930 MachineMemOperand::Flags MMOFlags,
10931 const MMOMetadata &Metadata) {
10932 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
10933 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
10934}
10935
10937 SDValue Ptr, SDValue Offset, EVT SVT,
10938 MachineMemOperand *MMO) {
10939 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
10940}
10941
10943 SDValue Ptr, EVT SVT,
10944 MachineMemOperand *MMO) {
10945 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
10946 ISD::UNINDEXED, true);
10947}
10948
10952 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
10953 assert(ST->getOffset().getOpcode() == ISD::POISON &&
10954 "Store is already a indexed store!");
10955 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10956 ST->getMemoryVT(), ST->getMemOperand(), AM,
10957 ST->isTruncatingStore());
10958}
10959
10961 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
10962 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
10963 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
10964 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
10965 const MDNode *Ranges, bool IsExpanding) {
10966 MMOFlags |= MachineMemOperand::MOLoad;
10967 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10968 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10969 // clients.
10970 if (PtrInfo.V.isNull())
10971 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10972
10973 TypeSize Size = MemVT.getStoreSize();
10975 MachineMemOperand *MMO = MF.getMachineMemOperand(
10976 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
10977 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
10978 MMO, IsExpanding);
10979}
10980
10982 ISD::LoadExtType ExtType, EVT VT,
10983 const SDLoc &dl, SDValue Chain, SDValue Ptr,
10984 SDValue Offset, SDValue Mask, SDValue EVL,
10985 EVT MemVT, MachineMemOperand *MMO,
10986 bool IsExpanding) {
10987 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10988 assert(Mask.getValueType().getVectorElementCount() ==
10989 VT.getVectorElementCount() &&
10990 "Vector width mismatch between mask and data");
10991
10992 bool Indexed = AM != ISD::UNINDEXED;
10993 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10994 "Unindexed load with an offset!");
10995
10996 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
10997 : getVTList(VT, MVT::Other);
10998 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
10999 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11000 ID.AddInteger(MemVT.getRawBits());
11001 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11002 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11003 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11004 ID.AddInteger(MMO->getFlags());
11005 FoldingSetInsertToken InsertToken;
11006 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11007 E->refineAlignment(MMO);
11008 E->refineMMOMetadata(MMO);
11009 return SDValue(E, 0);
11010 }
11011 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11012 ExtType, IsExpanding, MemVT, MMO);
11013 createOperands(N, Ops);
11014
11015 CSEMap.insert(N, InsertToken);
11016 InsertNode(N);
11017 SDValue V(N, 0);
11018 NewSDValueDbgMsg(V, "Creating new node: ", this);
11019 return V;
11020}
11021
11023 SDValue Ptr, SDValue Mask, SDValue EVL,
11024 MachinePointerInfo PtrInfo,
11025 MaybeAlign Alignment,
11026 MachineMemOperand::Flags MMOFlags,
11027 const AAMDNodes &AAInfo, const MDNode *Ranges,
11028 bool IsExpanding) {
11030 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11031 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11032 IsExpanding);
11033}
11034
11036 SDValue Ptr, SDValue Mask, SDValue EVL,
11037 MachineMemOperand *MMO, bool IsExpanding) {
11039 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11040 Mask, EVL, VT, MMO, IsExpanding);
11041}
11042
11044 EVT VT, SDValue Chain, SDValue Ptr,
11045 SDValue Mask, SDValue EVL,
11046 MachinePointerInfo PtrInfo, EVT MemVT,
11047 MaybeAlign Alignment,
11048 MachineMemOperand::Flags MMOFlags,
11049 const AAMDNodes &AAInfo, bool IsExpanding) {
11051 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11052 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11053 IsExpanding);
11054}
11055
11057 EVT VT, SDValue Chain, SDValue Ptr,
11058 SDValue Mask, SDValue EVL, EVT MemVT,
11059 MachineMemOperand *MMO, bool IsExpanding) {
11061 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11062 EVL, MemVT, MMO, IsExpanding);
11063}
11064
11068 auto *LD = cast<VPLoadSDNode>(OrigLoad);
11069 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11070 "Load is already a indexed load!");
11071 // Don't propagate the invariant or dereferenceable flags.
11072 auto MMOFlags =
11073 LD->getMemOperand()->getFlags() &
11075 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
11076 LD->getChain(), Base, Offset, LD->getMask(),
11077 LD->getVectorLength(), LD->getPointerInfo(),
11078 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
11079 nullptr, LD->isExpandingLoad());
11080}
11081
11083 SDValue Ptr, SDValue Offset, SDValue Mask,
11084 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11085 ISD::MemIndexedMode AM, bool IsTruncating,
11086 bool IsCompressing) {
11087 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11088 assert(Mask.getValueType().getVectorElementCount() ==
11090 "Vector width mismatch between mask and data");
11091
11092 bool Indexed = AM != ISD::UNINDEXED;
11093 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11094 "Unindexed vp_store with an offset!");
11095 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11096 : getVTList(MVT::Other);
11097 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11098 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11099 ID.AddInteger(MemVT.getRawBits());
11100 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11101 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11102 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11103 ID.AddInteger(MMO->getFlags());
11104 FoldingSetInsertToken InsertToken;
11105 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11106 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11107 return SDValue(E, 0);
11108 }
11109 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11110 IsTruncating, IsCompressing, MemVT, MMO);
11111 createOperands(N, Ops);
11112
11113 CSEMap.insert(N, InsertToken);
11114 InsertNode(N);
11115 SDValue V(N, 0);
11116 NewSDValueDbgMsg(V, "Creating new node: ", this);
11117 return V;
11118}
11119
11121 SDValue Val, SDValue Ptr, SDValue Mask,
11122 SDValue EVL, MachinePointerInfo PtrInfo,
11123 EVT SVT, Align Alignment,
11124 MachineMemOperand::Flags MMOFlags,
11125 const AAMDNodes &AAInfo,
11126 bool IsCompressing) {
11127 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11128
11129 MMOFlags |= MachineMemOperand::MOStore;
11130 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11131
11132 if (PtrInfo.V.isNull())
11133 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11134
11136 MachineMemOperand *MMO = MF.getMachineMemOperand(
11137 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11138 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11139 IsCompressing);
11140}
11141
11143 SDValue Val, SDValue Ptr, SDValue Mask,
11144 SDValue EVL, EVT SVT,
11145 MachineMemOperand *MMO,
11146 bool IsCompressing) {
11147 EVT VT = Val.getValueType();
11148
11149 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11150 if (VT == SVT)
11151 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11152 EVL, VT, MMO, ISD::UNINDEXED,
11153 /*IsTruncating*/ false, IsCompressing);
11154
11156 "Should only be a truncating store, not extending!");
11157 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11158 assert(VT.isVector() == SVT.isVector() &&
11159 "Cannot use trunc store to convert to or from a vector!");
11160 assert((!VT.isVector() ||
11162 "Cannot use trunc store to change the number of vector elements!");
11163
11164 SDVTList VTs = getVTList(MVT::Other);
11166 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11167 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11168 ID.AddInteger(SVT.getRawBits());
11169 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11170 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11171 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11172 ID.AddInteger(MMO->getFlags());
11173 FoldingSetInsertToken InsertToken;
11174 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11175 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11176 return SDValue(E, 0);
11177 }
11178 auto *N =
11179 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11180 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11181 createOperands(N, Ops);
11182
11183 CSEMap.insert(N, InsertToken);
11184 InsertNode(N);
11185 SDValue V(N, 0);
11186 NewSDValueDbgMsg(V, "Creating new node: ", this);
11187 return V;
11188}
11189
11193 auto *ST = cast<VPStoreSDNode>(OrigStore);
11194 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11195 "Store is already an indexed store!");
11196 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
11197 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
11198 Offset, ST->getMask(), ST->getVectorLength()};
11199 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11200 ID.AddInteger(ST->getMemoryVT().getRawBits());
11201 ID.AddInteger(ST->getRawSubclassData());
11202 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
11203 ID.AddInteger(ST->getMemOperand()->getFlags());
11204 FoldingSetInsertToken InsertToken;
11205 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11206 return SDValue(E, 0);
11207
11208 auto *N = newSDNode<VPStoreSDNode>(
11209 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
11210 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
11211 createOperands(N, Ops);
11212
11213 CSEMap.insert(N, InsertToken);
11214 InsertNode(N);
11215 SDValue V(N, 0);
11216 NewSDValueDbgMsg(V, "Creating new node: ", this);
11217 return V;
11218}
11219
11221 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11222 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11223 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11224 bool Indexed = AM != ISD::UNINDEXED;
11225 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11226 "Unindexed load with an offset!");
11227
11228 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11229 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11230 : getVTList(VT, MVT::Other);
11231 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11232 ID.AddInteger(MemVT.getRawBits());
11233 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11234 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11235 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11236
11237 FoldingSetInsertToken InsertToken;
11238 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11239 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11240 return SDValue(E, 0);
11241 }
11242
11243 auto *N =
11244 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11245 ExtType, IsExpanding, MemVT, MMO);
11246 createOperands(N, Ops);
11247 CSEMap.insert(N, InsertToken);
11248 InsertNode(N);
11249 SDValue V(N, 0);
11250 NewSDValueDbgMsg(V, "Creating new node: ", this);
11251 return V;
11252}
11253
11255 SDValue Ptr, SDValue Stride,
11256 SDValue Mask, SDValue EVL,
11257 MachineMemOperand *MMO,
11258 bool IsExpanding) {
11260 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11261 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11262}
11263
11265 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11266 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11267 MachineMemOperand *MMO, bool IsExpanding) {
11269 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11270 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11271}
11272
11274 SDValue Val, SDValue Ptr,
11275 SDValue Offset, SDValue Stride,
11276 SDValue Mask, SDValue EVL, EVT MemVT,
11277 MachineMemOperand *MMO,
11279 bool IsTruncating, bool IsCompressing) {
11280 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11281 bool Indexed = AM != ISD::UNINDEXED;
11282 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11283 "Unindexed vp_store with an offset!");
11284 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11285 : getVTList(MVT::Other);
11286 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11287 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11288 ID.AddInteger(MemVT.getRawBits());
11289 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11290 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11291 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11292 FoldingSetInsertToken InsertToken;
11293 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11294 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11295 return SDValue(E, 0);
11296 }
11297 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11298 VTs, AM, IsTruncating,
11299 IsCompressing, MemVT, MMO);
11300 createOperands(N, Ops);
11301
11302 CSEMap.insert(N, InsertToken);
11303 InsertNode(N);
11304 SDValue V(N, 0);
11305 NewSDValueDbgMsg(V, "Creating new node: ", this);
11306 return V;
11307}
11308
11310 SDValue Val, SDValue Ptr,
11311 SDValue Stride, SDValue Mask,
11312 SDValue EVL, EVT SVT,
11313 MachineMemOperand *MMO,
11314 bool IsCompressing) {
11315 EVT VT = Val.getValueType();
11316
11317 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11318 if (VT == SVT)
11319 return getStridedStoreVP(Chain, DL, Val, Ptr, getPOISON(Ptr.getValueType()),
11320 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
11321 /*IsTruncating*/ false, IsCompressing);
11322
11324 "Should only be a truncating store, not extending!");
11325 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11326 assert(VT.isVector() == SVT.isVector() &&
11327 "Cannot use trunc store to convert to or from a vector!");
11328 assert((!VT.isVector() ||
11330 "Cannot use trunc store to change the number of vector elements!");
11331
11332 SDVTList VTs = getVTList(MVT::Other);
11334 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
11335 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11336 ID.AddInteger(SVT.getRawBits());
11337 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11338 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11339 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11340 FoldingSetInsertToken InsertToken;
11341 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11342 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11343 return SDValue(E, 0);
11344 }
11345 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11346 VTs, ISD::UNINDEXED, true,
11347 IsCompressing, SVT, MMO);
11348 createOperands(N, Ops);
11349
11350 CSEMap.insert(N, InsertToken);
11351 InsertNode(N);
11352 SDValue V(N, 0);
11353 NewSDValueDbgMsg(V, "Creating new node: ", this);
11354 return V;
11355}
11356
11359 ISD::MemIndexType IndexType) {
11360 assert(Ops.size() == 6 && "Incompatible number of operands");
11361
11362 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11363 ID.AddInteger(VT.getRawBits());
11364 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11365 dl.getIROrder(), VTs, VT, MMO, IndexType));
11366 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11367 ID.AddInteger(MMO->getFlags());
11368 FoldingSetInsertToken InsertToken;
11369 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11370 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11371 return SDValue(E, 0);
11372 }
11373
11374 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11375 VT, MMO, IndexType);
11376 createOperands(N, Ops);
11377
11378 assert(N->getMask().getValueType().getVectorElementCount() ==
11379 N->getValueType(0).getVectorElementCount() &&
11380 "Vector width mismatch between mask and data");
11381 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11382 N->getValueType(0).getVectorElementCount().isScalable() &&
11383 "Scalable flags of index and data do not match");
11385 N->getIndex().getValueType().getVectorElementCount(),
11386 N->getValueType(0).getVectorElementCount()) &&
11387 "Vector width mismatch between index and data");
11388 assert(isa<ConstantSDNode>(N->getScale()) &&
11389 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11390 "Scale should be a constant power of 2");
11391
11392 CSEMap.insert(N, InsertToken);
11393 InsertNode(N);
11394 SDValue V(N, 0);
11395 NewSDValueDbgMsg(V, "Creating new node: ", this);
11396 return V;
11397}
11398
11401 MachineMemOperand *MMO,
11402 ISD::MemIndexType IndexType) {
11403 assert(Ops.size() == 7 && "Incompatible number of operands");
11404
11405 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11406 ID.AddInteger(VT.getRawBits());
11407 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11408 dl.getIROrder(), VTs, VT, MMO, IndexType));
11409 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11410 ID.AddInteger(MMO->getFlags());
11411 FoldingSetInsertToken InsertToken;
11412 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11413 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11414 return SDValue(E, 0);
11415 }
11416 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11417 VT, MMO, IndexType);
11418 createOperands(N, Ops);
11419
11420 assert(N->getMask().getValueType().getVectorElementCount() ==
11421 N->getValue().getValueType().getVectorElementCount() &&
11422 "Vector width mismatch between mask and data");
11423 assert(
11424 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11425 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11426 "Scalable flags of index and data do not match");
11428 N->getIndex().getValueType().getVectorElementCount(),
11429 N->getValue().getValueType().getVectorElementCount()) &&
11430 "Vector width mismatch between index and data");
11431 assert(isa<ConstantSDNode>(N->getScale()) &&
11432 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11433 "Scale should be a constant power of 2");
11434
11435 CSEMap.insert(N, InsertToken);
11436 InsertNode(N);
11437 SDValue V(N, 0);
11438 NewSDValueDbgMsg(V, "Creating new node: ", this);
11439 return V;
11440}
11441
11444 SDValue PassThru, EVT MemVT,
11445 MachineMemOperand *MMO,
11447 ISD::LoadExtType ExtTy, bool isExpanding) {
11448 bool Indexed = AM != ISD::UNINDEXED;
11449 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11450 "Unindexed masked load with an offset!");
11451 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11452 : getVTList(VT, MVT::Other);
11453 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11454 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11455 ID.AddInteger(MemVT.getRawBits());
11456 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11457 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11458 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11459 ID.AddInteger(MMO->getFlags());
11460 FoldingSetInsertToken InsertToken;
11461 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11462 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11463 return SDValue(E, 0);
11464 }
11465 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11466 AM, ExtTy, isExpanding, MemVT, MMO);
11467 createOperands(N, Ops);
11468
11469 CSEMap.insert(N, InsertToken);
11470 InsertNode(N);
11471 SDValue V(N, 0);
11472 NewSDValueDbgMsg(V, "Creating new node: ", this);
11473 return V;
11474}
11475
11480 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11481 "Masked load is already a indexed load!");
11482 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11483 Offset, LD->getMask(), LD->getPassThru(),
11484 LD->getMemoryVT(), LD->getMemOperand(), AM,
11485 LD->getExtensionType(), LD->isExpandingLoad());
11486}
11487
11490 SDValue Mask, EVT MemVT,
11491 MachineMemOperand *MMO,
11492 ISD::MemIndexedMode AM, bool IsTruncating,
11493 bool IsCompressing) {
11494 assert(Chain.getValueType() == MVT::Other &&
11495 "Invalid chain type");
11496 bool Indexed = AM != ISD::UNINDEXED;
11497 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11498 "Unindexed masked store with an offset!");
11499 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11500 : getVTList(MVT::Other);
11501 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11502 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11503 ID.AddInteger(MemVT.getRawBits());
11504 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11505 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11506 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11507 ID.AddInteger(MMO->getFlags());
11508 FoldingSetInsertToken InsertToken;
11509 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11510 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11511 return SDValue(E, 0);
11512 }
11513 auto *N =
11514 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11515 IsTruncating, IsCompressing, MemVT, MMO);
11516 createOperands(N, Ops);
11517
11518 CSEMap.insert(N, InsertToken);
11519 InsertNode(N);
11520 SDValue V(N, 0);
11521 NewSDValueDbgMsg(V, "Creating new node: ", this);
11522 return V;
11523}
11524
11529 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11530 "Masked store is already a indexed store!");
11531 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11532 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11533 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11534}
11535
11538 MachineMemOperand *MMO,
11539 ISD::MemIndexType IndexType,
11540 ISD::LoadExtType ExtTy) {
11541 assert(Ops.size() == 6 && "Incompatible number of operands");
11542
11543 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11544 ID.AddInteger(MemVT.getRawBits());
11545 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11546 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11547 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11548 ID.AddInteger(MMO->getFlags());
11549 FoldingSetInsertToken InsertToken;
11550 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11551 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11552 return SDValue(E, 0);
11553 }
11554
11555 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11556 VTs, MemVT, MMO, IndexType, ExtTy);
11557 createOperands(N, Ops);
11558
11559 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11560 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11561 assert(N->getMask().getValueType().getVectorElementCount() ==
11562 N->getValueType(0).getVectorElementCount() &&
11563 "Vector width mismatch between mask and data");
11564 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11565 N->getValueType(0).getVectorElementCount().isScalable() &&
11566 "Scalable flags of index and data do not match");
11568 N->getIndex().getValueType().getVectorElementCount(),
11569 N->getValueType(0).getVectorElementCount()) &&
11570 "Vector width mismatch between index and data");
11571 assert(isa<ConstantSDNode>(N->getScale()) &&
11572 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11573 "Scale should be a constant power of 2");
11574
11575 CSEMap.insert(N, InsertToken);
11576 InsertNode(N);
11577 SDValue V(N, 0);
11578 NewSDValueDbgMsg(V, "Creating new node: ", this);
11579 return V;
11580}
11581
11584 MachineMemOperand *MMO,
11585 ISD::MemIndexType IndexType,
11586 bool IsTrunc) {
11587 assert(Ops.size() == 6 && "Incompatible number of operands");
11588
11589 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11590 ID.AddInteger(MemVT.getRawBits());
11591 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11592 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11593 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11594 ID.AddInteger(MMO->getFlags());
11595 FoldingSetInsertToken InsertToken;
11596 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11597 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11598 return SDValue(E, 0);
11599 }
11600
11601 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11602 VTs, MemVT, MMO, IndexType, IsTrunc);
11603 createOperands(N, Ops);
11604
11605 assert(N->getMask().getValueType().getVectorElementCount() ==
11606 N->getValue().getValueType().getVectorElementCount() &&
11607 "Vector width mismatch between mask and data");
11608 assert(
11609 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11610 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11611 "Scalable flags of index and data do not match");
11613 N->getIndex().getValueType().getVectorElementCount(),
11614 N->getValue().getValueType().getVectorElementCount()) &&
11615 "Vector width mismatch between index and data");
11616 assert(isa<ConstantSDNode>(N->getScale()) &&
11617 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11618 "Scale should be a constant power of 2");
11619
11620 CSEMap.insert(N, InsertToken);
11621 InsertNode(N);
11622 SDValue V(N, 0);
11623 NewSDValueDbgMsg(V, "Creating new node: ", this);
11624 return V;
11625}
11626
11628 const SDLoc &dl, ArrayRef<SDValue> Ops,
11629 MachineMemOperand *MMO,
11630 ISD::MemIndexType IndexType) {
11631 assert(Ops.size() == 7 && "Incompatible number of operands");
11632
11634 ID.AddInteger(MemVT.getRawBits());
11635 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11636 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11637 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11638 ID.AddInteger(MMO->getFlags());
11639 FoldingSetInsertToken InsertToken;
11640 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11641 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11642 return SDValue(E, 0);
11643 }
11644
11645 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11646 VTs, MemVT, MMO, IndexType);
11647 createOperands(N, Ops);
11648
11649 assert(N->getMask().getValueType().getVectorElementCount() ==
11650 N->getIndex().getValueType().getVectorElementCount() &&
11651 "Vector width mismatch between mask and data");
11652 assert(isa<ConstantSDNode>(N->getScale()) &&
11653 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11654 "Scale should be a constant power of 2");
11655 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11656
11657 CSEMap.insert(N, InsertToken);
11658 InsertNode(N);
11659 SDValue V(N, 0);
11660 NewSDValueDbgMsg(V, "Creating new node: ", this);
11661 return V;
11662}
11663
11665 SDValue Ptr, SDValue Mask, SDValue EVL,
11666 MachineMemOperand *MMO) {
11667 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11668 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11669 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11670 ID.AddInteger(VT.getRawBits());
11671 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11672 VTs, VT, MMO));
11673 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11674 ID.AddInteger(MMO->getFlags());
11675 FoldingSetInsertToken InsertToken;
11676 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11677 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11678 return SDValue(E, 0);
11679 }
11680 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11681 VT, MMO);
11682 createOperands(N, Ops);
11683
11684 CSEMap.insert(N, InsertToken);
11685 InsertNode(N);
11686 SDValue V(N, 0);
11687 NewSDValueDbgMsg(V, "Creating new node: ", this);
11688 return V;
11689}
11690
11692 EVT MemVT, MachineMemOperand *MMO) {
11693 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11694 SDVTList VTs = getVTList(MVT::Other);
11695 SDValue Ops[] = {Chain, Ptr};
11697 ID.AddInteger(MemVT.getRawBits());
11698 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11699 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11700 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11701 ID.AddInteger(MMO->getFlags());
11702 FoldingSetInsertToken InsertToken;
11703 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11704 return SDValue(E, 0);
11705
11706 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11707 dl.getDebugLoc(), VTs, MemVT, MMO);
11708 createOperands(N, Ops);
11709
11710 CSEMap.insert(N, InsertToken);
11711 InsertNode(N);
11712 SDValue V(N, 0);
11713 NewSDValueDbgMsg(V, "Creating new node: ", this);
11714 return V;
11715}
11716
11718 EVT MemVT, MachineMemOperand *MMO) {
11719 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11720 SDVTList VTs = getVTList(MVT::Other);
11721 SDValue Ops[] = {Chain, Ptr};
11723 ID.AddInteger(MemVT.getRawBits());
11724 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11725 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11726 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11727 ID.AddInteger(MMO->getFlags());
11728 FoldingSetInsertToken InsertToken;
11729 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11730 return SDValue(E, 0);
11731
11732 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11733 dl.getDebugLoc(), VTs, MemVT, MMO);
11734 createOperands(N, Ops);
11735
11736 CSEMap.insert(N, InsertToken);
11737 InsertNode(N);
11738 SDValue V(N, 0);
11739 NewSDValueDbgMsg(V, "Creating new node: ", this);
11740 return V;
11741}
11742
11744 // select undef, T, F --> T (if T is a constant), otherwise F
11745 // select, ?, undef, F --> F
11746 // select, ?, T, undef --> T
11747 if (Cond.isUndef())
11748 return isConstantValueOfAnyType(T) ? T : F;
11749 if (T.isUndef())
11751 if (F.isUndef())
11753
11754 // select true, T, F --> T
11755 // select false, T, F --> F
11756 if (auto C = isBoolConstant(Cond))
11757 return *C ? T : F;
11758
11759 // select ?, T, T --> T
11760 if (T == F)
11761 return T;
11762
11763 return SDValue();
11764}
11765
11767 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11768 if (X.isUndef())
11769 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11770 // shift X, undef --> undef (because it may shift by the bitwidth)
11771 if (Y.isUndef())
11772 return getUNDEF(X.getValueType());
11773
11774 // shift 0, Y --> 0
11775 // shift X, 0 --> X
11777 return X;
11778
11779 // shift X, C >= bitwidth(X) --> undef
11780 // All vector elements must be too big (or undef) to avoid partial undefs.
11781 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11782 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11783 };
11784 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11785 return getUNDEF(X.getValueType());
11786
11787 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11788 if (X.getValueType().getScalarType() == MVT::i1)
11789 return X;
11790
11791 return SDValue();
11792}
11793
11795 SDNodeFlags Flags) {
11796 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11797 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11798 // operation is poison. That result can be relaxed to undef.
11799 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11800 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11801 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11802 (YC && YC->getValueAPF().isNaN());
11803 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11804 (YC && YC->getValueAPF().isInfinity());
11805
11806 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11807 return getUNDEF(X.getValueType());
11808
11809 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11810 return getUNDEF(X.getValueType());
11811
11812 if (!YC)
11813 return SDValue();
11814
11815 // X + -0.0 --> X
11816 if (Opcode == ISD::FADD)
11817 if (YC->getValueAPF().isNegZero())
11818 return X;
11819
11820 // X - +0.0 --> X
11821 if (Opcode == ISD::FSUB)
11822 if (YC->getValueAPF().isPosZero())
11823 return X;
11824
11825 // X * 1.0 --> X
11826 // X / 1.0 --> X
11827 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11828 if (YC->getValueAPF().isOne())
11829 return X;
11830
11831 // X * 0.0 --> 0.0
11832 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11833 if (YC->getValueAPF().isZero())
11834 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11835
11836 return SDValue();
11837}
11838
11840 SDValue Ptr, SDValue SV, unsigned Align) {
11841 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11842 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11843}
11844
11845SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11847 switch (Ops.size()) {
11848 case 0: return getNode(Opcode, DL, VT);
11849 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
11850 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
11851 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
11852 default: break;
11853 }
11854
11855 // Copy from an SDUse array into an SDValue array for use with
11856 // the regular getNode logic.
11858 return getNode(Opcode, DL, VT, NewOps);
11859}
11860
11861SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11863 SDNodeFlags Flags;
11864 if (Inserter)
11865 Flags = Inserter->getFlags();
11866 return getNode(Opcode, DL, VT, Ops, Flags);
11867}
11868
11869SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11870 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11871 unsigned NumOps = Ops.size();
11872 switch (NumOps) {
11873 case 0: return getNode(Opcode, DL, VT);
11874 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
11875 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
11876 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
11877 default: break;
11878 }
11879
11880#ifndef NDEBUG
11881 for (const auto &Op : Ops)
11882 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11883 "Operand is DELETED_NODE!");
11884#endif
11885
11886 switch (Opcode) {
11887 default: break;
11888 case ISD::BUILD_VECTOR:
11889 // Attempt to simplify BUILD_VECTOR.
11890 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
11891 return V;
11892 break;
11894 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
11895 return V;
11896 break;
11897 case ISD::SELECT_CC:
11898 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
11899 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
11900 "LHS and RHS of condition must have same type!");
11901 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11902 "True and False arms of SelectCC must have same type!");
11903 assert(Ops[2].getValueType() == VT &&
11904 "select_cc node must be of same type as true and false value!");
11905 assert((!Ops[0].getValueType().isVector() ||
11906 Ops[0].getValueType().getVectorElementCount() ==
11907 VT.getVectorElementCount()) &&
11908 "Expected select_cc with vector result to have the same sized "
11909 "comparison type!");
11910 break;
11911 case ISD::BR_CC:
11912 assert(NumOps == 5 && "BR_CC takes 5 operands!");
11913 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11914 "LHS/RHS of comparison should match types!");
11915 break;
11916 case ISD::VP_REDUCE_MUL:
11917 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
11918 if (VT == MVT::i1)
11919 Opcode = ISD::VP_REDUCE_AND;
11920 break;
11921 case ISD::VP_REDUCE_ADD:
11922 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
11923 if (VT == MVT::i1)
11924 Opcode = ISD::VP_REDUCE_XOR;
11925 break;
11926 case ISD::VP_REDUCE_SMAX:
11927 case ISD::VP_REDUCE_UMIN:
11928 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
11929 // VP_REDUCE_AND.
11930 if (VT == MVT::i1)
11931 Opcode = ISD::VP_REDUCE_AND;
11932 break;
11933 case ISD::VP_REDUCE_SMIN:
11934 case ISD::VP_REDUCE_UMAX:
11935 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
11936 // VP_REDUCE_OR.
11937 if (VT == MVT::i1)
11938 Opcode = ISD::VP_REDUCE_OR;
11939 break;
11940 }
11941
11942 // Memoize nodes.
11943 SDNode *N;
11944 SDVTList VTs = getVTList(VT);
11945
11946 if (VT != MVT::Glue) {
11947 SDNodeKey ID(Opcode, VTs, Ops);
11948 FoldingSetInsertToken InsertToken;
11949
11950 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11951 E->intersectFlagsWith(Flags);
11952 return SDValue(E, 0);
11953 }
11954
11955 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11956 createOperands(N, Ops);
11957
11958 CSEMap.insert(N, InsertToken);
11959 } else {
11960 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11961 createOperands(N, Ops);
11962 }
11963
11964 N->setFlags(Flags);
11965 InsertNode(N);
11966 SDValue V(N, 0);
11967 NewSDValueDbgMsg(V, "Creating new node: ", this);
11968 return V;
11969}
11970
11971SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11972 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
11973 SDNodeFlags Flags;
11974 if (Inserter)
11975 Flags = Inserter->getFlags();
11976 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11977}
11978
11979SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11981 const SDNodeFlags Flags) {
11982 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11983}
11984
11985SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11987 SDNodeFlags Flags;
11988 if (Inserter)
11989 Flags = Inserter->getFlags();
11990 return getNode(Opcode, DL, VTList, Ops, Flags);
11991}
11992
11993SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11994 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11995 if (VTList.NumVTs == 1)
11996 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
11997
11998#ifndef NDEBUG
11999 for (const auto &Op : Ops)
12000 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12001 "Operand is DELETED_NODE!");
12002#endif
12003
12004 switch (Opcode) {
12005 case ISD::SADDO:
12006 case ISD::UADDO:
12007 case ISD::SSUBO:
12008 case ISD::USUBO: {
12009 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12010 "Invalid add/sub overflow op!");
12011 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12012 Ops[0].getValueType() == Ops[1].getValueType() &&
12013 Ops[0].getValueType() == VTList.VTs[0] &&
12014 "Binary operator types must match!");
12015 SDValue N1 = Ops[0], N2 = Ops[1];
12016 canonicalizeCommutativeBinop(Opcode, N1, N2);
12017
12018 // (X +- 0) -> X with zero-overflow.
12019 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12020 /*AllowTruncation*/ true);
12021 if (N2CV && N2CV->isZero()) {
12022 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12023 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12024 }
12025
12026 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12027 VTList.VTs[1].getScalarType() == MVT::i1) {
12028 SDValue F1 = getFreeze(N1);
12029 SDValue F2 = getFreeze(N2);
12030 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12031 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12032 return getNode(ISD::MERGE_VALUES, DL, VTList,
12033 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12034 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12035 Flags);
12036 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12037 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12038 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12039 return getNode(ISD::MERGE_VALUES, DL, VTList,
12040 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12041 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12042 Flags);
12043 }
12044 }
12045 break;
12046 }
12047 case ISD::SADDO_CARRY:
12048 case ISD::UADDO_CARRY:
12049 case ISD::SSUBO_CARRY:
12050 case ISD::USUBO_CARRY:
12051 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12052 "Invalid add/sub overflow op!");
12053 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12054 Ops[0].getValueType() == Ops[1].getValueType() &&
12055 Ops[0].getValueType() == VTList.VTs[0] &&
12056 Ops[2].getValueType() == VTList.VTs[1] &&
12057 "Binary operator types must match!");
12058 break;
12059 case ISD::SMUL_LOHI:
12060 case ISD::UMUL_LOHI: {
12061 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12062 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12063 VTList.VTs[0] == Ops[0].getValueType() &&
12064 VTList.VTs[0] == Ops[1].getValueType() &&
12065 "Binary operator types must match!");
12066 // Constant fold.
12069 if (LHS && RHS) {
12070 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12071 unsigned OutWidth = Width * 2;
12072 APInt Val = LHS->getAPIntValue();
12073 APInt Mul = RHS->getAPIntValue();
12074 if (Opcode == ISD::SMUL_LOHI) {
12075 Val = Val.sext(OutWidth);
12076 Mul = Mul.sext(OutWidth);
12077 } else {
12078 Val = Val.zext(OutWidth);
12079 Mul = Mul.zext(OutWidth);
12080 }
12081 Val *= Mul;
12082
12083 SDValue Hi =
12084 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12085 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12086 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12087 }
12088 break;
12089 }
12090 case ISD::FFREXP: {
12091 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12092 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12093 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12094
12096 int FrexpExp;
12097 APFloat FrexpMant =
12098 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12099 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12100 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12101 DL, VTList.VTs[1]);
12102 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12103 }
12104
12105 break;
12106 }
12108 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12109 "Invalid STRICT_FP_EXTEND!");
12110 assert(VTList.VTs[0].isFloatingPoint() &&
12111 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12112 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12113 "STRICT_FP_EXTEND result type should be vector iff the operand "
12114 "type is vector!");
12115 assert((!VTList.VTs[0].isVector() ||
12116 VTList.VTs[0].getVectorElementCount() ==
12117 Ops[1].getValueType().getVectorElementCount()) &&
12118 "Vector element count mismatch!");
12119 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12120 "Invalid fpext node, dst <= src!");
12121 break;
12123 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12124 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12125 "STRICT_FP_ROUND result type should be vector iff the operand "
12126 "type is vector!");
12127 assert((!VTList.VTs[0].isVector() ||
12128 VTList.VTs[0].getVectorElementCount() ==
12129 Ops[1].getValueType().getVectorElementCount()) &&
12130 "Vector element count mismatch!");
12131 assert(VTList.VTs[0].isFloatingPoint() &&
12132 Ops[1].getValueType().isFloatingPoint() &&
12133 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12134 Ops[2].getOpcode() == ISD::TargetConstant &&
12135 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12136 "Invalid STRICT_FP_ROUND!");
12137 break;
12138 }
12139
12140 // Memoize the node unless it returns a glue result.
12141 SDNode *N;
12142 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12143 SDNodeKey ID(Opcode, VTList, Ops);
12144 FoldingSetInsertToken InsertToken;
12145 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12146 E->intersectFlagsWith(Flags);
12147 return SDValue(E, 0);
12148 }
12149
12150 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12151 createOperands(N, Ops);
12152 CSEMap.insert(N, InsertToken);
12153 } else {
12154 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12155 createOperands(N, Ops);
12156 }
12157
12158 N->setFlags(Flags);
12159 InsertNode(N);
12160 SDValue V(N, 0);
12161 NewSDValueDbgMsg(V, "Creating new node: ", this);
12162 return V;
12163}
12164
12165SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12166 SDVTList VTList) {
12167 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12168}
12169
12170SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12171 SDValue N1) {
12172 SDValue Ops[] = { N1 };
12173 return getNode(Opcode, DL, VTList, Ops);
12174}
12175
12176SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12177 SDValue N1, SDValue N2) {
12178 SDValue Ops[] = { N1, N2 };
12179 return getNode(Opcode, DL, VTList, Ops);
12180}
12181
12182SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12183 SDValue N1, SDValue N2, SDValue N3) {
12184 SDValue Ops[] = { N1, N2, N3 };
12185 return getNode(Opcode, DL, VTList, Ops);
12186}
12187
12188SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12189 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12190 SDValue Ops[] = { N1, N2, N3, N4 };
12191 return getNode(Opcode, DL, VTList, Ops);
12192}
12193
12194SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12195 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12196 SDValue N5) {
12197 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12198 return getNode(Opcode, DL, VTList, Ops);
12199}
12200
12202 if (!VT.isExtended())
12203 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12204
12205 EVT VTs[] = {VT};
12206 return getVTList(VTs);
12207}
12208
12210 EVT VTs[] = {VT1, VT2};
12211 return getVTList(VTs);
12212}
12213
12215 EVT VTs[] = {VT1, VT2, VT3};
12216 return getVTList(VTs);
12217}
12218
12220 EVT VTs[] = {VT1, VT2, VT3, VT4};
12221 return getVTList(VTs);
12222}
12223
12225 auto It = VTLists.find(VTs);
12226 if (It == VTLists.end()) {
12227 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12228 llvm::copy(VTs, Array);
12229 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12230 }
12231 return makeVTList(It->data(), It->size());
12232}
12233
12234/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12235/// specified operands. If the resultant node already exists in the DAG,
12236/// this does not modify the specified node, instead it returns the node that
12237/// already exists. If the resultant node does not exist in the DAG, the
12238/// input node is returned. As a degenerate case, if you specify the same
12239/// input operands as the node already has, the input node is returned.
12241 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12242
12243 // Check to see if there is no change.
12244 if (Op == N->getOperand(0)) return N;
12245
12246 // See if the modified node already exists.
12247 FoldingSetInsertToken InsertToken;
12248 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken))
12249 return Existing;
12250
12251 // Nope it doesn't. Remove the node from its current place in the maps.
12252 if (InsertToken)
12253 if (!RemoveNodeFromCSEMaps(N))
12254 InsertToken = {};
12255
12256 // Now we update the operands.
12257 N->OperandList[0].set(Op);
12258
12260 // If this gets put into a CSE map, add it.
12261 if (InsertToken)
12262 CSEMap.insert(N, InsertToken);
12263 return N;
12264}
12265
12267 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12268
12269 // Check to see if there is no change.
12270 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12271 return N; // No operands changed, just return the input node.
12272
12273 // See if the modified node already exists.
12274 FoldingSetInsertToken InsertToken;
12275 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken))
12276 return Existing;
12277
12278 // Nope it doesn't. Remove the node from its current place in the maps.
12279 if (InsertToken)
12280 if (!RemoveNodeFromCSEMaps(N))
12281 InsertToken = {};
12282
12283 // Now we update the operands.
12284 if (N->OperandList[0] != Op1)
12285 N->OperandList[0].set(Op1);
12286 if (N->OperandList[1] != Op2)
12287 N->OperandList[1].set(Op2);
12288
12290 // If this gets put into a CSE map, add it.
12291 if (InsertToken)
12292 CSEMap.insert(N, InsertToken);
12293 return N;
12294}
12295
12298 SDValue Ops[] = { Op1, Op2, Op3 };
12299 return UpdateNodeOperands(N, Ops);
12300}
12301
12304 SDValue Op3, SDValue Op4) {
12305 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12306 return UpdateNodeOperands(N, Ops);
12307}
12308
12311 SDValue Op3, SDValue Op4, SDValue Op5) {
12312 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12313 return UpdateNodeOperands(N, Ops);
12314}
12315
12318 unsigned NumOps = Ops.size();
12319 assert(N->getNumOperands() == NumOps &&
12320 "Update with wrong number of operands");
12321
12322 // If no operands changed just return the input node.
12323 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12324 return N;
12325
12326 // See if the modified node already exists.
12327 FoldingSetInsertToken InsertToken;
12328 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken))
12329 return Existing;
12330
12331 // Nope it doesn't. Remove the node from its current place in the maps.
12332 if (InsertToken)
12333 if (!RemoveNodeFromCSEMaps(N))
12334 InsertToken = {};
12335
12336 // Now we update the operands.
12337 for (unsigned i = 0; i != NumOps; ++i)
12338 if (N->OperandList[i] != Ops[i])
12339 N->OperandList[i].set(Ops[i]);
12340
12342 // If this gets put into a CSE map, add it.
12343 if (InsertToken)
12344 CSEMap.insert(N, InsertToken);
12345 return N;
12346}
12347
12348/// DropOperands - Release the operands and set this node to have
12349/// zero operands.
12351 // Unlike the code in MorphNodeTo that does this, we don't need to
12352 // watch for dead nodes here.
12353 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12354 SDUse &Use = *I++;
12355 Use.set(SDValue());
12356 }
12357}
12358
12360 ArrayRef<MachineMemOperand *> NewMemRefs) {
12361 if (NewMemRefs.empty()) {
12362 N->clearMemRefs();
12363 return;
12364 }
12365
12366 // Check if we can avoid allocating by storing a single reference directly.
12367 if (NewMemRefs.size() == 1) {
12368 N->MemRefs = NewMemRefs[0];
12369 N->NumMemRefs = 1;
12370 return;
12371 }
12372
12373 MachineMemOperand **MemRefsBuffer =
12374 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12375 llvm::copy(NewMemRefs, MemRefsBuffer);
12376 N->MemRefs = MemRefsBuffer;
12377 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12378}
12379
12380/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12381/// machine opcode.
12382///
12384 EVT VT) {
12385 SDVTList VTs = getVTList(VT);
12386 return SelectNodeTo(N, MachineOpc, VTs, {});
12387}
12388
12390 EVT VT, SDValue Op1) {
12391 SDVTList VTs = getVTList(VT);
12392 SDValue Ops[] = { Op1 };
12393 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12394}
12395
12397 EVT VT, SDValue Op1,
12398 SDValue Op2) {
12399 SDVTList VTs = getVTList(VT);
12400 SDValue Ops[] = { Op1, Op2 };
12401 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12402}
12403
12405 EVT VT, SDValue Op1,
12406 SDValue Op2, SDValue Op3) {
12407 SDVTList VTs = getVTList(VT);
12408 SDValue Ops[] = { Op1, Op2, Op3 };
12409 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12410}
12411
12414 SDVTList VTs = getVTList(VT);
12415 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12416}
12417
12419 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12420 SDVTList VTs = getVTList(VT1, VT2);
12421 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12422}
12423
12425 EVT VT1, EVT VT2) {
12426 SDVTList VTs = getVTList(VT1, VT2);
12427 return SelectNodeTo(N, MachineOpc, VTs, {});
12428}
12429
12431 EVT VT1, EVT VT2, EVT VT3,
12433 SDVTList VTs = getVTList(VT1, VT2, VT3);
12434 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12435}
12436
12438 EVT VT1, EVT VT2,
12439 SDValue Op1, SDValue Op2) {
12440 SDVTList VTs = getVTList(VT1, VT2);
12441 SDValue Ops[] = { Op1, Op2 };
12442 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12443}
12444
12447 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12448 // Reset the NodeID to -1.
12449 New->setNodeId(-1);
12450 if (New != N) {
12451 ReplaceAllUsesWith(N, New);
12453 }
12454 return New;
12455}
12456
12457/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12458/// the line number information on the merged node since it is not possible to
12459/// preserve the information that operation is associated with multiple lines.
12460/// This will make the debugger working better at -O0, were there is a higher
12461/// probability having other instructions associated with that line.
12462///
12463/// For IROrder, we keep the smaller of the two
12464SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12465 DebugLoc NLoc = N->getDebugLoc();
12466 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12467 N->setDebugLoc(DebugLoc());
12468 }
12469 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12470 N->setIROrder(Order);
12471 return N;
12472}
12473
12474/// MorphNodeTo - This *mutates* the specified node to have the specified
12475/// return type, opcode, and operands.
12476///
12477/// Note that MorphNodeTo returns the resultant node. If there is already a
12478/// node of the specified opcode and operands, it returns that node instead of
12479/// the current one. Note that the SDLoc need not be the same.
12480///
12481/// Using MorphNodeTo is faster than creating a new node and swapping it in
12482/// with ReplaceAllUsesWith both because it often avoids allocating a new
12483/// node, and because it doesn't require CSE recalculation for any of
12484/// the node's users.
12485///
12486/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12487/// As a consequence it isn't appropriate to use from within the DAG combiner or
12488/// the legalizer which maintain worklists that would need to be updated when
12489/// deleting things.
12492 // If an identical node already exists, use it.
12493 FoldingSetInsertToken InsertToken;
12494 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12495 SDNodeKey ID(Opc, VTs, Ops);
12496 AddNodeIDCustom(ID.Tail, N, Opc);
12497 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12498 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12499 }
12500
12501 if (!RemoveNodeFromCSEMaps(N))
12502 InsertToken = {};
12503
12504 // Start the morphing.
12505 N->NodeType = Opc;
12506 N->ValueList = VTs.VTs;
12507 N->NumValues = VTs.NumVTs;
12508
12509 // Clear the operands list, updating used nodes to remove this from their
12510 // use list. Keep track of any operands that become dead as a result.
12511 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12512 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12513 SDUse &Use = *I++;
12514 SDNode *Used = Use.getNode();
12515 Use.set(SDValue());
12516 if (Used->use_empty())
12517 DeadNodeSet.insert(Used);
12518 }
12519
12520 // For MachineNode, initialize the memory references information.
12522 MN->clearMemRefs();
12523
12524 // Swap for an appropriately sized array from the recycler.
12525 removeOperands(N);
12526 createOperands(N, Ops);
12527
12528 // Delete any nodes that are still dead after adding the uses for the
12529 // new operands.
12530 if (!DeadNodeSet.empty()) {
12531 SmallVector<SDNode *, 16> DeadNodes;
12532 for (SDNode *N : DeadNodeSet)
12533 if (N->use_empty())
12534 DeadNodes.push_back(N);
12535 RemoveDeadNodes(DeadNodes);
12536 }
12537
12538 if (InsertToken)
12539 CSEMap.insert(N, InsertToken); // Memoize the new node.
12540 return N;
12541}
12542
12544 unsigned OrigOpc = Node->getOpcode();
12545 unsigned NewOpc;
12546 switch (OrigOpc) {
12547 default:
12548 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12549#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12550 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12551#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12552 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12553#include "llvm/IR/ConstrainedOps.def"
12554 }
12555
12556 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12557
12558 // We're taking this node out of the chain, so we need to re-link things.
12559 SDValue InputChain = Node->getOperand(0);
12560 SDValue OutputChain = SDValue(Node, 1);
12561 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12562
12564 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12565 Ops.push_back(Node->getOperand(i));
12566
12567 SDVTList VTs = getVTList(Node->getValueType(0));
12568 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12569
12570 // MorphNodeTo can operate in two ways: if an existing node with the
12571 // specified operands exists, it can just return it. Otherwise, it
12572 // updates the node in place to have the requested operands.
12573 if (Res == Node) {
12574 // If we updated the node in place, reset the node ID. To the isel,
12575 // this should be just like a newly allocated machine node.
12576 Res->setNodeId(-1);
12577 } else {
12580 }
12581
12582 return Res;
12583}
12584
12585/// getMachineNode - These are used for target selectors to create a new node
12586/// with specified return type(s), MachineInstr opcode, and operands.
12587///
12588/// Note that getMachineNode returns the resultant node. If there is already a
12589/// node of the specified opcode and operands, it returns that node instead of
12590/// the current one.
12592 EVT VT) {
12593 SDVTList VTs = getVTList(VT);
12594 return getMachineNode(Opcode, dl, VTs, {});
12595}
12596
12598 EVT VT, SDValue Op1) {
12599 SDVTList VTs = getVTList(VT);
12600 SDValue Ops[] = { Op1 };
12601 return getMachineNode(Opcode, dl, VTs, Ops);
12602}
12603
12605 EVT VT, SDValue Op1, SDValue Op2) {
12606 SDVTList VTs = getVTList(VT);
12607 SDValue Ops[] = { Op1, Op2 };
12608 return getMachineNode(Opcode, dl, VTs, Ops);
12609}
12610
12612 EVT VT, SDValue Op1, SDValue Op2,
12613 SDValue Op3) {
12614 SDVTList VTs = getVTList(VT);
12615 SDValue Ops[] = { Op1, Op2, Op3 };
12616 return getMachineNode(Opcode, dl, VTs, Ops);
12617}
12618
12621 SDVTList VTs = getVTList(VT);
12622 return getMachineNode(Opcode, dl, VTs, Ops);
12623}
12624
12626 EVT VT1, EVT VT2, SDValue Op1,
12627 SDValue Op2) {
12628 SDVTList VTs = getVTList(VT1, VT2);
12629 SDValue Ops[] = { Op1, Op2 };
12630 return getMachineNode(Opcode, dl, VTs, Ops);
12631}
12632
12634 EVT VT1, EVT VT2, SDValue Op1,
12635 SDValue Op2, SDValue Op3) {
12636 SDVTList VTs = getVTList(VT1, VT2);
12637 SDValue Ops[] = { Op1, Op2, Op3 };
12638 return getMachineNode(Opcode, dl, VTs, Ops);
12639}
12640
12642 EVT VT1, EVT VT2,
12644 SDVTList VTs = getVTList(VT1, VT2);
12645 return getMachineNode(Opcode, dl, VTs, Ops);
12646}
12647
12649 EVT VT1, EVT VT2, EVT VT3,
12650 SDValue Op1, SDValue Op2) {
12651 SDVTList VTs = getVTList(VT1, VT2, VT3);
12652 SDValue Ops[] = { Op1, Op2 };
12653 return getMachineNode(Opcode, dl, VTs, Ops);
12654}
12655
12657 EVT VT1, EVT VT2, EVT VT3,
12658 SDValue Op1, SDValue Op2,
12659 SDValue Op3) {
12660 SDVTList VTs = getVTList(VT1, VT2, VT3);
12661 SDValue Ops[] = { Op1, Op2, Op3 };
12662 return getMachineNode(Opcode, dl, VTs, Ops);
12663}
12664
12666 EVT VT1, EVT VT2, EVT VT3,
12668 SDVTList VTs = getVTList(VT1, VT2, VT3);
12669 return getMachineNode(Opcode, dl, VTs, Ops);
12670}
12671
12673 ArrayRef<EVT> ResultTys,
12675 SDVTList VTs = getVTList(ResultTys);
12676 return getMachineNode(Opcode, dl, VTs, Ops);
12677}
12678
12680 SDVTList VTs,
12682 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12684 FoldingSetInsertToken InsertToken;
12685
12686 if (DoCSE) {
12687 SDNodeKey ID(~Opcode, VTs, Ops);
12688 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12689 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12690 }
12691 }
12692
12693 // Allocate a new MachineSDNode.
12694 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12695 createOperands(N, Ops);
12696
12697 if (DoCSE)
12698 CSEMap.insert(N, InsertToken);
12699
12700 InsertNode(N);
12701 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12702 return N;
12703}
12704
12705/// getTargetExtractSubreg - A convenience function for creating
12706/// TargetOpcode::EXTRACT_SUBREG nodes.
12708 SDValue Operand) {
12709 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12710 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12711 VT, Operand, SRIdxVal);
12712 return SDValue(Subreg, 0);
12713}
12714
12715/// getTargetInsertSubreg - A convenience function for creating
12716/// TargetOpcode::INSERT_SUBREG nodes.
12718 SDValue Operand, SDValue Subreg) {
12719 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12720 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12721 VT, Operand, Subreg, SRIdxVal);
12722 return SDValue(Result, 0);
12723}
12724
12725/// getNodeIfExists - Get the specified node if it's already available, or
12726/// else return NULL.
12729 bool AllowCommute) {
12730 SDNodeFlags Flags;
12731 if (Inserter)
12732 Flags = Inserter->getFlags();
12733 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12734}
12735
12738 const SDNodeFlags Flags,
12739 bool AllowCommute) {
12740 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12741 return nullptr;
12742
12743 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12744 SDNodeKey ID(Opcode, VTList, LookupOps);
12745 FoldingSetInsertToken InsertToken;
12746 if (SDNode *E = lookupNode(ID, InsertToken)) {
12747 E->intersectFlagsWith(Flags);
12748 return E;
12749 }
12750 return nullptr;
12751 };
12752
12753 if (SDNode *Existing = Lookup(Ops))
12754 return Existing;
12755
12756 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12757 return Lookup({Ops[1], Ops[0]});
12758
12759 return nullptr;
12760}
12761
12762/// doesNodeExist - Check if a node exists without modifying its flags.
12763bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12765 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12766 SDNodeKey ID(Opcode, VTList, Ops);
12767 FoldingSetInsertToken InsertToken;
12768 if (lookupNode(ID, SDLoc(), InsertToken))
12769 return true;
12770 }
12771 return false;
12772}
12773
12774/// getDbgValue - Creates a SDDbgValue node.
12775///
12776/// SDNode
12778 SDNode *N, unsigned R, bool IsIndirect,
12779 const DebugLoc &DL, unsigned O) {
12780 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12781 "Expected inlined-at fields to agree");
12782 return new (DbgInfo->getAlloc())
12783 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12784 {}, IsIndirect, DL, O,
12785 /*IsVariadic=*/false);
12786}
12787
12788/// Constant
12790 DIExpression *Expr,
12791 const Value *C,
12792 const DebugLoc &DL, unsigned O) {
12793 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12794 "Expected inlined-at fields to agree");
12795 return new (DbgInfo->getAlloc())
12796 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12797 /*IsIndirect=*/false, DL, O,
12798 /*IsVariadic=*/false);
12799}
12800
12801/// FrameIndex
12803 DIExpression *Expr, unsigned FI,
12804 bool IsIndirect,
12805 const DebugLoc &DL,
12806 unsigned O) {
12807 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12808 "Expected inlined-at fields to agree");
12809 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12810}
12811
12812/// FrameIndex with dependencies
12814 DIExpression *Expr, unsigned FI,
12815 ArrayRef<SDNode *> Dependencies,
12816 bool IsIndirect,
12817 const DebugLoc &DL,
12818 unsigned O) {
12819 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12820 "Expected inlined-at fields to agree");
12821 return new (DbgInfo->getAlloc())
12822 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
12823 Dependencies, IsIndirect, DL, O,
12824 /*IsVariadic=*/false);
12825}
12826
12827/// VReg
12829 Register VReg, bool IsIndirect,
12830 const DebugLoc &DL, unsigned O) {
12831 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12832 "Expected inlined-at fields to agree");
12833 return new (DbgInfo->getAlloc())
12834 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
12835 {}, IsIndirect, DL, O,
12836 /*IsVariadic=*/false);
12837}
12838
12841 ArrayRef<SDNode *> Dependencies,
12842 bool IsIndirect, const DebugLoc &DL,
12843 unsigned O, bool IsVariadic) {
12844 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12845 "Expected inlined-at fields to agree");
12846 return new (DbgInfo->getAlloc())
12847 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
12848 DL, O, IsVariadic);
12849}
12850
12852 unsigned OffsetInBits, unsigned SizeInBits,
12853 bool InvalidateDbg) {
12854 SDNode *FromNode = From.getNode();
12855 SDNode *ToNode = To.getNode();
12856 assert(FromNode && ToNode && "Can't modify dbg values");
12857
12858 // PR35338
12859 // TODO: assert(From != To && "Redundant dbg value transfer");
12860 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
12861 if (From == To || FromNode == ToNode)
12862 return;
12863
12864 if (!FromNode->getHasDebugValue())
12865 return;
12866
12867 SDDbgOperand FromLocOp =
12868 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
12870
12872 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
12873 if (Dbg->isInvalidated())
12874 continue;
12875
12876 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
12877
12878 // Create a new location ops vector that is equal to the old vector, but
12879 // with each instance of FromLocOp replaced with ToLocOp.
12880 bool Changed = false;
12881 auto NewLocOps = Dbg->copyLocationOps();
12882 std::replace_if(
12883 NewLocOps.begin(), NewLocOps.end(),
12884 [&Changed, FromLocOp](const SDDbgOperand &Op) {
12885 bool Match = Op == FromLocOp;
12886 Changed |= Match;
12887 return Match;
12888 },
12889 ToLocOp);
12890 // Ignore this SDDbgValue if we didn't find a matching location.
12891 if (!Changed)
12892 continue;
12893
12894 DIVariable *Var = Dbg->getVariable();
12895 auto *Expr = Dbg->getExpression();
12896 // If a fragment is requested, update the expression.
12897 if (SizeInBits) {
12898 // When splitting a larger (e.g., sign-extended) value whose
12899 // lower bits are described with an SDDbgValue, do not attempt
12900 // to transfer the SDDbgValue to the upper bits.
12901 if (auto FI = Expr->getFragmentInfo())
12902 if (OffsetInBits + SizeInBits > FI->SizeInBits)
12903 continue;
12904 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
12905 SizeInBits);
12906 if (!Fragment)
12907 continue;
12908 Expr = *Fragment;
12909 }
12910
12911 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
12912 // Clone the SDDbgValue and move it to To.
12913 SDDbgValue *Clone = getDbgValueList(
12914 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
12915 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
12916 Dbg->isVariadic());
12917 ClonedDVs.push_back(Clone);
12918
12919 if (InvalidateDbg) {
12920 // Invalidate value and indicate the SDDbgValue should not be emitted.
12921 Dbg->setIsInvalidated();
12922 Dbg->setIsEmitted();
12923 }
12924 }
12925
12926 for (SDDbgValue *Dbg : ClonedDVs) {
12927 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
12928 "Transferred DbgValues should depend on the new SDNode");
12929 AddDbgValue(Dbg, false);
12930 }
12931}
12932
12934 if (!N.getHasDebugValue())
12935 return;
12936
12937 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
12938 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
12939 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
12940 return SDDbgOperand::fromNode(Node, ResNo);
12941 };
12942
12944 for (auto *DV : GetDbgValues(&N)) {
12945 if (DV->isInvalidated())
12946 continue;
12947 switch (N.getOpcode()) {
12948 default:
12949 break;
12950 case ISD::ADD: {
12951 SDValue N0 = N.getOperand(0);
12952 SDValue N1 = N.getOperand(1);
12953 if (!isa<ConstantSDNode>(N0)) {
12954 bool RHSConstant = isa<ConstantSDNode>(N1);
12955 uint64_t Offset;
12956 if (RHSConstant)
12957 Offset = N.getConstantOperandVal(1);
12958 // We are not allowed to turn indirect debug values variadic, so
12959 // don't salvage those.
12960 if (!RHSConstant && DV->isIndirect())
12961 continue;
12962
12963 // Rewrite an ADD constant node into a DIExpression. Since we are
12964 // performing arithmetic to compute the variable's *value* in the
12965 // DIExpression, we need to mark the expression with a
12966 // DW_OP_stack_value.
12967 auto *DIExpr = DV->getExpression();
12968 auto NewLocOps = DV->copyLocationOps();
12969 bool Changed = false;
12970 size_t OrigLocOpsSize = NewLocOps.size();
12971 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
12972 // We're not given a ResNo to compare against because the whole
12973 // node is going away. We know that any ISD::ADD only has one
12974 // result, so we can assume any node match is using the result.
12975 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
12976 NewLocOps[i].getSDNode() != &N)
12977 continue;
12978 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
12979 if (RHSConstant) {
12982 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
12983 } else {
12984 // Convert to a variadic expression (if not already).
12985 // convertToVariadicExpression() returns a const pointer, so we use
12986 // a temporary const variable here.
12987 const auto *TmpDIExpr =
12991 ExprOps.push_back(NewLocOps.size());
12992 ExprOps.push_back(dwarf::DW_OP_plus);
12993 SDDbgOperand RHS =
12995 NewLocOps.push_back(RHS);
12996 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
12997 }
12998 Changed = true;
12999 }
13000 (void)Changed;
13001 assert(Changed && "Salvage target doesn't use N");
13002
13003 bool IsVariadic =
13004 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13005
13006 auto AdditionalDependencies = DV->getAdditionalDependencies();
13007 SDDbgValue *Clone = getDbgValueList(
13008 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13009 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13010 ClonedDVs.push_back(Clone);
13011 DV->setIsInvalidated();
13012 DV->setIsEmitted();
13013 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13014 N0.getNode()->dumprFull(this);
13015 dbgs() << " into " << *DIExpr << '\n');
13016 }
13017 break;
13018 }
13019 case ISD::TRUNCATE: {
13020 SDValue N0 = N.getOperand(0);
13021 TypeSize FromSize = N0.getValueSizeInBits();
13022 TypeSize ToSize = N.getValueSizeInBits(0);
13023
13024 DIExpression *DbgExpression = DV->getExpression();
13025 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13026 auto NewLocOps = DV->copyLocationOps();
13027 bool Changed = false;
13028 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13029 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13030 NewLocOps[i].getSDNode() != &N)
13031 continue;
13032
13033 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13034 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13035 Changed = true;
13036 }
13037 assert(Changed && "Salvage target doesn't use N");
13038 (void)Changed;
13039
13040 SDDbgValue *Clone =
13041 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13042 DV->getAdditionalDependencies(), DV->isIndirect(),
13043 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13044
13045 ClonedDVs.push_back(Clone);
13046 DV->setIsInvalidated();
13047 DV->setIsEmitted();
13048 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13049 dbgs() << " into " << *DbgExpression << '\n');
13050 break;
13051 }
13052 }
13053 }
13054
13055 for (SDDbgValue *Dbg : ClonedDVs) {
13056 assert((!Dbg->getSDNodes().empty() ||
13057 llvm::any_of(Dbg->getLocationOps(),
13058 [&](const SDDbgOperand &Op) {
13059 return Op.getKind() == SDDbgOperand::FRAMEIX;
13060 })) &&
13061 "Salvaged DbgValue should depend on a new SDNode");
13062 AddDbgValue(Dbg, false);
13063 }
13064}
13065
13066/// Creates a SDDbgLabel node.
13068 const DebugLoc &DL, unsigned O) {
13069 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13070 "Expected inlined-at fields to agree");
13071 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13072}
13073
13074namespace {
13075
13076/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13077/// pointed to by a use iterator is deleted, increment the use iterator
13078/// so that it doesn't dangle.
13079///
13080class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13083
13084 void NodeDeleted(SDNode *N, SDNode *E) override {
13085 // Increment the iterator as needed.
13086 while (UI != UE && N == UI->getUser())
13087 ++UI;
13088 }
13089
13090public:
13091 RAUWUpdateListener(SelectionDAG &d,
13094 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13095};
13096
13097} // end anonymous namespace
13098
13099/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13100/// This can cause recursive merging of nodes in the DAG.
13101///
13102/// This version assumes From has a single result value.
13103///
13105 SDNode *From = FromN.getNode();
13106 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13107 "Cannot replace with this method!");
13108 assert(From != To.getNode() && "Cannot replace uses of with self");
13109
13110 // Preserve Debug Values
13111 transferDbgValues(FromN, To);
13112 // Preserve extra info.
13113 copyExtraInfo(From, To.getNode());
13114
13115 // Iterate over all the existing uses of From. New uses will be added
13116 // to the beginning of the use list, which we avoid visiting.
13117 // This specifically avoids visiting uses of From that arise while the
13118 // replacement is happening, because any such uses would be the result
13119 // of CSE: If an existing node looks like From after one of its operands
13120 // is replaced by To, we don't want to replace of all its users with To
13121 // too. See PR3018 for more info.
13122 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13123 RAUWUpdateListener Listener(*this, UI, UE);
13124 while (UI != UE) {
13125 SDNode *User = UI->getUser();
13126
13127 // This node is about to morph, remove its old self from the CSE maps.
13128 RemoveNodeFromCSEMaps(User);
13129
13130 // A user can appear in a use list multiple times, and when this
13131 // happens the uses are usually next to each other in the list.
13132 // To help reduce the number of CSE recomputations, process all
13133 // the uses of this user that we can find this way.
13134 do {
13135 SDUse &Use = *UI;
13136 ++UI;
13137 Use.set(To);
13138 if (To->isDivergent() != From->isDivergent())
13140 } while (UI != UE && UI->getUser() == User);
13141 // Now that we have modified User, add it back to the CSE maps. If it
13142 // already exists there, recursively merge the results together.
13143 AddModifiedNodeToCSEMaps(User);
13144 }
13145
13146 // If we just RAUW'd the root, take note.
13147 if (FromN == getRoot())
13148 setRoot(To);
13149}
13150
13151/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13152/// This can cause recursive merging of nodes in the DAG.
13153///
13154/// This version assumes that for each value of From, there is a
13155/// corresponding value in To in the same position with the same type.
13156///
13158#ifndef NDEBUG
13159 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13160 assert((!From->hasAnyUseOfValue(i) ||
13161 From->getValueType(i) == To->getValueType(i)) &&
13162 "Cannot use this version of ReplaceAllUsesWith!");
13163#endif
13164
13165 // Handle the trivial case.
13166 if (From == To)
13167 return;
13168
13169 // Preserve Debug Info. Only do this if there's a use.
13170 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13171 if (From->hasAnyUseOfValue(i)) {
13172 assert((i < To->getNumValues()) && "Invalid To location");
13173 transferDbgValues(SDValue(From, i), SDValue(To, i));
13174 }
13175 // Preserve extra info.
13176 copyExtraInfo(From, To);
13177
13178 // Iterate over just the existing users of From. See the comments in
13179 // the ReplaceAllUsesWith above.
13180 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13181 RAUWUpdateListener Listener(*this, UI, UE);
13182 while (UI != UE) {
13183 SDNode *User = UI->getUser();
13184
13185 // This node is about to morph, remove its old self from the CSE maps.
13186 RemoveNodeFromCSEMaps(User);
13187
13188 // A user can appear in a use list multiple times, and when this
13189 // happens the uses are usually next to each other in the list.
13190 // To help reduce the number of CSE recomputations, process all
13191 // the uses of this user that we can find this way.
13192 do {
13193 SDUse &Use = *UI;
13194 ++UI;
13195 Use.setNode(To);
13196 if (To->isDivergent() != From->isDivergent())
13198 } while (UI != UE && UI->getUser() == User);
13199
13200 // Now that we have modified User, add it back to the CSE maps. If it
13201 // already exists there, recursively merge the results together.
13202 AddModifiedNodeToCSEMaps(User);
13203 }
13204
13205 // If we just RAUW'd the root, take note.
13206 if (From == getRoot().getNode())
13207 setRoot(SDValue(To, getRoot().getResNo()));
13208}
13209
13210/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13211/// This can cause recursive merging of nodes in the DAG.
13212///
13213/// This version can replace From with any result values. To must match the
13214/// number and types of values returned by From.
13216 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13217 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13218
13219 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13220 // Preserve Debug Info.
13221 transferDbgValues(SDValue(From, i), To[i]);
13222 // Preserve extra info.
13223 copyExtraInfo(From, To[i].getNode());
13224 }
13225
13226 // Iterate over just the existing users of From. See the comments in
13227 // the ReplaceAllUsesWith above.
13228 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13229 RAUWUpdateListener Listener(*this, UI, UE);
13230 while (UI != UE) {
13231 SDNode *User = UI->getUser();
13232
13233 // This node is about to morph, remove its old self from the CSE maps.
13234 RemoveNodeFromCSEMaps(User);
13235
13236 // A user can appear in a use list multiple times, and when this happens the
13237 // uses are usually next to each other in the list. To help reduce the
13238 // number of CSE and divergence recomputations, process all the uses of this
13239 // user that we can find this way.
13240 bool To_IsDivergent = false;
13241 do {
13242 SDUse &Use = *UI;
13243 const SDValue &ToOp = To[Use.getResNo()];
13244 ++UI;
13245 Use.set(ToOp);
13246 if (ToOp.getValueType() != MVT::Other)
13247 To_IsDivergent |= ToOp->isDivergent();
13248 } while (UI != UE && UI->getUser() == User);
13249
13250 if (To_IsDivergent != From->isDivergent())
13252
13253 // Now that we have modified User, add it back to the CSE maps. If it
13254 // already exists there, recursively merge the results together.
13255 AddModifiedNodeToCSEMaps(User);
13256 }
13257
13258 // If we just RAUW'd the root, take note.
13259 if (From == getRoot().getNode())
13260 setRoot(SDValue(To[getRoot().getResNo()]));
13261}
13262
13263/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13264/// uses of other values produced by From.getNode() alone. The Deleted
13265/// vector is handled the same way as for ReplaceAllUsesWith.
13267 // Handle the really simple, really trivial case efficiently.
13268 if (From == To) return;
13269
13270 // Handle the simple, trivial, case efficiently.
13271 if (From.getNode()->getNumValues() == 1) {
13272 ReplaceAllUsesWith(From, To);
13273 return;
13274 }
13275
13276 // Preserve Debug Info.
13277 transferDbgValues(From, To);
13278 copyExtraInfo(From.getNode(), To.getNode());
13279
13280 // Iterate over just the existing users of From. See the comments in
13281 // the ReplaceAllUsesWith above.
13282 SDNode::use_iterator UI = From.getNode()->use_begin(),
13283 UE = From.getNode()->use_end();
13284 RAUWUpdateListener Listener(*this, UI, UE);
13285 while (UI != UE) {
13286 SDNode *User = UI->getUser();
13287 bool UserRemovedFromCSEMaps = false;
13288
13289 // A user can appear in a use list multiple times, and when this
13290 // happens the uses are usually next to each other in the list.
13291 // To help reduce the number of CSE recomputations, process all
13292 // the uses of this user that we can find this way.
13293 do {
13294 SDUse &Use = *UI;
13295
13296 // Skip uses of different values from the same node.
13297 if (Use.getResNo() != From.getResNo()) {
13298 ++UI;
13299 continue;
13300 }
13301
13302 // If this node hasn't been modified yet, it's still in the CSE maps,
13303 // so remove its old self from the CSE maps.
13304 if (!UserRemovedFromCSEMaps) {
13305 RemoveNodeFromCSEMaps(User);
13306 UserRemovedFromCSEMaps = true;
13307 }
13308
13309 ++UI;
13310 Use.set(To);
13311 if (To->isDivergent() != From->isDivergent())
13313 } while (UI != UE && UI->getUser() == User);
13314 // We are iterating over all uses of the From node, so if a use
13315 // doesn't use the specific value, no changes are made.
13316 if (!UserRemovedFromCSEMaps)
13317 continue;
13318
13319 // Now that we have modified User, add it back to the CSE maps. If it
13320 // already exists there, recursively merge the results together.
13321 AddModifiedNodeToCSEMaps(User);
13322 }
13323
13324 // If we just RAUW'd the root, take note.
13325 if (From == getRoot())
13326 setRoot(To);
13327}
13328
13329namespace {
13330
13331/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13332/// to record information about a use.
13333struct UseMemo {
13334 SDNode *User;
13335 unsigned Index;
13336 SDUse *Use;
13337};
13338
13339/// operator< - Sort Memos by User.
13340bool operator<(const UseMemo &L, const UseMemo &R) {
13341 return (intptr_t)L.User < (intptr_t)R.User;
13342}
13343
13344/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13345/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13346/// the node already has been taken care of recursively.
13347class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13348 SmallVectorImpl<UseMemo> &Uses;
13349
13350 void NodeDeleted(SDNode *N, SDNode *E) override {
13351 for (UseMemo &Memo : Uses)
13352 if (Memo.User == N)
13353 Memo.User = nullptr;
13354 }
13355
13356public:
13357 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13358 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13359};
13360
13361} // end anonymous namespace
13362
13363/// Return true if a glue output should propagate divergence information.
13365 switch (Node->getOpcode()) {
13366 case ISD::CopyFromReg:
13367 case ISD::CopyToReg:
13368 return false;
13369 default:
13370 return true;
13371 }
13372
13373 llvm_unreachable("covered opcode switch");
13374}
13375
13377 if (TLI->isSDNodeAlwaysUniform(N)) {
13378 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13379 "Conflicting divergence information!");
13380 return false;
13381 }
13382 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13383 return true;
13384 for (const auto &Op : N->ops()) {
13385 EVT VT = Op.getValueType();
13386
13387 // Skip Chain. It does not carry divergence.
13388 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13389 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13390 return true;
13391 }
13392 return false;
13393}
13394
13396 SmallVector<SDNode *, 16> Worklist(1, N);
13397 do {
13398 N = Worklist.pop_back_val();
13399 bool IsDivergent = calculateDivergence(N);
13400 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13401 N->SDNodeBits.IsDivergent = IsDivergent;
13402 llvm::append_range(Worklist, N->users());
13403 }
13404 } while (!Worklist.empty());
13405}
13406
13407void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13409 Order.reserve(AllNodes.size());
13410 for (auto &N : allnodes()) {
13411 unsigned NOps = N.getNumOperands();
13412 Degree[&N] = NOps;
13413 if (0 == NOps)
13414 Order.push_back(&N);
13415 }
13416 for (size_t I = 0; I != Order.size(); ++I) {
13417 SDNode *N = Order[I];
13418 for (auto *U : N->users()) {
13419 unsigned &UnsortedOps = Degree[U];
13420 if (0 == --UnsortedOps)
13421 Order.push_back(U);
13422 }
13423 }
13424}
13425
13426#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13427void SelectionDAG::VerifyDAGDivergence() {
13428 std::vector<SDNode *> TopoOrder;
13429 CreateTopologicalOrder(TopoOrder);
13430 for (auto *N : TopoOrder) {
13431 assert(calculateDivergence(N) == N->isDivergent() &&
13432 "Divergence bit inconsistency detected");
13433 }
13434}
13435#endif
13436
13437/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13438/// uses of other values produced by From.getNode() alone. The same value
13439/// may appear in both the From and To list. The Deleted vector is
13440/// handled the same way as for ReplaceAllUsesWith.
13442 const SDValue *To,
13443 unsigned Num){
13444 // Handle the simple, trivial case efficiently.
13445 if (Num == 1)
13446 return ReplaceAllUsesOfValueWith(*From, *To);
13447
13448 transferDbgValues(*From, *To);
13449 copyExtraInfo(From->getNode(), To->getNode());
13450
13451 // Read up all the uses and make records of them. This helps
13452 // processing new uses that are introduced during the
13453 // replacement process.
13455 for (unsigned i = 0; i != Num; ++i) {
13456 unsigned FromResNo = From[i].getResNo();
13457 SDNode *FromNode = From[i].getNode();
13458 for (SDUse &Use : FromNode->uses()) {
13459 if (Use.getResNo() == FromResNo) {
13460 UseMemo Memo = {Use.getUser(), i, &Use};
13461 Uses.push_back(Memo);
13462 }
13463 }
13464 }
13465
13466 // Sort the uses, so that all the uses from a given User are together.
13468 RAUOVWUpdateListener Listener(*this, Uses);
13469
13470 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13471 UseIndex != UseIndexEnd; ) {
13472 // We know that this user uses some value of From. If it is the right
13473 // value, update it.
13474 SDNode *User = Uses[UseIndex].User;
13475 // If the node has been deleted by recursive CSE updates when updating
13476 // another node, then just skip this entry.
13477 if (User == nullptr) {
13478 ++UseIndex;
13479 continue;
13480 }
13481
13482 // This node is about to morph, remove its old self from the CSE maps.
13483 RemoveNodeFromCSEMaps(User);
13484
13485 // The Uses array is sorted, so all the uses for a given User
13486 // are next to each other in the list.
13487 // To help reduce the number of CSE recomputations, process all
13488 // the uses of this user that we can find this way.
13489 do {
13490 unsigned i = Uses[UseIndex].Index;
13491 SDUse &Use = *Uses[UseIndex].Use;
13492 ++UseIndex;
13493
13494 Use.set(To[i]);
13495 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13496
13497 // Now that we have modified User, add it back to the CSE maps. If it
13498 // already exists there, recursively merge the results together.
13499 AddModifiedNodeToCSEMaps(User);
13500 }
13501}
13502
13503/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13504/// based on their topological order. It returns the maximum id and a vector
13505/// of the SDNodes* in assigned order by reference.
13507 unsigned DAGSize = 0;
13508
13509 // SortedPos tracks the progress of the algorithm. Nodes before it are
13510 // sorted, nodes after it are unsorted. When the algorithm completes
13511 // it is at the end of the list.
13512 allnodes_iterator SortedPos = allnodes_begin();
13513
13514 // Visit all the nodes. Move nodes with no operands to the front of
13515 // the list immediately. Annotate nodes that do have operands with their
13516 // operand count. Before we do this, the Node Id fields of the nodes
13517 // may contain arbitrary values. After, the Node Id fields for nodes
13518 // before SortedPos will contain the topological sort index, and the
13519 // Node Id fields for nodes At SortedPos and after will contain the
13520 // count of outstanding operands.
13522 checkForCycles(&N, this);
13523 unsigned Degree = N.getNumOperands();
13524 if (Degree == 0) {
13525 // A node with no uses, add it to the result array immediately.
13526 N.setNodeId(DAGSize++);
13527 allnodes_iterator Q(&N);
13528 if (Q != SortedPos)
13529 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13530 assert(SortedPos != AllNodes.end() && "Overran node list");
13531 ++SortedPos;
13532 } else {
13533 // Temporarily use the Node Id as scratch space for the degree count.
13534 N.setNodeId(Degree);
13535 }
13536 }
13537
13538 // Visit all the nodes. As we iterate, move nodes into sorted order,
13539 // such that by the time the end is reached all nodes will be sorted.
13540 for (SDNode &Node : allnodes()) {
13541 SDNode *N = &Node;
13542 checkForCycles(N, this);
13543 // N is in sorted position, so all its uses have one less operand
13544 // that needs to be sorted.
13545 for (SDNode *P : N->users()) {
13546 unsigned Degree = P->getNodeId();
13547 assert(Degree != 0 && "Invalid node degree");
13548 --Degree;
13549 if (Degree == 0) {
13550 // All of P's operands are sorted, so P may sorted now.
13551 P->setNodeId(DAGSize++);
13552 if (P->getIterator() != SortedPos)
13553 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13554 assert(SortedPos != AllNodes.end() && "Overran node list");
13555 ++SortedPos;
13556 } else {
13557 // Update P's outstanding operand count.
13558 P->setNodeId(Degree);
13559 }
13560 }
13561 if (Node.getIterator() == SortedPos) {
13562#ifndef NDEBUG
13564 SDNode *S = &*++I;
13565 dbgs() << "Overran sorted position:\n";
13566 S->dumprFull(this); dbgs() << "\n";
13567 dbgs() << "Checking if this is due to cycles\n";
13568 checkForCycles(this, true);
13569#endif
13570 llvm_unreachable(nullptr);
13571 }
13572 }
13573
13574 assert(SortedPos == AllNodes.end() &&
13575 "Topological sort incomplete!");
13576 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13577 "First node in topological sort is not the entry token!");
13578 assert(AllNodes.front().getNodeId() == 0 &&
13579 "First node in topological sort has non-zero id!");
13580 assert(AllNodes.front().getNumOperands() == 0 &&
13581 "First node in topological sort has operands!");
13582 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13583 "Last node in topologic sort has unexpected id!");
13584 assert(AllNodes.back().use_empty() &&
13585 "Last node in topologic sort has users!");
13586 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13587 return DAGSize;
13588}
13589
13591 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13592 SortedNodes.clear();
13593 // Node -> remaining number of outstanding operands.
13594 DenseMap<const SDNode *, unsigned> RemainingOperands;
13595
13596 // Put nodes without any operands into SortedNodes first.
13597 for (const SDNode &N : allnodes()) {
13598 checkForCycles(&N, this);
13599 unsigned NumOperands = N.getNumOperands();
13600 if (NumOperands == 0)
13601 SortedNodes.push_back(&N);
13602 else
13603 // Record their total number of outstanding operands.
13604 RemainingOperands[&N] = NumOperands;
13605 }
13606
13607 // A node is pushed into SortedNodes when all of its operands (predecessors in
13608 // the graph) are also in SortedNodes.
13609 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13610 const SDNode *N = SortedNodes[i];
13611 for (const SDNode *U : N->users()) {
13612 // HandleSDNode is never part of a DAG and therefore has no entry in
13613 // RemainingOperands.
13614 if (U->getOpcode() == ISD::HANDLENODE)
13615 continue;
13616 unsigned &NumRemOperands = RemainingOperands[U];
13617 assert(NumRemOperands && "Invalid number of remaining operands");
13618 --NumRemOperands;
13619 if (!NumRemOperands)
13620 SortedNodes.push_back(U);
13621 }
13622 }
13623
13624 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13625 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13626 "First node in topological sort is not the entry token");
13627 assert(SortedNodes.front()->getNumOperands() == 0 &&
13628 "First node in topological sort has operands");
13629}
13630
13631/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13632/// value is produced by SD.
13633void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13634 for (SDNode *SD : DB->getSDNodes()) {
13635 if (!SD)
13636 continue;
13637 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13638 SD->setHasDebugValue(true);
13639 }
13640 DbgInfo->add(DB, isParameter);
13641}
13642
13643void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13644
13646 SDValue NewMemOpChain) {
13647 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13648 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13649 // The new memory operation must have the same position as the old load in
13650 // terms of memory dependency. Create a TokenFactor for the old load and new
13651 // memory operation and update uses of the old load's output chain to use that
13652 // TokenFactor.
13653 if (OldChain == NewMemOpChain || OldChain.use_empty())
13654 return NewMemOpChain;
13655
13656 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13657 OldChain, NewMemOpChain);
13658 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13659 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13660 return TokenFactor;
13661}
13662
13664 SDValue NewMemOp) {
13665 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13666 SDValue OldChain = SDValue(OldLoad, 1);
13667 SDValue NewMemOpChain = NewMemOp.getValue(1);
13668 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13669}
13670
13672 Function **OutFunction) {
13673 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13674
13675 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13676 auto *Module = MF->getFunction().getParent();
13677 auto *Function = Module->getFunction(Symbol);
13678
13679 if (OutFunction != nullptr)
13680 *OutFunction = Function;
13681
13682 if (Function != nullptr) {
13683 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13684 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13685 }
13686
13687 std::string ErrorStr;
13688 raw_string_ostream ErrorFormatter(ErrorStr);
13689 ErrorFormatter << "Undefined external symbol ";
13690 ErrorFormatter << '"' << Symbol << '"';
13691 report_fatal_error(Twine(ErrorStr));
13692}
13693
13694//===----------------------------------------------------------------------===//
13695// SDNode Class
13696//===----------------------------------------------------------------------===//
13697
13700 return Const != nullptr && Const->isZero();
13701}
13702
13704 return V.isUndef() || isNullConstant(V);
13705}
13706
13709 return Const != nullptr && Const->isZero() && !Const->isNegative();
13710}
13711
13714 return Const != nullptr && Const->isAllOnes();
13715}
13716
13719 return Const != nullptr && Const->isOne();
13720}
13721
13724 return Const != nullptr && Const->isMinSignedValue();
13725}
13726
13728 SDValue V, unsigned OperandNo,
13729 unsigned Depth) const {
13730 APInt DemandedElts = getDemandAllEltsMask(V);
13731 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13732}
13733
13735 SDValue V, const APInt &DemandedElts,
13736 unsigned OperandNo, unsigned Depth) const {
13737 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13738 // TODO: Target-specific opcodes could be added.
13739 if (V.getValueType().isInteger()) {
13740 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13741 if (Known.isConstant()) {
13742 const APInt &Const = Known.getConstant();
13743 switch (Opcode) {
13744 case ISD::ADD:
13745 case ISD::OR:
13746 case ISD::XOR:
13747 case ISD::UMAX:
13748 return Const.isZero();
13749 case ISD::MUL:
13750 return Const.isOne();
13751 case ISD::AND:
13752 case ISD::UMIN:
13753 return Const.isAllOnes();
13754 case ISD::SMAX:
13755 return Const.isMinSignedValue();
13756 case ISD::SMIN:
13757 return Const.isMaxSignedValue();
13758 case ISD::SUB:
13759 case ISD::SHL:
13760 case ISD::SRA:
13761 case ISD::SRL:
13762 return OperandNo == 1 && Const.isZero();
13763 case ISD::UDIV:
13764 case ISD::SDIV:
13765 return OperandNo == 1 && Const.isOne();
13766 }
13767 }
13768 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13769 switch (Opcode) {
13770 case ISD::FADD:
13771 return ConstFP->isZero() &&
13772 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13773 case ISD::FSUB:
13774 return OperandNo == 1 && ConstFP->isZero() &&
13775 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13776 case ISD::FMUL:
13777 return ConstFP->isOne();
13778 case ISD::FDIV:
13779 return OperandNo == 1 && ConstFP->isOne();
13780 case ISD::FMINNUM:
13781 case ISD::FMAXNUM:
13782 case ISD::FMINIMUMNUM:
13783 case ISD::FMAXIMUMNUM: {
13784 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
13785 // depending on fast-math flags (FMF).
13786 EVT VT = V.getValueType();
13787 const fltSemantics &Semantics = VT.getFltSemantics();
13788 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13789 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13790 : APFloat::getLargest(Semantics);
13791 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
13792 NeutralAF.changeSign();
13793
13794 return ConstFP->isExactlyValue(NeutralAF);
13795 }
13796 case ISD::FMINIMUM:
13797 case ISD::FMAXIMUM: {
13798 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
13799 const APFloat &VAPF = ConstFP->getValueAPF();
13800 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
13801 if (Flags.hasNoInfs())
13802 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
13803 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
13804 }
13805 }
13806 }
13807 return false;
13808}
13809
13811 while (V.getOpcode() == ISD::BITCAST)
13812 V = V.getOperand(0);
13813 return V;
13814}
13815
13817 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
13818 V = V.getOperand(0);
13819 return V;
13820}
13821
13823 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13824 V = V.getOperand(0);
13825 return V;
13826}
13827
13829 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13830 SDValue InVec = V.getOperand(0);
13831 SDValue EltNo = V.getOperand(2);
13832 EVT VT = InVec.getValueType();
13833 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
13834 if (IndexC && VT.isFixedLengthVector() &&
13835 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
13836 !DemandedElts[IndexC->getZExtValue()]) {
13837 V = InVec;
13838 continue;
13839 }
13840 break;
13841 }
13842 return V;
13843}
13844
13846 while (V.getOpcode() == ISD::TRUNCATE)
13847 V = V.getOperand(0);
13848 return V;
13849}
13850
13851bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
13852 if (V.getOpcode() != ISD::XOR)
13853 return false;
13854 V = peekThroughBitcasts(V.getOperand(1));
13855 unsigned NumBits = V.getScalarValueSizeInBits();
13856 ConstantSDNode *C =
13857 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
13858 return C && (C->getAPIntValue().countr_one() >= NumBits);
13859}
13860
13862 bool AllowTruncation) {
13863 APInt DemandedElts = getDemandAllEltsMask(N);
13864 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
13865}
13866
13868 bool AllowUndefs,
13869 bool AllowTruncation) {
13871 return CN;
13872
13873 // SplatVectors can truncate their operands. Ignore that case here unless
13874 // AllowTruncation is set.
13875 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
13876 EVT VecEltVT = N->getValueType(0).getVectorElementType();
13877 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13878 EVT CVT = CN->getValueType(0);
13879 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
13880 if (AllowTruncation || CVT == VecEltVT)
13881 return CN;
13882 }
13883 }
13884
13886 BitVector UndefElements;
13887 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
13888
13889 // BuildVectors can truncate their operands. Ignore that case here unless
13890 // AllowTruncation is set.
13891 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13892 if (CN && (UndefElements.none() || AllowUndefs)) {
13893 EVT CVT = CN->getValueType(0);
13894 EVT NSVT = N.getValueType().getScalarType();
13895 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
13896 if (AllowTruncation || (CVT == NSVT))
13897 return CN;
13898 }
13899 }
13900
13901 return nullptr;
13902}
13903
13905 APInt DemandedElts = getDemandAllEltsMask(N);
13906 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
13907}
13908
13910 const APInt &DemandedElts,
13911 bool AllowUndefs) {
13913 return CN;
13914
13916 BitVector UndefElements;
13917 ConstantFPSDNode *CN =
13918 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
13919 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13920 if (CN && (UndefElements.none() || AllowUndefs))
13921 return CN;
13922 }
13923
13924 if (N.getOpcode() == ISD::SPLAT_VECTOR)
13925 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
13926 return CN;
13927
13928 return nullptr;
13929}
13930
13931bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
13932 // TODO: may want to use peekThroughBitcast() here.
13933 ConstantSDNode *C =
13934 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13935 return C && C->isZero();
13936}
13937
13938bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
13939 ConstantSDNode *C =
13940 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
13941 return C && C->isOne();
13942}
13943
13944bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
13945 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13946 return C && C->isOne();
13947}
13948
13949bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
13951 unsigned BitWidth = N.getScalarValueSizeInBits();
13952 ConstantSDNode *C =
13953 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13954 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
13955}
13956
13957bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
13958 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
13959 return C && APInt::isSameValue(C->getAPIntValue(),
13960 APInt(C->getAPIntValue().getBitWidth(), 1));
13961}
13962
13963bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
13965 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
13966 return C && C->isZero();
13967}
13968
13969bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
13970 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13971 return C && C->isZero();
13972}
13973
13977
13979 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
13981 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
13982 bool IsVolatile = false;
13983 bool IsNonTemporal = false;
13984 bool IsDereferenceable = true;
13985 bool IsInvariant = true;
13986 for (const MachineMemOperand *MMO : memoperands()) {
13987 IsVolatile |= MMO->isVolatile();
13988 IsNonTemporal |= MMO->isNonTemporal();
13989 IsDereferenceable &= MMO->isDereferenceable();
13990 IsInvariant &= MMO->isInvariant();
13991 }
13992 MemSDNodeBits.IsVolatile = IsVolatile;
13993 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
13994 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
13995 MemSDNodeBits.IsInvariant = IsInvariant;
13996
13997 // For the single-MMO case, we check here that the size of the memory operand
13998 // fits within the size of the MMO. This is because the MMO might indicate
13999 // only a possible address range instead of specifying the affected memory
14000 // addresses precisely.
14003 getMemOperand()->getSize().getValue())) &&
14004 "Size mismatch!");
14005}
14006
14007namespace {
14008
14009 struct EVTArray {
14010 std::vector<EVT> VTs;
14011
14012 EVTArray() {
14013 VTs.reserve(MVT::VALUETYPE_SIZE);
14014 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14015 VTs.push_back(MVT((MVT::SimpleValueType)i));
14016 }
14017 };
14018
14019} // end anonymous namespace
14020
14021/// getValueTypeList - Return a pointer to the specified value type.
14022///
14023const EVT *SDNode::getValueTypeList(MVT VT) {
14024 static EVTArray SimpleVTArray;
14025
14026 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14027 return &SimpleVTArray.VTs[VT.SimpleTy];
14028}
14029
14030/// hasAnyUseOfValue - Return true if there are any use of the indicated
14031/// value. This method ignores uses of other values defined by this operation.
14032bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14033 assert(Value < getNumValues() && "Bad value!");
14034
14035 for (SDUse &U : uses())
14036 if (U.getResNo() == Value)
14037 return true;
14038
14039 return false;
14040}
14041
14042/// isOnlyUserOf - Return true if this node is the only use of N.
14043bool SDNode::isOnlyUserOf(const SDNode *N) const {
14044 bool Seen = false;
14045 for (const SDNode *User : N->users()) {
14046 if (User == this)
14047 Seen = true;
14048 else
14049 return false;
14050 }
14051
14052 return Seen;
14053}
14054
14055/// Return true if the only users of N are contained in Nodes.
14057 bool Seen = false;
14058 for (const SDNode *User : N->users()) {
14059 if (llvm::is_contained(Nodes, User))
14060 Seen = true;
14061 else
14062 return false;
14063 }
14064
14065 return Seen;
14066}
14067
14068/// Return true if the referenced return value is an operand of N.
14069bool SDValue::isOperandOf(const SDNode *N) const {
14070 return is_contained(N->op_values(), *this);
14071}
14072
14073bool SDNode::isOperandOf(const SDNode *N) const {
14074 return any_of(N->op_values(),
14075 [this](SDValue Op) { return this == Op.getNode(); });
14076}
14077
14078/// reachesChainWithoutSideEffects - Return true if this operand (which must
14079/// be a chain) reaches the specified operand without crossing any
14080/// side-effecting instructions on any chain path. In practice, this looks
14081/// through token factors and non-volatile loads. In order to remain efficient,
14082/// this only looks a couple of nodes in, it does not do an exhaustive search.
14083///
14084/// Note that we only need to examine chains when we're searching for
14085/// side-effects; SelectionDAG requires that all side-effects are represented
14086/// by chains, even if another operand would force a specific ordering. This
14087/// constraint is necessary to allow transformations like splitting loads.
14089 unsigned Depth) const {
14090 if (*this == Dest) return true;
14091
14092 // Don't search too deeply, we just want to be able to see through
14093 // TokenFactor's etc.
14094 if (Depth == 0) return false;
14095
14096 // If this is a token factor, all inputs to the TF happen in parallel.
14097 if (getOpcode() == ISD::TokenFactor) {
14098 // First, try a shallow search.
14099 if (is_contained((*this)->ops(), Dest)) {
14100 // We found the chain we want as an operand of this TokenFactor.
14101 // Essentially, we reach the chain without side-effects if we could
14102 // serialize the TokenFactor into a simple chain of operations with
14103 // Dest as the last operation. This is automatically true if the
14104 // chain has one use: there are no other ordering constraints.
14105 // If the chain has more than one use, we give up: some other
14106 // use of Dest might force a side-effect between Dest and the current
14107 // node.
14108 if (Dest.hasOneUse())
14109 return true;
14110 }
14111 // Next, try a deep search: check whether every operand of the TokenFactor
14112 // reaches Dest.
14113 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14114 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14115 });
14116 }
14117
14118 // Loads don't have side effects, look through them.
14119 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14120 if (Ld->isUnordered())
14121 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14122 }
14123 return false;
14124}
14125
14126bool SDNode::hasPredecessor(const SDNode *N) const {
14129 Worklist.push_back(this);
14130 return hasPredecessorHelper(N, Visited, Worklist);
14131}
14132
14134 this->Flags &= Flags;
14135}
14136
14137SDValue
14139 ArrayRef<ISD::NodeType> CandidateBinOps,
14140 bool AllowPartials) {
14141 // The pattern must end in an extract from index 0.
14142 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14143 !isNullConstant(Extract->getOperand(1)))
14144 return SDValue();
14145
14146 // Match against one of the candidate binary ops.
14147 SDValue Op = Extract->getOperand(0);
14148 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14149 return Op.getOpcode() == unsigned(BinOp);
14150 }))
14151 return SDValue();
14152
14153 // Floating-point reductions may require relaxed constraints on the final step
14154 // of the reduction because they may reorder intermediate operations.
14155 unsigned CandidateBinOp = Op.getOpcode();
14156 if (Op.getValueType().isFloatingPoint()) {
14157 SDNodeFlags Flags = Op->getFlags();
14158 switch (CandidateBinOp) {
14159 case ISD::FADD:
14160 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14161 return SDValue();
14162 break;
14163 default:
14164 llvm_unreachable("Unhandled FP opcode for binop reduction");
14165 }
14166 }
14167
14168 // Matching failed - attempt to see if we did enough stages that a partial
14169 // reduction from a subvector is possible.
14170 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14171 if (!AllowPartials || !Op)
14172 return SDValue();
14173 EVT OpVT = Op.getValueType();
14174 EVT OpSVT = OpVT.getScalarType();
14175 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14176 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14178 return SDValue();
14179 BinOp = (ISD::NodeType)CandidateBinOp;
14180 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14181 };
14182
14183 // At each stage, we're looking for something that looks like:
14184 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14185 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14186 // i32 undef, i32 undef, i32 undef, i32 undef>
14187 // %a = binop <8 x i32> %op, %s
14188 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14189 // we expect something like:
14190 // <4,5,6,7,u,u,u,u>
14191 // <2,3,u,u,u,u,u,u>
14192 // <1,u,u,u,u,u,u,u>
14193 // While a partial reduction match would be:
14194 // <2,3,u,u,u,u,u,u>
14195 // <1,u,u,u,u,u,u,u>
14196 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14197 SDValue PrevOp;
14198 for (unsigned i = 0; i < Stages; ++i) {
14199 unsigned MaskEnd = (1 << i);
14200
14201 if (Op.getOpcode() != CandidateBinOp)
14202 return PartialReduction(PrevOp, MaskEnd);
14203
14204 SDValue Op0 = Op.getOperand(0);
14205 SDValue Op1 = Op.getOperand(1);
14206
14208 if (Shuffle) {
14209 Op = Op1;
14210 } else {
14211 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14212 Op = Op0;
14213 }
14214
14215 // The first operand of the shuffle should be the same as the other operand
14216 // of the binop.
14217 if (!Shuffle || Shuffle->getOperand(0) != Op)
14218 return PartialReduction(PrevOp, MaskEnd);
14219
14220 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14221 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14222 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14223 return PartialReduction(PrevOp, MaskEnd);
14224
14225 PrevOp = Op;
14226 }
14227
14228 // Handle subvector reductions, which tend to appear after the shuffle
14229 // reduction stages.
14230 while (Op.getOpcode() == CandidateBinOp) {
14231 unsigned NumElts = Op.getValueType().getVectorNumElements();
14232 SDValue Op0 = Op.getOperand(0);
14233 SDValue Op1 = Op.getOperand(1);
14234 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14236 Op0.getOperand(0) != Op1.getOperand(0))
14237 break;
14238 SDValue Src = Op0.getOperand(0);
14239 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14240 if (NumSrcElts != (2 * NumElts))
14241 break;
14242 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14243 Op1.getConstantOperandAPInt(1) == NumElts) &&
14244 !(Op1.getConstantOperandAPInt(1) == 0 &&
14245 Op0.getConstantOperandAPInt(1) == NumElts))
14246 break;
14247 Op = Src;
14248 }
14249
14250 BinOp = (ISD::NodeType)CandidateBinOp;
14251 return Op;
14252}
14253
14255 EVT VT = N->getValueType(0);
14256 EVT EltVT = VT.getVectorElementType();
14257 unsigned NE = getMaxRuntimeNumElements(VT);
14258
14259 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14260 reportFatalUsageError("Cannot unroll scalable vector!");
14261
14262 assert(NE && "Nothing to unroll!");
14263 SDLoc dl(N);
14264
14265 // If ResNE is 0, fully unroll the vector op.
14266 if (ResNE == 0)
14267 ResNE = NE;
14268 else if (NE > ResNE)
14269 NE = ResNE;
14270
14271 if (N->getNumValues() == 2) {
14272 SmallVector<SDValue, 8> Scalars0, Scalars1;
14273 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14274 EVT VT1 = N->getValueType(1);
14275 EVT EltVT1 = VT1.getVectorElementType();
14276
14277 unsigned i;
14278 for (i = 0; i != NE; ++i) {
14279 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14280 SDValue Operand = N->getOperand(j);
14281 EVT OperandVT = Operand.getValueType();
14282
14283 // A vector operand; extract a single element.
14284 EVT OperandEltVT = OperandVT.getVectorElementType();
14285 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14286 }
14287
14288 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14289 Scalars0.push_back(EltOp);
14290 Scalars1.push_back(EltOp.getValue(1));
14291 }
14292
14293 for (; i < ResNE; ++i) {
14294 Scalars0.push_back(getUNDEF(EltVT));
14295 Scalars1.push_back(getUNDEF(EltVT1));
14296 }
14297
14299 : ElementCount::getFixed(ResNE);
14300 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14301 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14302 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14303 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14304 return getMergeValues({Vec0, Vec1}, dl);
14305 }
14306
14307 assert(N->getNumValues() == 1 &&
14308 "Can't unroll a vector with multiple results!");
14309
14311 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14312
14313 unsigned i;
14314 for (i= 0; i != NE; ++i) {
14315 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14316 SDValue Operand = N->getOperand(j);
14317 EVT OperandVT = Operand.getValueType();
14318 if (OperandVT.isVector()) {
14319 // A vector operand; extract a single element.
14320 EVT OperandEltVT = OperandVT.getVectorElementType();
14321 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14322 } else {
14323 // A scalar operand; just use it as is.
14324 Operands[j] = Operand;
14325 }
14326 }
14327
14328 switch (N->getOpcode()) {
14329 default: {
14330 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14331 N->getFlags()));
14332 break;
14333 }
14334 case ISD::VSELECT:
14335 Scalars.push_back(
14336 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14337 break;
14338 case ISD::SHL:
14339 case ISD::SRA:
14340 case ISD::SRL:
14341 case ISD::ROTL:
14342 case ISD::ROTR:
14343 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14345 Operands[1])));
14346 break;
14348 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14349 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14350 Operands[0],
14351 getValueType(ExtVT)));
14352 break;
14353 }
14354 case ISD::ADDRSPACECAST: {
14355 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14356 Scalars.push_back(
14357 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14358 ASC->getDestAddressSpace(), ASC->getFlags()));
14359 break;
14360 }
14361 }
14362 }
14363
14364 for (; i < ResNE; ++i)
14365 Scalars.push_back(getUNDEF(EltVT));
14366
14367 EVT VecVT = VT.isScalableVector()
14368 ? VT
14369 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14370 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14371}
14372
14373std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14374 SDNode *N, unsigned ResNE) {
14375 unsigned Opcode = N->getOpcode();
14376 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14377 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14378 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14379 "Expected an overflow opcode");
14380
14381 EVT ResVT = N->getValueType(0);
14382 EVT OvVT = N->getValueType(1);
14383 EVT ResEltVT = ResVT.getVectorElementType();
14384 EVT OvEltVT = OvVT.getVectorElementType();
14385 SDLoc dl(N);
14386
14387 // If ResNE is 0, fully unroll the vector op.
14388 unsigned NE = ResVT.getVectorNumElements();
14389 if (ResNE == 0)
14390 ResNE = NE;
14391 else if (NE > ResNE)
14392 NE = ResNE;
14393
14394 SmallVector<SDValue, 8> LHSScalars;
14395 SmallVector<SDValue, 8> RHSScalars;
14396 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14397 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14398
14399 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14400 SDVTList VTs = getVTList(ResEltVT, SVT);
14401 SmallVector<SDValue, 8> ResScalars;
14402 SmallVector<SDValue, 8> OvScalars;
14403 for (unsigned i = 0; i < NE; ++i) {
14404 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14405 SDValue Ov =
14406 getSelect(dl, OvEltVT, Res.getValue(1),
14407 getBoolConstant(true, dl, OvEltVT, ResVT),
14408 getConstant(0, dl, OvEltVT));
14409
14410 ResScalars.push_back(Res);
14411 OvScalars.push_back(Ov);
14412 }
14413
14414 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14415 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14416
14417 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14418 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14419 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14420 getBuildVector(NewOvVT, dl, OvScalars));
14421}
14422
14425 unsigned Bytes, int Dist,
14426 const SelectionDAG &DAG) {
14427 if (LS->isVolatile() || Base->isVolatile())
14428 return false;
14429 // TODO: probably too restrictive for atomics, revisit
14430 if (!LS->isSimple())
14431 return false;
14432 if (LS->isIndexed() || Base->isIndexed())
14433 return false;
14434 if (LS->getChain() != Base->getChain())
14435 return false;
14436 EVT VT = LS->getMemoryVT();
14437 if (VT.getSizeInBits() / 8 != Bytes)
14438 return false;
14439
14440 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14441 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14442
14443 int64_t Offset = 0;
14444 if (BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14445 return (Dist * (int64_t)Bytes == Offset);
14446 return false;
14447}
14448
14451 unsigned Bytes,
14452 int Dist) const {
14453 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14454}
14455
14458 unsigned Bytes,
14459 int Dist) const {
14460 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14461}
14462
14463/// InferPtrAlignment - Infer alignment of a load / store address. Return
14464/// std::nullopt if it cannot be inferred.
14466 // If this is a GlobalAddress + cst, return the alignment.
14467 const GlobalValue *GV = nullptr;
14468 int64_t GVOffset = 0;
14469 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14470 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14471 KnownBits Known(PtrWidth);
14473 unsigned AlignBits = Known.countMinTrailingZeros();
14474 if (AlignBits)
14475 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
14476 }
14477
14478 // If this is a direct reference to a stack slot, use information about the
14479 // stack slot's alignment.
14480 int FrameIdx = INT_MIN;
14481 int64_t FrameOffset = 0;
14483 FrameIdx = FI->getIndex();
14484 } else if (isBaseWithConstantOffset(Ptr) &&
14486 // Handle FI+Cst
14487 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14488 FrameOffset = Ptr.getConstantOperandVal(1);
14489 }
14490
14491 if (FrameIdx != INT_MIN) {
14493 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14494 }
14495
14496 return std::nullopt;
14497}
14498
14499/// Split the scalar node with EXTRACT_ELEMENT using the provided
14500/// VTs and return the low/high part.
14501std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14502 const SDLoc &DL,
14503 const EVT &LoVT,
14504 const EVT &HiVT) {
14505 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14506 "Split node must be a scalar type");
14507 SDValue Lo =
14509 SDValue Hi =
14511 return std::make_pair(Lo, Hi);
14512}
14513
14514/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14515/// which is split (or expanded) into two not necessarily identical pieces.
14516std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14517 // Currently all types are split in half.
14518 EVT LoVT, HiVT;
14519 if (!VT.isVector())
14520 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14521 else
14522 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14523
14524 return std::make_pair(LoVT, HiVT);
14525}
14526
14527/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14528/// type, dependent on an enveloping VT that has been split into two identical
14529/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14530std::pair<EVT, EVT>
14532 bool *HiIsEmpty) const {
14533 EVT EltTp = VT.getVectorElementType();
14534 // Examples:
14535 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14536 // custom VL=9 with enveloping VL=8/8 yields 8/1
14537 // custom VL=10 with enveloping VL=8/8 yields 8/2
14538 // etc.
14539 ElementCount VTNumElts = VT.getVectorElementCount();
14540 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14541 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14542 "Mixing fixed width and scalable vectors when enveloping a type");
14543 EVT LoVT, HiVT;
14544 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14545 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14546 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14547 *HiIsEmpty = false;
14548 } else {
14549 // Flag that hi type has zero storage size, but return split envelop type
14550 // (this would be easier if vector types with zero elements were allowed).
14551 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14552 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14553 *HiIsEmpty = true;
14554 }
14555 return std::make_pair(LoVT, HiVT);
14556}
14557
14558/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14559/// low/high part.
14560std::pair<SDValue, SDValue>
14561SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14562 const EVT &HiVT) {
14563 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14564 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14565 "Splitting vector with an invalid mixture of fixed and scalable "
14566 "vector types");
14568 N.getValueType().getVectorMinNumElements() &&
14569 "More vector elements requested than available!");
14570 SDValue Lo, Hi;
14571 Lo = getExtractSubvector(DL, LoVT, N, 0);
14572 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14573 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14574 // IDX with the runtime scaling factor of the result vector type. For
14575 // fixed-width result vectors, that runtime scaling factor is 1.
14577 return std::make_pair(Lo, Hi);
14578}
14579
14580std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14581 const SDLoc &DL) {
14582 // Split the vector length parameter.
14583 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14584 EVT VT = N.getValueType();
14586 "Expecting the mask to be an evenly-sized vector");
14587 SDValue HalfNumElts = getElementCount(
14589 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14590 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14591 return std::make_pair(Lo, Hi);
14592}
14593
14594/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14596 EVT VT = N.getValueType();
14599 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14600}
14601
14604 unsigned Start, unsigned Count,
14605 EVT EltVT) {
14606 EVT VT = Op.getValueType();
14607 if (Count == 0)
14609 if (EltVT == EVT())
14610 EltVT = VT.getVectorElementType();
14611 SDLoc SL(Op);
14612 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14613 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14614 }
14615}
14616
14617// getAddressSpace - Return the address space this GlobalAddress belongs to.
14619 return getGlobal()->getType()->getAddressSpace();
14620}
14621
14624 return Val.MachineCPVal->getType();
14625 return Val.ConstVal->getType();
14626}
14627
14628bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14629 unsigned &SplatBitSize,
14630 bool &HasAnyUndefs,
14631 unsigned MinSplatBits,
14632 bool IsBigEndian) const {
14633 EVT VT = getValueType(0);
14634 assert(VT.isVector() && "Expected a vector type");
14635 unsigned VecWidth = VT.getSizeInBits();
14636 if (MinSplatBits > VecWidth)
14637 return false;
14638
14639 // FIXME: The widths are based on this node's type, but build vectors can
14640 // truncate their operands.
14641 SplatValue = APInt(VecWidth, 0);
14642 SplatUndef = APInt(VecWidth, 0);
14643
14644 // Get the bits. Bits with undefined values (when the corresponding element
14645 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14646 // in SplatValue. If any of the values are not constant, give up and return
14647 // false.
14648 unsigned int NumOps = getNumOperands();
14649 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14650 unsigned EltWidth = VT.getScalarSizeInBits();
14651
14652 for (unsigned j = 0; j < NumOps; ++j) {
14653 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14654 SDValue OpVal = getOperand(i);
14655 unsigned BitPos = j * EltWidth;
14656
14657 if (OpVal.isUndef())
14658 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14659 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14660 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14661 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14662 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14663 else
14664 return false;
14665 }
14666
14667 // The build_vector is all constants or undefs. Find the smallest element
14668 // size that splats the vector.
14669 HasAnyUndefs = (SplatUndef != 0);
14670
14671 // FIXME: This does not work for vectors with elements less than 8 bits.
14672 while (VecWidth > 8) {
14673 // If we can't split in half, stop here.
14674 if (VecWidth & 1)
14675 break;
14676
14677 unsigned HalfSize = VecWidth / 2;
14678 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14679 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14680 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14681 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14682
14683 // If the two halves do not match (ignoring undef bits), stop here.
14684 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14685 MinSplatBits > HalfSize)
14686 break;
14687
14688 SplatValue = HighValue | LowValue;
14689 SplatUndef = HighUndef & LowUndef;
14690
14691 VecWidth = HalfSize;
14692 }
14693
14694 // FIXME: The loop above only tries to split in halves. But if the input
14695 // vector for example is <3 x i16> it wouldn't be able to detect a
14696 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14697 // optimizations. I guess that back in the days when this helper was created
14698 // vectors normally was power-of-2 sized.
14699
14700 SplatBitSize = VecWidth;
14701 return true;
14702}
14703
14705 BitVector *UndefElements) const {
14706 unsigned NumOps = getNumOperands();
14707 if (UndefElements) {
14708 UndefElements->clear();
14709 UndefElements->resize(NumOps);
14710 }
14711 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14712 if (!DemandedElts)
14713 return SDValue();
14714 SDValue Splatted;
14715 for (unsigned i = 0; i != NumOps; ++i) {
14716 if (!DemandedElts[i])
14717 continue;
14718 SDValue Op = getOperand(i);
14719 if (Op.isUndef()) {
14720 if (UndefElements)
14721 (*UndefElements)[i] = true;
14722 } else if (!Splatted) {
14723 Splatted = Op;
14724 } else if (Splatted != Op) {
14725 return SDValue();
14726 }
14727 }
14728
14729 if (!Splatted) {
14730 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14731 assert(getOperand(FirstDemandedIdx).isUndef() &&
14732 "Can only have a splat without a constant for all undefs.");
14733 return getOperand(FirstDemandedIdx);
14734 }
14735
14736 return Splatted;
14737}
14738
14740 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14741 return getSplatValue(DemandedElts, UndefElements);
14742}
14743
14745 SmallVectorImpl<SDValue> &Sequence,
14746 BitVector *UndefElements) const {
14747 unsigned NumOps = getNumOperands();
14748 Sequence.clear();
14749 if (UndefElements) {
14750 UndefElements->clear();
14751 UndefElements->resize(NumOps);
14752 }
14753 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14754 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14755 return false;
14756
14757 // Set the undefs even if we don't find a sequence (like getSplatValue).
14758 if (UndefElements)
14759 for (unsigned I = 0; I != NumOps; ++I)
14760 if (DemandedElts[I] && getOperand(I).isUndef())
14761 (*UndefElements)[I] = true;
14762
14763 // Iteratively widen the sequence length looking for repetitions.
14764 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14765 Sequence.append(SeqLen, SDValue());
14766 for (unsigned I = 0; I != NumOps; ++I) {
14767 if (!DemandedElts[I])
14768 continue;
14769 SDValue &SeqOp = Sequence[I % SeqLen];
14771 if (Op.isUndef()) {
14772 if (!SeqOp)
14773 SeqOp = Op;
14774 continue;
14775 }
14776 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14777 Sequence.clear();
14778 break;
14779 }
14780 SeqOp = Op;
14781 }
14782 if (!Sequence.empty())
14783 return true;
14784 }
14785
14786 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14787 return false;
14788}
14789
14791 BitVector *UndefElements) const {
14792 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14793 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14794}
14795
14798 BitVector *UndefElements) const {
14800 getSplatValue(DemandedElts, UndefElements));
14801}
14802
14805 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14806}
14807
14810 BitVector *UndefElements) const {
14812 getSplatValue(DemandedElts, UndefElements));
14813}
14814
14819
14820int32_t
14822 uint32_t BitWidth) const {
14823 if (ConstantFPSDNode *CN =
14825 bool IsExact;
14826 APSInt IntVal(BitWidth);
14827 const APFloat &APF = CN->getValueAPF();
14828 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14829 APFloat::opOK ||
14830 !IsExact)
14831 return -1;
14832
14833 return IntVal.exactLogBase2();
14834 }
14835 return -1;
14836}
14837
14839 bool IsLittleEndian, unsigned DstEltSizeInBits,
14840 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
14841 // Early-out if this contains anything but Undef/Constant/ConstantFP.
14842 if (!isConstant())
14843 return false;
14844
14845 unsigned NumSrcOps = getNumOperands();
14846 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
14847 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14848 "Invalid bitcast scale");
14849
14850 // Extract raw src bits.
14851 SmallVector<APInt> SrcBitElements(NumSrcOps,
14852 APInt::getZero(SrcEltSizeInBits));
14853 BitVector SrcUndeElements(NumSrcOps, false);
14854
14855 for (unsigned I = 0; I != NumSrcOps; ++I) {
14857 if (Op.isUndef()) {
14858 SrcUndeElements.set(I);
14859 continue;
14860 }
14861 auto *CInt = dyn_cast<ConstantSDNode>(Op);
14862 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
14863 assert((CInt || CFP) && "Unknown constant");
14864 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
14865 : CFP->getValueAPF().bitcastToAPInt();
14866 }
14867
14868 // Recast to dst width.
14869 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
14870 SrcBitElements, UndefElements, SrcUndeElements);
14871 return true;
14872}
14873
14874void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
14875 unsigned DstEltSizeInBits,
14876 SmallVectorImpl<APInt> &DstBitElements,
14877 ArrayRef<APInt> SrcBitElements,
14878 BitVector &DstUndefElements,
14879 const BitVector &SrcUndefElements) {
14880 unsigned NumSrcOps = SrcBitElements.size();
14881 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
14882 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14883 "Invalid bitcast scale");
14884 assert(NumSrcOps == SrcUndefElements.size() &&
14885 "Vector size mismatch");
14886
14887 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
14888 DstUndefElements.clear();
14889 DstUndefElements.resize(NumDstOps, false);
14890 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
14891
14892 // Concatenate src elements constant bits together into dst element.
14893 if (SrcEltSizeInBits <= DstEltSizeInBits) {
14894 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
14895 for (unsigned I = 0; I != NumDstOps; ++I) {
14896 DstUndefElements.set(I);
14897 APInt &DstBits = DstBitElements[I];
14898 for (unsigned J = 0; J != Scale; ++J) {
14899 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14900 if (SrcUndefElements[Idx])
14901 continue;
14902 DstUndefElements.reset(I);
14903 const APInt &SrcBits = SrcBitElements[Idx];
14904 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
14905 "Illegal constant bitwidths");
14906 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
14907 }
14908 }
14909 return;
14910 }
14911
14912 // Split src element constant bits into dst elements.
14913 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
14914 for (unsigned I = 0; I != NumSrcOps; ++I) {
14915 if (SrcUndefElements[I]) {
14916 DstUndefElements.set(I * Scale, (I + 1) * Scale);
14917 continue;
14918 }
14919 const APInt &SrcBits = SrcBitElements[I];
14920 for (unsigned J = 0; J != Scale; ++J) {
14921 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14922 APInt &DstBits = DstBitElements[Idx];
14923 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
14924 }
14925 }
14926}
14927
14929 for (const SDValue &Op : op_values()) {
14930 unsigned Opc = Op.getOpcode();
14931 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
14932 return false;
14933 }
14934 return true;
14935}
14936
14937std::optional<std::pair<APInt, APInt>>
14939 unsigned NumOps = getNumOperands();
14940 if (NumOps < 2)
14941 return std::nullopt;
14942
14943 unsigned EltSize = getValueType(0).getScalarSizeInBits();
14944 APInt Start, Stride;
14945 int FirstIdx = -1, SecondIdx = -1;
14946
14947 // Find the first two non-undef constant elements to determine Start and
14948 // Stride, then verify all remaining elements match the sequence.
14949 for (unsigned I = 0; I < NumOps; ++I) {
14951 if (Op->isUndef())
14952 continue;
14953 if (!isa<ConstantSDNode>(Op))
14954 return std::nullopt;
14955
14956 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
14957 if (FirstIdx < 0) {
14958 FirstIdx = I;
14959 Start = Val;
14960 } else if (SecondIdx < 0) {
14961 SecondIdx = I;
14962 // Compute stride using modular arithmetic. Simple division would handle
14963 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
14964 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
14965 // Note that modular arithmetic is agnostic to signed/unsigned.
14966 unsigned IdxDiff = I - FirstIdx;
14967 APInt ValDiff = Val - Start;
14968
14969 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
14970 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
14971 if (ValDiff.countr_zero() < CommonPow2Bits)
14972 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
14973 IdxDiff >>= CommonPow2Bits;
14974 ValDiff.lshrInPlace(CommonPow2Bits);
14975
14976 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
14977 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
14978 // one, but we could try all candidates to handle more cases.
14979 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
14980 if (Stride.isZero())
14981 return std::nullopt;
14982
14983 // Step 3: Adjust Start based on the first defined element's index.
14984 Start -= Stride * FirstIdx;
14985 } else {
14986 // Verify this element matches the sequence.
14987 if (Val != Start + Stride * I)
14988 return std::nullopt;
14989 }
14990 }
14991
14992 // Need at least two defined elements.
14993 if (SecondIdx < 0)
14994 return std::nullopt;
14995
14996 return std::make_pair(Start, Stride);
14997}
14998
15000 // Find the first non-undef value in the shuffle mask.
15001 unsigned i, e;
15002 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15003 /* search */;
15004
15005 // If all elements are undefined, this shuffle can be considered a splat
15006 // (although it should eventually get simplified away completely).
15007 if (i == e)
15008 return true;
15009
15010 // Make sure all remaining elements are either undef or the same as the first
15011 // non-undef value.
15012 for (int Idx = Mask[i]; i != e; ++i)
15013 if (Mask[i] >= 0 && Mask[i] != Idx)
15014 return false;
15015 return true;
15016}
15017
15018// Returns true if it is a constant integer BuildVector or constant integer,
15019// possibly hidden by a bitcast.
15021 SDValue N, bool AllowOpaques) const {
15023
15024 if (auto *C = dyn_cast<ConstantSDNode>(N))
15025 return AllowOpaques || !C->isOpaque();
15026
15028 return true;
15029
15030 // Treat a GlobalAddress supporting constant offset folding as a
15031 // constant integer.
15032 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15033 if (GA->getOpcode() == ISD::GlobalAddress &&
15034 TLI->isOffsetFoldingLegal(GA))
15035 return true;
15036
15037 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15038 isa<ConstantSDNode>(N.getOperand(0)))
15039 return true;
15040 return false;
15041}
15042
15043// Returns true if it is a constant float BuildVector or constant float.
15046 return true;
15047
15049 return true;
15050
15051 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15052 isa<ConstantFPSDNode>(N.getOperand(0)))
15053 return true;
15054
15055 return false;
15056}
15057
15058std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15059 ConstantSDNode *Const =
15060 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15061 if (!Const)
15062 return std::nullopt;
15063
15064 EVT VT = N->getValueType(0);
15065 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15066 switch (TLI->getBooleanContents(N.getValueType())) {
15068 if (CVal.isOne())
15069 return true;
15070 if (CVal.isZero())
15071 return false;
15072 return std::nullopt;
15074 if (CVal.isAllOnes())
15075 return true;
15076 if (CVal.isZero())
15077 return false;
15078 return std::nullopt;
15080 return CVal[0];
15081 }
15082 llvm_unreachable("Unknown BooleanContent enum");
15083}
15084
15085void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15086 assert(!Node->OperandList && "Node already has operands");
15088 "too many operands to fit into SDNode");
15089 SDUse *Ops = OperandRecycler.allocate(
15090 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15091
15092 bool IsDivergent = false;
15093 for (unsigned I = 0; I != Vals.size(); ++I) {
15094 Ops[I].setUser(Node);
15095 Ops[I].setInitial(Vals[I]);
15096 EVT VT = Ops[I].getValueType();
15097
15098 // Skip Chain. It does not carry divergence.
15099 if (VT != MVT::Other &&
15100 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15101 Ops[I].getNode()->isDivergent()) {
15102 IsDivergent = true;
15103 }
15104 }
15105 Node->NumOperands = Vals.size();
15106 Node->OperandList = Ops;
15107 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15108 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15109 Node->SDNodeBits.IsDivergent = IsDivergent;
15110 }
15111 checkForCycles(Node);
15112}
15113
15116 size_t Limit = SDNode::getMaxNumOperands();
15117 while (Vals.size() > Limit) {
15118 unsigned SliceIdx = Vals.size() - Limit;
15119 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15120 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15121 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15122 Vals.emplace_back(NewTF);
15123 }
15124 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15125}
15126
15128 EVT VT, SDNodeFlags Flags) {
15129 switch (Opcode) {
15130 default:
15131 return SDValue();
15132 case ISD::ADD:
15133 case ISD::OR:
15134 case ISD::XOR:
15135 case ISD::UMAX:
15136 case ISD::MUL:
15137 case ISD::AND:
15138 case ISD::UMIN:
15139 case ISD::SMAX:
15140 case ISD::SMIN:
15142 VT);
15143 case ISD::FADD:
15144 // If flags allow, prefer positive zero since it's generally cheaper
15145 // to materialize on most targets.
15146 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15147 case ISD::FMUL:
15148 return getConstantFP(1.0, DL, VT);
15149 case ISD::FMINNUM:
15150 case ISD::FMAXNUM:
15151 case ISD::FMINIMUMNUM:
15152 case ISD::FMAXIMUMNUM: {
15153 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15154 // depending on fast-math flags (FMF).
15155 const fltSemantics &Semantics = VT.getFltSemantics();
15156 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15157 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15158 APFloat::getLargest(Semantics);
15159 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15160 NeutralAF.changeSign();
15161
15162 return getConstantFP(NeutralAF, DL, VT);
15163 }
15164 case ISD::FMINIMUM:
15165 case ISD::FMAXIMUM: {
15166 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15167 const fltSemantics &Semantics = VT.getFltSemantics();
15168 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15169 : APFloat::getLargest(Semantics);
15170 if (Opcode == ISD::FMAXIMUM)
15171 NeutralAF.changeSign();
15172
15173 return getConstantFP(NeutralAF, DL, VT);
15174 }
15175
15176 }
15177}
15178
15180 SDValue Acc, SDValue LHS,
15181 SDValue RHS) {
15182 EVT AccVT = Acc.getValueType();
15183 if (AccVT.isFloatingPoint()) {
15184 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15185 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15186 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15187 }
15189 "Unexpected opcode");
15190 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15191 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15192 return getNegative(MLA, DL, AccVT);
15193}
15194
15195/// Helper used to make a call to a library function that has one argument of
15196/// pointer type.
15197///
15198/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15199/// used to get or set floating-point state. They have one argument of pointer
15200/// type, which points to the memory region containing bits of the
15201/// floating-point state. The value returned by such function is ignored in the
15202/// created call.
15203///
15204/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15205/// \param Ptr Pointer used to save/load state.
15206/// \param InChain Ingoing token chain.
15207/// \returns Outgoing chain token.
15209 SDValue InChain,
15210 const SDLoc &DLoc) {
15211 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15213 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15214 RTLIB::LibcallImpl LibcallImpl =
15215 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15216 if (LibcallImpl == RTLIB::Unsupported)
15217 reportFatalUsageError("emitting call to unsupported libcall");
15218
15219 SDValue Callee =
15220 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15222 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
15223 Libcalls->getLibcallImplCallingConv(LibcallImpl),
15224 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15225 return TLI->LowerCallTo(CLI).second;
15226}
15227
15229 assert(From && To && "Invalid SDNode; empty source SDValue?");
15230 auto I = SDEI.find(From);
15231 if (I == SDEI.end())
15232 return;
15233
15234 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15235 // the iterator, hence the need to make a copy to prevent a use-after-free.
15236 NodeExtraInfo NEI = I->second;
15237 if (LLVM_LIKELY(!NEI.PCSections)) {
15238 // No deep copy required for the types of extra info set.
15239 //
15240 // FIXME: Investigate if other types of extra info also need deep copy. This
15241 // depends on the types of nodes they can be attached to: if some extra info
15242 // is only ever attached to nodes where a replacement To node is always the
15243 // node where later use and propagation of the extra info has the intended
15244 // semantics, no deep copy is required.
15245 SDEI[To] = std::move(NEI);
15246 return;
15247 }
15248
15249 const SDNode *EntrySDN = getEntryNode().getNode();
15250
15251 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15252 // through the replacement of From with To. Otherwise, replacements of a node
15253 // (From) with more complex nodes (To and its operands) may result in lost
15254 // extra info where the root node (To) is insignificant in further propagating
15255 // and using extra info when further lowering to MIR.
15256 //
15257 // In the first step pre-populate the visited set with the nodes reachable
15258 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15259 // DAG that is not new and should be left untouched.
15260 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15261 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15262 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15263 if (MaxDepth == 0) {
15264 // Remember this node in case we need to increase MaxDepth and continue
15265 // populating FromReach from this node.
15266 Leafs.emplace_back(N);
15267 return;
15268 }
15269 if (!FromReach.insert(N).second)
15270 return;
15271 for (const SDValue &Op : N->op_values())
15272 Self(Self, Op.getNode(), MaxDepth - 1);
15273 };
15274
15275 // Copy extra info to To and all its transitive operands (that are new).
15277 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15278 if (FromReach.contains(N))
15279 return true;
15280 if (!Visited.insert(N).second)
15281 return true;
15282 if (EntrySDN == N)
15283 return false;
15284 for (const SDValue &Op : N->op_values()) {
15285 if (N == To && Op.getNode() == EntrySDN) {
15286 // Special case: New node's operand is the entry node; just need to
15287 // copy extra info to new node.
15288 break;
15289 }
15290 if (!Self(Self, Op.getNode()))
15291 return false;
15292 }
15293 // Copy only if entry node was not reached.
15294 SDEI[N] = std::move(NEI);
15295 return true;
15296 };
15297
15298 // We first try with a lower MaxDepth, assuming that the path to common
15299 // operands between From and To is relatively short. This significantly
15300 // improves performance in the common case. The initial MaxDepth is big
15301 // enough to avoid retry in the common case; the last MaxDepth is large
15302 // enough to avoid having to use the fallback below (and protects from
15303 // potential stack exhaustion from recursion).
15304 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15305 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15306 // StartFrom is the previous (or initial) set of leafs reachable at the
15307 // previous maximum depth.
15309 std::swap(StartFrom, Leafs);
15310 for (const SDNode *N : StartFrom)
15311 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15312 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15313 return;
15314 // This should happen very rarely (reached the entry node).
15315 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15316 assert(!Leafs.empty());
15317 }
15318
15319 // This should not happen - but if it did, that means the subgraph reachable
15320 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15321 // could not visit all reachable common operands. Consequently, we were able
15322 // to reach the entry node.
15323 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15324 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15325 // Best-effort fallback if assertions disabled.
15326 SDEI[To] = std::move(NEI);
15327}
15328
15330 assert(VT.isVector() && "Can only unroll vector types!");
15331 if (VT.isFixedLengthVector())
15332 return VT.getVectorNumElements();
15333
15334 const MachineFunction &MF = getMachineFunction();
15335 const Function &F = MF.getFunction();
15336
15337 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15338 if (MaxVScale.ugt(VScaleUnrollLimit))
15339 return 0;
15340
15341 bool Overflow;
15342 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15343 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15344 if (Overflow)
15345 return 0;
15346
15347 return MaxNElts.getZExtValue();
15348}
15349
15351 ArrayRef<SDValue> Scalars) {
15352 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15353 "Element count mismatch!");
15354 if (VT.isFixedLengthVector())
15355 return getBuildVector(VT, DL, Scalars);
15356
15357 SDValue Vec = getPOISON(VT);
15358 // Iterate in reverse so result remains poison until we encounter a lane that
15359 // exists, after which all lower-numbered lanes must also exist.
15360 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15361 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15362
15363 return Vec;
15364}
15365
15366#ifndef NDEBUG
15367static void checkForCyclesHelper(const SDNode *N,
15370 const llvm::SelectionDAG *DAG) {
15371 // If this node has already been checked, don't check it again.
15372 if (Checked.count(N))
15373 return;
15374
15375 // If a node has already been visited on this depth-first walk, reject it as
15376 // a cycle.
15377 if (!Visited.insert(N).second) {
15378 errs() << "Detected cycle in SelectionDAG\n";
15379 dbgs() << "Offending node:\n";
15380 N->dumprFull(DAG); dbgs() << "\n";
15381 abort();
15382 }
15383
15384 for (const SDValue &Op : N->op_values())
15385 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15386
15387 Checked.insert(N);
15388 Visited.erase(N);
15389}
15390#endif
15391
15393 const llvm::SelectionDAG *DAG,
15394 bool force) {
15395#ifndef NDEBUG
15396 bool check = force;
15397#ifdef EXPENSIVE_CHECKS
15398 check = true;
15399#endif // EXPENSIVE_CHECKS
15400 if (check) {
15401 assert(N && "Checking nonexistent SDNode");
15404 checkForCyclesHelper(N, visited, checked, DAG);
15405 }
15406#endif // !NDEBUG
15407}
15408
15409void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15410 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15411}
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
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:609
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:343
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:539
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 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 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 void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, unsigned AS)
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:6010
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:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
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:226
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
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:1533
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:1351
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
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:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:255
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
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:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
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:837
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
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:216
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
static bool isSameValue(const APInt &I1, const APInt &I2, bool SignedCompare=false)
Determine if two APInts have the same value, after zero-extending or sign-extending (if SignedCompare...
Definition APInt.h:551
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:1782
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:830
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:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
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:1388
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
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:1262
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1438
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
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:1242
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:386
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:861
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
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.
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:43
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:305
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:68
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:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
Machine Value Type.
SimpleValueType SimpleTy
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,.
This class contains meta information specific to a module.
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
The optimization diagnostic interface.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
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:911
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 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 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 void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE, Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallsInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, MachineModuleInfo &MMI, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
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
bool hasSwiftErrorArg() const
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
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 makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, const SDLoc &DLoc)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
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 getBasicBlock(MachineBasicBlock *MBB)
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 SDValue getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
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)
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 SDValue getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT SVT, MachineMemOperand *MMO, bool IsCompressing=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.
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.
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.
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
const Triple & getTargetTriple() const
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:722
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:339
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:288
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
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:874
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:255
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:265
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
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:176
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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:252
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
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:3235
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3165
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:3245
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3216
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
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:3225
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3255
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2295
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3207
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:3240
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2300
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
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:24
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:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ TargetConstantPool
Definition ISDOpcodes.h:189
@ 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:513
@ 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:45
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:236
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ 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:540
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ TargetBlockAddress
Definition ISDOpcodes.h:191
@ 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:294
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:524
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ 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:863
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ GlobalAddress
Definition ISDOpcodes.h:88
@ 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:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ 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:749
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:920
@ 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:530
@ 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:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:780
@ 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:89
@ 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:798
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:717
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ TargetExternalSymbol
Definition ISDOpcodes.h:190
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ TargetJumpTable
Definition ISDOpcodes.h:188
@ TargetIndex
TargetIndex - Like a constant pool entry, but with completely target-dependent semantics.
Definition ISDOpcodes.h:198
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ TRUNCATE_SSAT_U
Definition ISDOpcodes.h:883
@ 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:837
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ STEP_VECTOR
STEP_VECTOR(IMM) - Returns a scalable vector whose lanes are comprised of a linear sequence of unsign...
Definition ISDOpcodes.h:693
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:543
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:233
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:69
@ 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:81
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:185
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:802
@ 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:706
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:78
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:48
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:224
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ TargetConstantFP
Definition ISDOpcodes.h:180
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ 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 - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:386
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ ATOMIC_LOAD_FMINIMUM
@ TargetFrameIndex
Definition ISDOpcodes.h:187
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:655
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:909
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ 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.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ 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.
@ 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:785
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:179
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:507
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ 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:737
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:712
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:659
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:304
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:683
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:241
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ 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:797
@ ExternalSymbol
Definition ISDOpcodes.h:93
@ 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:969
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:701
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:931
@ 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:955
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ 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:843
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ TRUNCATE_SSAT_S
TRUNCATE_[SU]SAT_[SU] - Truncate for saturated operand [SU] located in middle, prefix for SAT means i...
Definition ISDOpcodes.h:881
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:724
@ TRUNCATE_USAT_U
Definition ISDOpcodes.h:885
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:338
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:186
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:753
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
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(SDNode *N, const SelectionDAG *DAG, 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:668
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:237
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:1759
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:1739
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:1557
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:2554
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:2208
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:633
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:1539
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:1746
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:407
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:1636
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 void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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...
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:1753
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:149
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:539
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:1885
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:719
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:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
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:197
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:2146
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 isOnesOrOnesSplat(SDValue N, 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 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:763
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:783
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
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:77
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:106
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
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)