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"
51#include "llvm/IR/Constant.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugLoc.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/GlobalValue.h"
59#include "llvm/IR/Metadata.h"
60#include "llvm/IR/Type.h"
64#include "llvm/Support/Debug.h"
74#include <algorithm>
75#include <cassert>
76#include <cstdint>
77#include <cstdlib>
78#include <limits>
79#include <optional>
80#include <string>
81#include <utility>
82#include <vector>
83
84using namespace llvm;
85using namespace llvm::SDPatternMatch;
86
87/// makeVTList - Return an instance of the SDVTList struct initialized with the
88/// specified members.
89static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
90 SDVTList Res = {VTs, NumVTs};
91 return Res;
92}
93
94// Default null implementations of the callbacks.
98
99void SelectionDAG::DAGNodeDeletedListener::anchor() {}
100void SelectionDAG::DAGNodeInsertedListener::anchor() {}
101
102#define DEBUG_TYPE "selectiondag"
103
104static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
105 cl::Hidden, cl::init(true),
106 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
107
108static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
109 cl::desc("Number limit for gluing ld/st of memcpy."),
110 cl::Hidden, cl::init(0));
111
113 MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192),
114 cl::desc("DAG combiner limit number of steps when searching DAG "
115 "for predecessor nodes"));
116
118 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
119}
120
122
123//===----------------------------------------------------------------------===//
124// ConstantFPSDNode Class
125//===----------------------------------------------------------------------===//
126
127/// isExactlyValue - We don't rely on operator== working on double values, as
128/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
129/// As such, this method can be used to do an exact bit-for-bit comparison of
130/// two floating point values.
132 return getValueAPF().bitwiseIsEqual(V);
133}
134
136 const APFloat& Val) {
137 assert(VT.isFloatingPoint() && "Can only convert between FP types");
138
139 // convert modifies in place, so make a copy.
140 APFloat Val2 = APFloat(Val);
141 bool losesInfo;
143 &losesInfo);
144 return !losesInfo;
145}
146
147//===----------------------------------------------------------------------===//
148// ISD Namespace
149//===----------------------------------------------------------------------===//
150
151bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
152 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
153 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
154 unsigned EltSize =
155 N->getValueType(0).getVectorElementType().getSizeInBits();
156 SplatVal = OptAPInt->trunc(EltSize);
157 return true;
158 }
159 }
160
161 auto *BV = dyn_cast<BuildVectorSDNode>(N);
162 if (!BV)
163 return false;
164
165 APInt SplatUndef;
166 unsigned SplatBitSize;
167 bool HasUndefs;
168 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
169 // Endianness does not matter here. We are checking for a splat given the
170 // element size of the vector, and if we find such a splat for little endian
171 // layout, then that should be valid also for big endian (as the full vector
172 // size is known to be a multiple of the element size).
173 const bool IsBigEndian = false;
174 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
175 EltSize, IsBigEndian) &&
176 EltSize == SplatBitSize;
177}
178
179// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
180// specializations of the more general isConstantSplatVector()?
181
182bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
183 // Look through a bit convert.
184 while (N->getOpcode() == ISD::BITCAST)
185 N = N->getOperand(0).getNode();
186
187 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
188 APInt SplatVal;
189 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
190 }
191
192 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
193
194 unsigned i = 0, e = N->getNumOperands();
195
196 // Skip over all of the undef values.
197 while (i != e && N->getOperand(i).isUndef())
198 ++i;
199
200 // Do not accept an all-undef vector.
201 if (i == e) return false;
202
203 // Do not accept build_vectors that aren't all constants or which have non-~0
204 // elements. We have to be a bit careful here, as the type of the constant
205 // may not be the same as the type of the vector elements due to type
206 // legalization (the elements are promoted to a legal type for the target and
207 // a vector of a type may be legal when the base element type is not).
208 // We only want to check enough bits to cover the vector elements, because
209 // we care if the resultant vector is all ones, not whether the individual
210 // constants are.
211 SDValue NotZero = N->getOperand(i);
212 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
213 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
214 if (OptAPInt->countr_one() < EltSize)
215 return false;
216 } else
217 return false;
218
219 // Okay, we have at least one ~0 value, check to see if the rest match or are
220 // undefs. Even with the above element type twiddling, this should be OK, as
221 // the same type legalization should have applied to all the elements.
222 for (++i; i != e; ++i)
223 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
224 return false;
225 return true;
226}
227
228bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
229 // Look through a bit convert.
230 while (N->getOpcode() == ISD::BITCAST)
231 N = N->getOperand(0).getNode();
232
233 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
234 APInt SplatVal;
235 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
236 }
237
238 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
239
240 bool IsAllUndef = true;
241 for (const SDValue &Op : N->op_values()) {
242 if (Op.isUndef())
243 continue;
244 IsAllUndef = false;
245 // Do not accept build_vectors that aren't all constants or which have non-0
246 // elements. We have to be a bit careful here, as the type of the constant
247 // may not be the same as the type of the vector elements due to type
248 // legalization (the elements are promoted to a legal type for the target
249 // and a vector of a type may be legal when the base element type is not).
250 // We only want to check enough bits to cover the vector elements, because
251 // we care if the resultant vector is all zeros, not whether the individual
252 // constants are.
253 if (auto OptAPInt = Op->bitcastToAPInt()) {
254 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
255 if (OptAPInt->countr_zero() < EltSize)
256 return false;
257 } else
258 return false;
259 }
260
261 // Do not accept an all-undef vector.
262 if (IsAllUndef)
263 return false;
264 return true;
265}
266
268 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
269}
270
272 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
273}
274
276 if (N->getOpcode() != ISD::BUILD_VECTOR)
277 return false;
278
279 for (const SDValue &Op : N->op_values()) {
280 if (Op.isUndef())
281 continue;
283 return false;
284 }
285 return true;
286}
287
289 if (N->getOpcode() != ISD::BUILD_VECTOR)
290 return false;
291
292 for (const SDValue &Op : N->op_values()) {
293 if (Op.isUndef())
294 continue;
296 return false;
297 }
298 return true;
299}
300
301bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
302 bool Signed) {
303 assert(N->getValueType(0).isVector() && "Expected a vector!");
304
305 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
306 if (EltSize <= NewEltSize)
307 return false;
308
309 if (N->getOpcode() == ISD::ZERO_EXTEND) {
310 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
311 NewEltSize) &&
312 !Signed;
313 }
314 if (N->getOpcode() == ISD::SIGN_EXTEND) {
315 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
316 NewEltSize) &&
317 Signed;
318 }
319 if (N->getOpcode() != ISD::BUILD_VECTOR)
320 return false;
321
322 for (const SDValue &Op : N->op_values()) {
323 if (Op.isUndef())
324 continue;
326 return false;
327
328 APInt C = Op->getAsAPIntVal().trunc(EltSize);
329 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
330 return false;
331 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
332 return false;
333 }
334
335 return true;
336}
337
339 // Return false if the node has no operands.
340 // This is "logically inconsistent" with the definition of "all" but
341 // is probably the desired behavior.
342 if (N->getNumOperands() == 0)
343 return false;
344 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
345}
346
348 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
349}
350
351template <typename ConstNodeType>
353 std::function<bool(ConstNodeType *)> Match,
354 bool AllowUndefs, bool AllowTruncation) {
355 // FIXME: Add support for scalar UNDEF cases?
356 if (auto *C = dyn_cast<ConstNodeType>(Op))
357 return Match(C);
358
359 // FIXME: Add support for vector UNDEF cases?
360 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
361 ISD::SPLAT_VECTOR != Op.getOpcode())
362 return false;
363
364 EVT SVT = Op.getValueType().getScalarType();
365 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
366 if (AllowUndefs && Op.getOperand(i).isUndef()) {
367 if (!Match(nullptr))
368 return false;
369 continue;
370 }
371
372 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
373 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
374 !Match(Cst))
375 return false;
376 }
377 return true;
378}
379// Build used template types.
381 SDValue, std::function<bool(ConstantSDNode *)>, bool, bool);
383 SDValue, std::function<bool(ConstantFPSDNode *)>, bool, bool);
384
386 SDValue LHS, SDValue RHS,
387 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
388 bool AllowUndefs, bool AllowTypeMismatch) {
389 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
390 return false;
391
392 // TODO: Add support for scalar UNDEF cases?
393 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
394 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
395 return Match(LHSCst, RHSCst);
396
397 // TODO: Add support for vector UNDEF cases?
398 if (LHS.getOpcode() != RHS.getOpcode() ||
399 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
400 LHS.getOpcode() != ISD::SPLAT_VECTOR))
401 return false;
402
403 EVT SVT = LHS.getValueType().getScalarType();
404 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
405 SDValue LHSOp = LHS.getOperand(i);
406 SDValue RHSOp = RHS.getOperand(i);
407 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
408 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
409 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
410 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
411 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
412 return false;
413 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
414 LHSOp.getValueType() != RHSOp.getValueType()))
415 return false;
416 if (!Match(LHSCst, RHSCst))
417 return false;
418 }
419 return true;
420}
421
423 switch (MinMaxOpc) {
424 default:
425 llvm_unreachable("unrecognized opcode");
426 case ISD::UMIN:
427 return ISD::UMAX;
428 case ISD::UMAX:
429 return ISD::UMIN;
430 case ISD::SMIN:
431 return ISD::SMAX;
432 case ISD::SMAX:
433 return ISD::SMIN;
434 }
435}
436
438 switch (MinMaxOpc) {
439 default:
440 llvm_unreachable("unrecognized min/max opcode");
441 case ISD::SMIN:
442 return ISD::UMIN;
443 case ISD::SMAX:
444 return ISD::UMAX;
445 case ISD::UMIN:
446 return ISD::SMIN;
447 case ISD::UMAX:
448 return ISD::SMAX;
449 }
450}
451
453 switch (VecReduceOpcode) {
454 default:
455 llvm_unreachable("Expected VECREDUCE opcode");
458 case ISD::VP_REDUCE_FADD:
459 case ISD::VP_REDUCE_SEQ_FADD:
460 return ISD::FADD;
463 case ISD::VP_REDUCE_FMUL:
464 case ISD::VP_REDUCE_SEQ_FMUL:
465 return ISD::FMUL;
467 case ISD::VP_REDUCE_ADD:
468 return ISD::ADD;
470 case ISD::VP_REDUCE_MUL:
471 return ISD::MUL;
473 case ISD::VP_REDUCE_AND:
474 return ISD::AND;
476 case ISD::VP_REDUCE_OR:
477 return ISD::OR;
479 case ISD::VP_REDUCE_XOR:
480 return ISD::XOR;
482 case ISD::VP_REDUCE_SMAX:
483 return ISD::SMAX;
485 case ISD::VP_REDUCE_SMIN:
486 return ISD::SMIN;
488 case ISD::VP_REDUCE_UMAX:
489 return ISD::UMAX;
491 case ISD::VP_REDUCE_UMIN:
492 return ISD::UMIN;
494 case ISD::VP_REDUCE_FMAX:
495 return ISD::FMAXNUM;
497 case ISD::VP_REDUCE_FMIN:
498 return ISD::FMINNUM;
500 case ISD::VP_REDUCE_FMAXIMUM:
501 return ISD::FMAXIMUM;
503 case ISD::VP_REDUCE_FMINIMUM:
504 return ISD::FMINIMUM;
505 }
506}
507
509 switch (MaskedOpc) {
510 case ISD::MASKED_UDIV:
511 return ISD::UDIV;
512 case ISD::MASKED_SDIV:
513 return ISD::SDIV;
514 case ISD::MASKED_UREM:
515 return ISD::UREM;
516 case ISD::MASKED_SREM:
517 return ISD::SREM;
518 default:
519 llvm_unreachable("Expected masked binop opcode");
520 }
521}
522
523bool ISD::isVPOpcode(unsigned Opcode) {
524 switch (Opcode) {
525 default:
526 return false;
527#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
528 case ISD::VPSD: \
529 return true;
530#include "llvm/IR/VPIntrinsics.def"
531 }
532}
533
534bool ISD::isVPBinaryOp(unsigned Opcode) {
535 switch (Opcode) {
536 default:
537 break;
538#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
539#define VP_PROPERTY_BINARYOP return true;
540#define END_REGISTER_VP_SDNODE(VPSD) break;
541#include "llvm/IR/VPIntrinsics.def"
542 }
543 return false;
544}
545
546bool ISD::isVPReduction(unsigned Opcode) {
547 switch (Opcode) {
548 default:
549 return false;
550 case ISD::VP_REDUCE_ADD:
551 case ISD::VP_REDUCE_MUL:
552 case ISD::VP_REDUCE_AND:
553 case ISD::VP_REDUCE_OR:
554 case ISD::VP_REDUCE_XOR:
555 case ISD::VP_REDUCE_SMAX:
556 case ISD::VP_REDUCE_SMIN:
557 case ISD::VP_REDUCE_UMAX:
558 case ISD::VP_REDUCE_UMIN:
559 case ISD::VP_REDUCE_FMAX:
560 case ISD::VP_REDUCE_FMIN:
561 case ISD::VP_REDUCE_FMAXIMUM:
562 case ISD::VP_REDUCE_FMINIMUM:
563 case ISD::VP_REDUCE_FADD:
564 case ISD::VP_REDUCE_FMUL:
565 case ISD::VP_REDUCE_SEQ_FADD:
566 case ISD::VP_REDUCE_SEQ_FMUL:
567 return true;
568 }
569}
570
571/// The operand position of the vector mask.
572std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
573 switch (Opcode) {
574 default:
575 return std::nullopt;
576#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
577 case ISD::VPSD: \
578 return MASKPOS;
579#include "llvm/IR/VPIntrinsics.def"
580 }
581}
582
583/// The operand position of the explicit vector length parameter.
584std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
585 switch (Opcode) {
586 default:
587 return std::nullopt;
588#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
589 case ISD::VPSD: \
590 return EVLPOS;
591#include "llvm/IR/VPIntrinsics.def"
592 }
593}
594
595std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
596 bool hasFPExcept) {
597 // FIXME: Return strict opcodes in case of fp exceptions.
598 switch (VPOpcode) {
599 default:
600 return std::nullopt;
601#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
602#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
603#define END_REGISTER_VP_SDNODE(VPOPC) break;
604#include "llvm/IR/VPIntrinsics.def"
605 }
606 return std::nullopt;
607}
608
609std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
610 switch (Opcode) {
611 default:
612 return std::nullopt;
613#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
614#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
615#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
616#include "llvm/IR/VPIntrinsics.def"
617 }
618}
619
621 switch (ExtType) {
622 case ISD::EXTLOAD:
623 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
624 case ISD::SEXTLOAD:
625 return ISD::SIGN_EXTEND;
626 case ISD::ZEXTLOAD:
627 return ISD::ZERO_EXTEND;
628 default:
629 break;
630 }
631
632 llvm_unreachable("Invalid LoadExtType");
633}
634
636 // To perform this operation, we just need to swap the L and G bits of the
637 // operation.
638 unsigned OldL = (Operation >> 2) & 1;
639 unsigned OldG = (Operation >> 1) & 1;
640 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
641 (OldL << 1) | // New G bit
642 (OldG << 2)); // New L bit.
643}
644
646 unsigned Operation = Op;
647 if (isIntegerLike)
648 Operation ^= 7; // Flip L, G, E bits, but not U.
649 else
650 Operation ^= 15; // Flip all of the condition bits.
651
653 Operation &= ~8; // Don't let N and U bits get set.
654
655 return ISD::CondCode(Operation);
656}
657
661
663 bool isIntegerLike) {
664 return getSetCCInverseImpl(Op, isIntegerLike);
665}
666
667/// For an integer comparison, return 1 if the comparison is a signed operation
668/// and 2 if the result is an unsigned comparison. Return zero if the operation
669/// does not depend on the sign of the input (setne and seteq).
670static int isSignedOp(ISD::CondCode Opcode) {
671 switch (Opcode) {
672 default: llvm_unreachable("Illegal integer setcc operation!");
673 case ISD::SETEQ:
674 case ISD::SETNE: return 0;
675 case ISD::SETLT:
676 case ISD::SETLE:
677 case ISD::SETGT:
678 case ISD::SETGE: return 1;
679 case ISD::SETULT:
680 case ISD::SETULE:
681 case ISD::SETUGT:
682 case ISD::SETUGE: return 2;
683 }
684}
685
687 EVT Type) {
688 bool IsInteger = Type.isInteger();
689 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
690 // Cannot fold a signed integer setcc with an unsigned integer setcc.
691 return ISD::SETCC_INVALID;
692
693 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
694
695 // If the N and U bits get set, then the resultant comparison DOES suddenly
696 // care about orderedness, and it is true when ordered.
697 if (Op > ISD::SETTRUE2)
698 Op &= ~16; // Clear the U bit if the N bit is set.
699
700 // Canonicalize illegal integer setcc's.
701 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
702 Op = ISD::SETNE;
703
704 return ISD::CondCode(Op);
705}
706
708 EVT Type) {
709 bool IsInteger = Type.isInteger();
710 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
711 // Cannot fold a signed setcc with an unsigned setcc.
712 return ISD::SETCC_INVALID;
713
714 // Combine all of the condition bits.
715 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
716
717 // Canonicalize illegal integer setcc's.
718 if (IsInteger) {
719 switch (Result) {
720 default: break;
721 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
722 case ISD::SETOEQ: // SETEQ & SETU[LG]E
723 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
724 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
725 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
726 }
727 }
728
729 return Result;
730}
731
732//===----------------------------------------------------------------------===//
733// SDNode Profile Support
734//===----------------------------------------------------------------------===//
735
736/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
737static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
738 ID.AddInteger(OpC);
739}
740
741/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
742/// solely with their pointer.
744 ID.AddPointer(VTList.VTs);
745}
746
747/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
750 for (const auto &Op : Ops) {
751 ID.AddPointer(Op.getNode());
752 ID.AddInteger(Op.getResNo());
753 }
754}
755
756/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
759 for (const auto &Op : Ops) {
760 ID.AddPointer(Op.getNode());
761 ID.AddInteger(Op.getResNo());
762 }
763}
764
765static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
766 SDVTList VTList, ArrayRef<SDValue> OpList) {
767 AddNodeIDOpcode(ID, OpC);
768 AddNodeIDValueTypes(ID, VTList);
769 AddNodeIDOperands(ID, OpList);
770}
771
772/// If this is an SDNode with special info, add this info to the NodeID data.
773static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
774 switch (N->getOpcode()) {
777 case ISD::MCSymbol:
778 llvm_unreachable("Should only be used on nodes with operands");
779 default: break; // Normal nodes don't need extra info.
781 case ISD::Constant: {
783 ID.AddPointer(C->getConstantIntValue());
784 ID.AddBoolean(C->isOpaque());
785 break;
786 }
788 case ISD::ConstantFP:
789 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
790 break;
796 ID.AddPointer(GA->getGlobal());
797 ID.AddInteger(GA->getOffset());
798 ID.AddInteger(GA->getTargetFlags());
799 break;
800 }
801 case ISD::BasicBlock:
802 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
803 break;
804 case ISD::Register:
805 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
806 break;
808 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
809 break;
810 case ISD::SRCVALUE:
811 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
812 break;
813 case ISD::FrameIndex:
815 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
816 break;
818 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
819 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
820 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
821 break;
822 case ISD::JumpTable:
824 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
825 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
826 break;
830 ID.AddInteger(CP->getAlign().value());
831 ID.AddInteger(CP->getOffset());
834 else
835 ID.AddPointer(CP->getConstVal());
836 ID.AddInteger(CP->getTargetFlags());
837 break;
838 }
839 case ISD::TargetIndex: {
841 ID.AddInteger(TI->getIndex());
842 ID.AddInteger(TI->getOffset());
843 ID.AddInteger(TI->getTargetFlags());
844 break;
845 }
846 case ISD::LOAD: {
847 const LoadSDNode *LD = cast<LoadSDNode>(N);
848 ID.AddInteger(LD->getMemoryVT().getRawBits());
849 ID.AddInteger(LD->getRawSubclassData());
850 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
851 ID.AddInteger(LD->getMemOperand()->getFlags());
852 break;
853 }
854 case ISD::STORE: {
855 const StoreSDNode *ST = cast<StoreSDNode>(N);
856 ID.AddInteger(ST->getMemoryVT().getRawBits());
857 ID.AddInteger(ST->getRawSubclassData());
858 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
859 ID.AddInteger(ST->getMemOperand()->getFlags());
860 break;
861 }
862 case ISD::VP_LOAD: {
863 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
864 ID.AddInteger(ELD->getMemoryVT().getRawBits());
865 ID.AddInteger(ELD->getRawSubclassData());
866 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
867 ID.AddInteger(ELD->getMemOperand()->getFlags());
868 break;
869 }
870 case ISD::VP_LOAD_FF: {
871 const auto *LD = cast<VPLoadFFSDNode>(N);
872 ID.AddInteger(LD->getMemoryVT().getRawBits());
873 ID.AddInteger(LD->getRawSubclassData());
874 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
875 ID.AddInteger(LD->getMemOperand()->getFlags());
876 break;
877 }
878 case ISD::VP_STORE: {
879 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
880 ID.AddInteger(EST->getMemoryVT().getRawBits());
881 ID.AddInteger(EST->getRawSubclassData());
882 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
883 ID.AddInteger(EST->getMemOperand()->getFlags());
884 break;
885 }
886 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
888 ID.AddInteger(SLD->getMemoryVT().getRawBits());
889 ID.AddInteger(SLD->getRawSubclassData());
890 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
891 break;
892 }
893 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
895 ID.AddInteger(SST->getMemoryVT().getRawBits());
896 ID.AddInteger(SST->getRawSubclassData());
897 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
898 break;
899 }
900 case ISD::VP_GATHER: {
902 ID.AddInteger(EG->getMemoryVT().getRawBits());
903 ID.AddInteger(EG->getRawSubclassData());
904 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
905 ID.AddInteger(EG->getMemOperand()->getFlags());
906 break;
907 }
908 case ISD::VP_SCATTER: {
910 ID.AddInteger(ES->getMemoryVT().getRawBits());
911 ID.AddInteger(ES->getRawSubclassData());
912 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
913 ID.AddInteger(ES->getMemOperand()->getFlags());
914 break;
915 }
916 case ISD::MLOAD: {
918 ID.AddInteger(MLD->getMemoryVT().getRawBits());
919 ID.AddInteger(MLD->getRawSubclassData());
920 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
921 ID.AddInteger(MLD->getMemOperand()->getFlags());
922 break;
923 }
924 case ISD::MSTORE: {
926 ID.AddInteger(MST->getMemoryVT().getRawBits());
927 ID.AddInteger(MST->getRawSubclassData());
928 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
929 ID.AddInteger(MST->getMemOperand()->getFlags());
930 break;
931 }
932 case ISD::MGATHER: {
934 ID.AddInteger(MG->getMemoryVT().getRawBits());
935 ID.AddInteger(MG->getRawSubclassData());
936 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
937 ID.AddInteger(MG->getMemOperand()->getFlags());
938 break;
939 }
940 case ISD::MSCATTER: {
942 ID.AddInteger(MS->getMemoryVT().getRawBits());
943 ID.AddInteger(MS->getRawSubclassData());
944 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
945 ID.AddInteger(MS->getMemOperand()->getFlags());
946 break;
947 }
950 case ISD::ATOMIC_SWAP:
962 case ISD::ATOMIC_LOAD:
963 case ISD::ATOMIC_STORE: {
964 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
965 ID.AddInteger(AT->getMemoryVT().getRawBits());
966 ID.AddInteger(AT->getRawSubclassData());
967 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
968 ID.AddInteger(AT->getMemOperand()->getFlags());
969 break;
970 }
971 case ISD::VECTOR_SHUFFLE: {
972 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
973 for (int M : Mask)
974 ID.AddInteger(M);
975 break;
976 }
977 case ISD::ADDRSPACECAST: {
979 ID.AddInteger(ASC->getSrcAddressSpace());
980 ID.AddInteger(ASC->getDestAddressSpace());
981 break;
982 }
984 case ISD::BlockAddress: {
986 ID.AddPointer(BA->getBlockAddress());
987 ID.AddInteger(BA->getOffset());
988 ID.AddInteger(BA->getTargetFlags());
989 break;
990 }
991 case ISD::AssertAlign:
992 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
993 break;
994 case ISD::PREFETCH:
997 // Handled by MemIntrinsicSDNode check after the switch.
998 break;
1000 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
1001 break;
1002 } // end switch (N->getOpcode())
1003
1004 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
1005 // to check.
1006 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
1007 ID.AddInteger(MN->getRawSubclassData());
1008 ID.AddInteger(MN->getMemoryVT().getRawBits());
1009 for (const MachineMemOperand *MMO : MN->memoperands()) {
1010 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1011 ID.AddInteger(MMO->getFlags());
1012 }
1013 }
1014}
1015
1016/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
1017/// data.
1018static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1019 AddNodeIDOpcode(ID, N->getOpcode());
1020 // Add the return value info.
1021 AddNodeIDValueTypes(ID, N->getVTList());
1022 // Add the operand info.
1023 AddNodeIDOperands(ID, N->ops());
1024
1025 // Handle SDNode leafs with special info.
1026 AddNodeIDCustom(ID, N);
1027}
1028
1029//===----------------------------------------------------------------------===//
1030// SelectionDAG Class
1031//===----------------------------------------------------------------------===//
1032
1033/// doNotCSE - Return true if CSE should not be performed for this node.
1034static bool doNotCSE(SDNode *N) {
1035 if (N->getValueType(0) == MVT::Glue)
1036 return true; // Never CSE anything that produces a glue result.
1037
1038 switch (N->getOpcode()) {
1039 default: break;
1040 case ISD::HANDLENODE:
1041 case ISD::EH_LABEL:
1042 return true; // Never CSE these nodes.
1043 }
1044
1045 // Check that remaining values produced are not flags.
1046 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1047 if (N->getValueType(i) == MVT::Glue)
1048 return true; // Never CSE anything that produces a glue result.
1049
1050 return false;
1051}
1052
1053/// Construct a DemandedElts mask which demands all elements of \p V.
1054/// If \p V is not a fixed-length vector, then this will return a single bit.
1056 EVT VT = V.getValueType();
1057 // Since the number of lanes in a scalable vector is unknown at compile time,
1058 // we track one bit which is implicitly broadcast to all lanes. This means
1059 // that all lanes in a scalable vector are considered demanded.
1061 : APInt(1, 1);
1062}
1063
1064/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1065/// SelectionDAG.
1067 // Create a dummy node (which is not added to allnodes), that adds a reference
1068 // to the root node, preventing it from being deleted.
1069 HandleSDNode Dummy(getRoot());
1070
1071 SmallVector<SDNode*, 128> DeadNodes;
1072
1073 // Add all obviously-dead nodes to the DeadNodes worklist.
1074 for (SDNode &Node : allnodes())
1075 if (Node.use_empty())
1076 DeadNodes.push_back(&Node);
1077
1078 RemoveDeadNodes(DeadNodes);
1079
1080 // If the root changed (e.g. it was a dead load, update the root).
1081 setRoot(Dummy.getValue());
1082}
1083
1084/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1085/// given list, and any nodes that become unreachable as a result.
1087
1088 // Process the worklist, deleting the nodes and adding their uses to the
1089 // worklist.
1090 while (!DeadNodes.empty()) {
1091 SDNode *N = DeadNodes.pop_back_val();
1092 // Skip to next node if we've already managed to delete the node. This could
1093 // happen if replacing a node causes a node previously added to the node to
1094 // be deleted.
1095 if (N->getOpcode() == ISD::DELETED_NODE)
1096 continue;
1097
1098 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1099 DUL->NodeDeleted(N, nullptr);
1100
1101 // Take the node out of the appropriate CSE map.
1102 RemoveNodeFromCSEMaps(N);
1103
1104 // Next, brutally remove the operand list. This is safe to do, as there are
1105 // no cycles in the graph.
1106 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1107 SDUse &Use = *I++;
1108 SDNode *Operand = Use.getNode();
1109 Use.set(SDValue());
1110
1111 // Now that we removed this operand, see if there are no uses of it left.
1112 if (Operand->use_empty())
1113 DeadNodes.push_back(Operand);
1114 }
1115
1116 DeallocateNode(N);
1117 }
1118}
1119
1121 SmallVector<SDNode*, 16> DeadNodes(1, N);
1122
1123 // Create a dummy node that adds a reference to the root node, preventing
1124 // it from being deleted. (This matters if the root is an operand of the
1125 // dead node.)
1126 HandleSDNode Dummy(getRoot());
1127
1128 RemoveDeadNodes(DeadNodes);
1129}
1130
1132 // First take this out of the appropriate CSE map.
1133 RemoveNodeFromCSEMaps(N);
1134
1135 // Finally, remove uses due to operands of this node, remove from the
1136 // AllNodes list, and delete the node.
1137 DeleteNodeNotInCSEMaps(N);
1138}
1139
1140void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1141 assert(N->getIterator() != AllNodes.begin() &&
1142 "Cannot delete the entry node!");
1143 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1144
1145 // Drop all of the operands and decrement used node's use counts.
1146 N->DropOperands();
1147
1148 DeallocateNode(N);
1149}
1150
1151void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1152 assert(!(V->isVariadic() && isParameter));
1153 if (isParameter)
1154 ByvalParmDbgValues.push_back(V);
1155 else
1156 DbgValues.push_back(V);
1157 for (const SDNode *Node : V->getSDNodes())
1158 if (Node)
1159 DbgValMap[Node].push_back(V);
1160}
1161
1163 DbgValMapType::iterator I = DbgValMap.find(Node);
1164 if (I == DbgValMap.end())
1165 return;
1166 for (auto &Val: I->second)
1167 Val->setIsInvalidated();
1168 DbgValMap.erase(I);
1169}
1170
1171void SelectionDAG::DeallocateNode(SDNode *N) {
1172 // If we have operands, deallocate them.
1174
1175 NodeAllocator.Deallocate(AllNodes.remove(N));
1176
1177 // Set the opcode to DELETED_NODE to help catch bugs when node
1178 // memory is reallocated.
1179 // FIXME: There are places in SDag that have grown a dependency on the opcode
1180 // value in the released node.
1181 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1182 N->NodeType = ISD::DELETED_NODE;
1183
1184 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1185 // them and forget about that node.
1186 DbgInfo->erase(N);
1187
1188 // Invalidate extra info.
1189 SDEI.erase(N);
1190}
1191
1192#ifndef NDEBUG
1193/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1194void SelectionDAG::verifyNode(SDNode *N) const {
1195 switch (N->getOpcode()) {
1196 default:
1197 if (N->isTargetOpcode())
1199 break;
1200 case ISD::BUILD_PAIR: {
1201 EVT VT = N->getValueType(0);
1202 assert(N->getNumValues() == 1 && "Too many results!");
1203 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1204 "Wrong return type!");
1205 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1206 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1207 "Mismatched operand types!");
1208 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1209 "Wrong operand type!");
1210 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1211 "Wrong return type size");
1212 break;
1213 }
1214 case ISD::BUILD_VECTOR: {
1215 assert(N->getNumValues() == 1 && "Too many results!");
1216 assert(N->getValueType(0).isVector() && "Wrong return type!");
1217 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1218 "Wrong number of operands!");
1219 EVT EltVT = N->getValueType(0).getVectorElementType();
1220 for (const SDUse &Op : N->ops()) {
1221 assert((Op.getValueType() == EltVT ||
1222 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1223 EltVT.bitsLE(Op.getValueType()))) &&
1224 "Wrong operand type!");
1225 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1226 "Operands must all have the same type");
1227 }
1228 break;
1229 }
1230 case ISD::SADDO:
1231 case ISD::UADDO:
1232 case ISD::SSUBO:
1233 case ISD::USUBO:
1234 assert(N->getNumValues() == 2 && "Wrong number of results!");
1235 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1236 "Invalid add/sub overflow op!");
1237 assert(N->getVTList().VTs[0].isInteger() &&
1238 N->getVTList().VTs[1].isInteger() &&
1239 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1240 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1241 "Binary operator types must match!");
1242 break;
1243 }
1244}
1245#endif // NDEBUG
1246
1247/// Insert a newly allocated node into the DAG.
1248///
1249/// Handles insertion into the all nodes list and CSE map, as well as
1250/// verification and other common operations when a new node is allocated.
1251void SelectionDAG::InsertNode(SDNode *N) {
1252 AllNodes.push_back(N);
1253#ifndef NDEBUG
1254 N->PersistentId = NextPersistentId++;
1255 verifyNode(N);
1256#endif
1257 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1258 DUL->NodeInserted(N);
1259}
1260
1261/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1262/// correspond to it. This is useful when we're about to delete or repurpose
1263/// the node. We don't want future request for structurally identical nodes
1264/// to return N anymore.
1265bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1266 bool Erased = false;
1267 switch (N->getOpcode()) {
1268 case ISD::HANDLENODE: return false; // noop.
1269 case ISD::CONDCODE:
1270 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1271 "Cond code doesn't exist!");
1272 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1273 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1274 break;
1276 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1277 break;
1279 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1280 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1281 ESN->getSymbol(), ESN->getTargetFlags()));
1282 break;
1283 }
1284 case ISD::MCSymbol: {
1285 auto *MCSN = cast<MCSymbolSDNode>(N);
1286 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1287 break;
1288 }
1289 case ISD::VALUETYPE: {
1290 EVT VT = cast<VTSDNode>(N)->getVT();
1291 if (VT.isExtended()) {
1292 Erased = ExtendedValueTypeNodes.erase(VT);
1293 } else {
1294 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1295 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1296 }
1297 break;
1298 }
1299 default:
1300 // Remove it from the CSE Map.
1301 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1302 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1303 Erased = CSEMap.RemoveNode(N);
1304 break;
1305 }
1306#ifndef NDEBUG
1307 // Verify that the node was actually in one of the CSE maps, unless it has a
1308 // glue result (which cannot be CSE'd) or is one of the special cases that are
1309 // not subject to CSE.
1310 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1311 !N->isMachineOpcode() && !doNotCSE(N)) {
1312 N->dump(this);
1313 dbgs() << "\n";
1314 llvm_unreachable("Node is not in map!");
1315 }
1316#endif
1317 return Erased;
1318}
1319
1320/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1321/// maps and modified in place. Add it back to the CSE maps, unless an identical
1322/// node already exists, in which case transfer all its users to the existing
1323/// node. This transfer can potentially trigger recursive merging.
1324void
1325SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1326 // For node types that aren't CSE'd, just act as if no identical node
1327 // already exists.
1328 if (!doNotCSE(N)) {
1329 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1330 if (Existing != N) {
1331 // If there was already an existing matching node, use ReplaceAllUsesWith
1332 // to replace the dead one with the existing one. This can cause
1333 // recursive merging of other unrelated nodes down the line.
1334 Existing->intersectFlagsWith(N->getFlags());
1335 if (auto *MemNode = dyn_cast<MemSDNode>(Existing))
1336 MemNode->refineRanges(cast<MemSDNode>(N)->memoperands());
1337 ReplaceAllUsesWith(N, Existing);
1338
1339 // N is now dead. Inform the listeners and delete it.
1340 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1341 DUL->NodeDeleted(N, Existing);
1342 DeleteNodeNotInCSEMaps(N);
1343 return;
1344 }
1345 }
1346
1347 // If the node doesn't already exist, we updated it. Inform listeners.
1348 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1349 DUL->NodeUpdated(N);
1350}
1351
1352/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1353/// were replaced with those specified. If this node is never memoized,
1354/// return null, otherwise return a pointer to the slot it would take. If a
1355/// node already exists with these operands, the slot will be non-null.
1356SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1357 void *&InsertPos) {
1358 if (doNotCSE(N))
1359 return nullptr;
1360
1361 SDValue Ops[] = { Op };
1362 FoldingSetNodeID ID;
1363 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1364 AddNodeIDCustom(ID, N);
1365 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1366 if (Node)
1367 Node->intersectFlagsWith(N->getFlags());
1368 return Node;
1369}
1370
1371/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1372/// were replaced with those specified. If this node is never memoized,
1373/// return null, otherwise return a pointer to the slot it would take. If a
1374/// node already exists with these operands, the slot will be non-null.
1375SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1376 SDValue Op1, SDValue Op2,
1377 void *&InsertPos) {
1378 if (doNotCSE(N))
1379 return nullptr;
1380
1381 SDValue Ops[] = { Op1, Op2 };
1382 FoldingSetNodeID ID;
1383 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1384 AddNodeIDCustom(ID, N);
1385 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1386 if (Node)
1387 Node->intersectFlagsWith(N->getFlags());
1388 return Node;
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, ArrayRef<SDValue> Ops,
1396 void *&InsertPos) {
1397 if (doNotCSE(N))
1398 return nullptr;
1399
1400 FoldingSetNodeID ID;
1401 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1402 AddNodeIDCustom(ID, N);
1403 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1404 if (Node)
1405 Node->intersectFlagsWith(N->getFlags());
1406 return Node;
1407}
1408
1410 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1411 : VT.getTypeForEVT(*getContext());
1412
1413 return getDataLayout().getABITypeAlign(Ty);
1414}
1415
1416// EntryNode could meaningfully have debug info if we can find it...
1418 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1419 getVTList(MVT::Other, MVT::Glue)),
1420 Root(getEntryNode()) {
1421 InsertNode(&EntryNode);
1422 DbgInfo = new SDDbgInfo();
1423}
1424
1426 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1427 const TargetLibraryInfo *LibraryInfo,
1428 const LibcallLoweringInfo *LibcallsInfo,
1429 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1431 FunctionVarLocs const *VarLocs) {
1432 MF = &NewMF;
1433 SDAGISelPass = PassPtr;
1434 ORE = &NewORE;
1437 LibInfo = LibraryInfo;
1438 Libcalls = LibcallsInfo;
1439 Context = &MF->getFunction().getContext();
1440 UA = NewUA;
1441 PSI = PSIin;
1442 BFI = BFIin;
1443 MMI = &MMIin;
1444 FnVarLocs = VarLocs;
1445}
1446
1448 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1449 allnodes_clear();
1450 OperandRecycler.clear(OperandAllocator);
1451 delete DbgInfo;
1452}
1453
1455 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1456}
1457
1458void SelectionDAG::allnodes_clear() {
1459 assert(&*AllNodes.begin() == &EntryNode);
1460 AllNodes.remove(AllNodes.begin());
1461 while (!AllNodes.empty())
1462 DeallocateNode(&AllNodes.front());
1463#ifndef NDEBUG
1464 NextPersistentId = 0;
1465#endif
1466}
1467
1468SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1469 void *&InsertPos) {
1470 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1471 if (N) {
1472 switch (N->getOpcode()) {
1473 default: break;
1474 case ISD::Constant:
1475 case ISD::ConstantFP:
1476 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1477 "debug location. Use another overload.");
1478 }
1479 }
1480 return N;
1481}
1482
1483SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1484 const SDLoc &DL, void *&InsertPos) {
1485 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1486 if (N) {
1487 switch (N->getOpcode()) {
1488 case ISD::Constant:
1489 case ISD::ConstantFP:
1490 // Erase debug location from the node if the node is used at several
1491 // different places. Do not propagate one location to all uses as it
1492 // will cause a worse single stepping debugging experience.
1493 if (N->getDebugLoc() != DL.getDebugLoc())
1494 N->setDebugLoc(DebugLoc());
1495 break;
1496 default:
1497 // When the node's point of use is located earlier in the instruction
1498 // sequence than its prior point of use, update its debug info to the
1499 // earlier location.
1500 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1501 N->setDebugLoc(DL.getDebugLoc());
1502 break;
1503 }
1504 }
1505 return N;
1506}
1507
1509 allnodes_clear();
1510 OperandRecycler.clear(OperandAllocator);
1511 OperandAllocator.Reset();
1512 CSEMap.clear();
1513
1514 ExtendedValueTypeNodes.clear();
1515 ExternalSymbols.clear();
1516 TargetExternalSymbols.clear();
1517 MCSymbols.clear();
1518 SDEI.clear();
1519 llvm::fill(CondCodeNodes, nullptr);
1520 llvm::fill(ValueTypeNodes, nullptr);
1521
1522 EntryNode.UseList = nullptr;
1523 InsertNode(&EntryNode);
1524 Root = getEntryNode();
1525 DbgInfo->clear();
1526}
1527
1529 return VT.bitsGT(Op.getValueType())
1530 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1531 : getNode(ISD::FP_ROUND, DL, VT, Op,
1532 getIntPtrConstant(0, DL, /*isTarget=*/true));
1533}
1534
1535std::pair<SDValue, SDValue>
1537 const SDLoc &DL, EVT VT) {
1538 assert(!VT.bitsEq(Op.getValueType()) &&
1539 "Strict no-op FP extend/round not allowed.");
1540 SDValue Res =
1541 VT.bitsGT(Op.getValueType())
1542 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1543 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1544 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1545
1546 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1547}
1548
1550 return VT.bitsGT(Op.getValueType()) ?
1551 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1552 getNode(ISD::TRUNCATE, DL, VT, Op);
1553}
1554
1556 return VT.bitsGT(Op.getValueType()) ?
1557 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1558 getNode(ISD::TRUNCATE, DL, VT, Op);
1559}
1560
1562 return VT.bitsGT(Op.getValueType()) ?
1563 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1564 getNode(ISD::TRUNCATE, DL, VT, Op);
1565}
1566
1568 EVT VT) {
1569 assert(!VT.isVector());
1570 auto Type = Op.getValueType();
1571 SDValue DestOp;
1572 if (Type == VT)
1573 return Op;
1574 auto Size = Op.getValueSizeInBits();
1575 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1576 if (DestOp.getValueType() == VT)
1577 return DestOp;
1578
1579 return getAnyExtOrTrunc(DestOp, DL, VT);
1580}
1581
1583 EVT VT) {
1584 assert(!VT.isVector());
1585 auto Type = Op.getValueType();
1586 SDValue DestOp;
1587 if (Type == VT)
1588 return Op;
1589 auto Size = Op.getValueSizeInBits();
1590 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1591 if (DestOp.getValueType() == VT)
1592 return DestOp;
1593
1594 return getSExtOrTrunc(DestOp, DL, VT);
1595}
1596
1598 EVT VT) {
1599 assert(!VT.isVector());
1600 auto Type = Op.getValueType();
1601 SDValue DestOp;
1602 if (Type == VT)
1603 return Op;
1604 auto Size = Op.getValueSizeInBits();
1605 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1606 if (DestOp.getValueType() == VT)
1607 return DestOp;
1608
1609 return getZExtOrTrunc(DestOp, DL, VT);
1610}
1611
1613 EVT OpVT) {
1614 if (VT.bitsLE(Op.getValueType()))
1615 return getNode(ISD::TRUNCATE, SL, VT, Op);
1616
1617 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1618 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1619}
1620
1622 EVT OpVT = Op.getValueType();
1623 assert(VT.isInteger() && OpVT.isInteger() &&
1624 "Cannot getZeroExtendInReg FP types");
1625 assert(VT.isVector() == OpVT.isVector() &&
1626 "getZeroExtendInReg type should be vector iff the operand "
1627 "type is vector!");
1628 assert((!VT.isVector() ||
1630 "Vector element counts must match in getZeroExtendInReg");
1631 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1632 if (OpVT == VT)
1633 return Op;
1634 // TODO: Use computeKnownBits instead of AssertZext.
1635 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1636 ->getVT()
1637 .getScalarType()
1638 .bitsLE(VT.getScalarType()))
1639 return Op;
1641 VT.getScalarSizeInBits());
1642 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1643}
1644
1646 SDValue EVL, const SDLoc &DL,
1647 EVT VT) {
1648 EVT OpVT = Op.getValueType();
1649 assert(VT.isInteger() && OpVT.isInteger() &&
1650 "Cannot getVPZeroExtendInReg FP types");
1651 assert(VT.isVector() && OpVT.isVector() &&
1652 "getVPZeroExtendInReg type and operand type should be vector!");
1654 "Vector element counts must match in getZeroExtendInReg");
1655 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1656 if (OpVT == VT)
1657 return Op;
1659 VT.getScalarSizeInBits());
1660 return getNode(ISD::VP_AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT), Mask,
1661 EVL);
1662}
1663
1665 // Only unsigned pointer semantics are supported right now. In the future this
1666 // might delegate to TLI to check pointer signedness.
1667 return getZExtOrTrunc(Op, DL, VT);
1668}
1669
1671 // Only unsigned pointer semantics are supported right now. In the future this
1672 // might delegate to TLI to check pointer signedness.
1673 return getZeroExtendInReg(Op, DL, VT);
1674}
1675
1677 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1678}
1679
1680/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1682 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1683}
1684
1686 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1687 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1688}
1689
1691 SDValue Mask, SDValue EVL, EVT VT) {
1692 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1693 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1694}
1695
1697 SDValue Mask, SDValue EVL) {
1698 return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL);
1699}
1700
1702 SDValue Mask, SDValue EVL) {
1703 if (VT.bitsGT(Op.getValueType()))
1704 return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL);
1705 if (VT.bitsLT(Op.getValueType()))
1706 return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL);
1707 return Op;
1708}
1709
1711 EVT OpVT) {
1712 if (!V)
1713 return getConstant(0, DL, VT);
1714
1715 switch (TLI->getBooleanContents(OpVT)) {
1718 return getConstant(1, DL, VT);
1720 return getAllOnesConstant(DL, VT);
1721 }
1722 llvm_unreachable("Unexpected boolean content enum!");
1723}
1724
1726 bool isT, bool isO) {
1727 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1728 DL, VT, isT, isO);
1729}
1730
1732 bool isT, bool isO) {
1733 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1734}
1735
1737 EVT VT, bool isT, bool isO) {
1738 assert(VT.isInteger() && "Cannot create FP integer constant!");
1739
1740 EVT EltVT = VT.getScalarType();
1741 const ConstantInt *Elt = &Val;
1742
1743 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1744 // to-be-splatted scalar ConstantInt.
1745 if (isa<VectorType>(Elt->getType()))
1746 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1747
1748 // In some cases the vector type is legal but the element type is illegal and
1749 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1750 // inserted value (the type does not need to match the vector element type).
1751 // Any extra bits introduced will be truncated away.
1752 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1754 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1755 APInt NewVal;
1756 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1757 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1758 else
1759 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1760 Elt = ConstantInt::get(*getContext(), NewVal);
1761 }
1762 // In other cases the element type is illegal and needs to be expanded, for
1763 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1764 // the value into n parts and use a vector type with n-times the elements.
1765 // Then bitcast to the type requested.
1766 // Legalizing constants too early makes the DAGCombiner's job harder so we
1767 // only legalize if the DAG tells us we must produce legal types.
1768 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1769 TLI->getTypeAction(*getContext(), EltVT) ==
1771 const APInt &NewVal = Elt->getValue();
1772 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1773 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1774
1775 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1776 if (VT.isScalableVector() ||
1777 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1778 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1779 "Can only handle an even split!");
1780 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1781
1782 SmallVector<SDValue, 2> ScalarParts;
1783 for (unsigned i = 0; i != Parts; ++i)
1784 ScalarParts.push_back(getConstant(
1785 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1786 ViaEltVT, isT, isO));
1787
1788 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1789 }
1790
1791 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1792 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1793
1794 // Check the temporary vector is the correct size. If this fails then
1795 // getTypeToTransformTo() probably returned a type whose size (in bits)
1796 // isn't a power-of-2 factor of the requested type size.
1797 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1798
1799 SmallVector<SDValue, 2> EltParts;
1800 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1801 EltParts.push_back(getConstant(
1802 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1803 ViaEltVT, isT, isO));
1804
1805 // EltParts is currently in little endian order. If we actually want
1806 // big-endian order then reverse it now.
1807 if (getDataLayout().isBigEndian())
1808 std::reverse(EltParts.begin(), EltParts.end());
1809
1810 // The elements must be reversed when the element order is different
1811 // to the endianness of the elements (because the BITCAST is itself a
1812 // vector shuffle in this situation). However, we do not need any code to
1813 // perform this reversal because getConstant() is producing a vector
1814 // splat.
1815 // This situation occurs in MIPS MSA.
1816
1818 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1819 llvm::append_range(Ops, EltParts);
1820
1821 SDValue V =
1822 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1823 return V;
1824 }
1825
1826 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1827 "APInt size does not match type size!");
1828 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1829 SDVTList VTs = getVTList(EltVT);
1831 AddNodeIDNode(ID, Opc, VTs, {});
1832 ID.AddPointer(Elt);
1833 ID.AddBoolean(isO);
1834 void *IP = nullptr;
1835 SDNode *N = nullptr;
1836 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1837 if (!VT.isVector())
1838 return SDValue(N, 0);
1839
1840 if (!N) {
1841 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1842 if (!isT)
1843 N->setDebugLoc(DL.getDebugLoc());
1844 CSEMap.InsertNode(N, IP);
1845 InsertNode(N);
1846 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1847 }
1848
1849 SDValue Result(N, 0);
1850 if (VT.isVector())
1851 Result = getSplat(VT, DL, Result);
1852 return Result;
1853}
1854
1856 bool isT, bool isO) {
1857 unsigned Size = VT.getScalarSizeInBits();
1858 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1859}
1860
1862 bool IsOpaque) {
1864 IsTarget, IsOpaque);
1865}
1866
1868 bool isTarget) {
1869 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1870}
1871
1873 const SDLoc &DL) {
1874 assert(VT.isInteger() && "Shift amount is not an integer type!");
1875 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1876 return getConstant(Val, DL, ShiftVT);
1877}
1878
1880 const SDLoc &DL) {
1881 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1882 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1883}
1884
1886 bool isTarget) {
1887 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1888}
1889
1891 bool isTarget) {
1892 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1893}
1894
1896 EVT VT, bool isTarget) {
1897 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1898
1899 EVT EltVT = VT.getScalarType();
1900 const ConstantFP *Elt = &V;
1901
1902 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1903 // the to-be-splatted scalar ConstantFP.
1904 if (isa<VectorType>(Elt->getType()))
1905 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1906
1907 // Do the map lookup using the actual bit pattern for the floating point
1908 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1909 // we don't have issues with SNANs.
1910 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1911 SDVTList VTs = getVTList(EltVT);
1913 AddNodeIDNode(ID, Opc, VTs, {});
1914 ID.AddPointer(Elt);
1915 void *IP = nullptr;
1916 SDNode *N = nullptr;
1917 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1918 if (!VT.isVector())
1919 return SDValue(N, 0);
1920
1921 if (!N) {
1922 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1923 CSEMap.InsertNode(N, IP);
1924 InsertNode(N);
1925 }
1926
1927 SDValue Result(N, 0);
1928 if (VT.isVector())
1929 Result = getSplat(VT, DL, Result);
1930 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1931 return Result;
1932}
1933
1935 bool isTarget) {
1936 EVT EltVT = VT.getScalarType();
1937 if (EltVT == MVT::f32)
1938 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1939 if (EltVT == MVT::f64)
1940 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1941 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1942 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1943 bool Ignored;
1944 APFloat APF = APFloat(Val);
1946 &Ignored);
1947 return getConstantFP(APF, DL, VT, isTarget);
1948 }
1949 llvm_unreachable("Unsupported type in getConstantFP");
1950}
1951
1953 EVT VT, int64_t Offset, bool isTargetGA,
1954 unsigned TargetFlags) {
1955 assert((TargetFlags == 0 || isTargetGA) &&
1956 "Cannot set target flags on target-independent globals");
1957
1958 // Truncate (with sign-extension) the offset value to the pointer size.
1960 if (BitWidth < 64)
1962
1963 unsigned Opc;
1964 if (GV->isThreadLocal())
1966 else
1968
1969 SDVTList VTs = getVTList(VT);
1971 AddNodeIDNode(ID, Opc, VTs, {});
1972 ID.AddPointer(GV);
1973 ID.AddInteger(Offset);
1974 ID.AddInteger(TargetFlags);
1975 void *IP = nullptr;
1976 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1977 return SDValue(E, 0);
1978
1979 auto *N = newSDNode<GlobalAddressSDNode>(
1980 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1981 CSEMap.InsertNode(N, IP);
1982 InsertNode(N);
1983 return SDValue(N, 0);
1984}
1985
1987 SDVTList VTs = getVTList(MVT::Untyped);
1990 ID.AddPointer(GV);
1991 void *IP = nullptr;
1992 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP))
1993 return SDValue(E, 0);
1994
1995 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1996 CSEMap.InsertNode(N, IP);
1997 InsertNode(N);
1998 return SDValue(N, 0);
1999}
2000
2001SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
2002 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
2003 SDVTList VTs = getVTList(VT);
2005 AddNodeIDNode(ID, Opc, VTs, {});
2006 ID.AddInteger(FI);
2007 void *IP = nullptr;
2008 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2009 return SDValue(E, 0);
2010
2011 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
2012 CSEMap.InsertNode(N, IP);
2013 InsertNode(N);
2014 return SDValue(N, 0);
2015}
2016
2017SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
2018 unsigned TargetFlags) {
2019 assert((TargetFlags == 0 || isTarget) &&
2020 "Cannot set target flags on target-independent jump tables");
2021 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
2022 SDVTList VTs = getVTList(VT);
2024 AddNodeIDNode(ID, Opc, VTs, {});
2025 ID.AddInteger(JTI);
2026 ID.AddInteger(TargetFlags);
2027 void *IP = nullptr;
2028 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2029 return SDValue(E, 0);
2030
2031 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
2032 CSEMap.InsertNode(N, IP);
2033 InsertNode(N);
2034 return SDValue(N, 0);
2035}
2036
2038 const SDLoc &DL) {
2040 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2041 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2042}
2043
2045 MaybeAlign Alignment, int Offset,
2046 bool isTarget, unsigned TargetFlags) {
2047 assert((TargetFlags == 0 || isTarget) &&
2048 "Cannot set target flags on target-independent globals");
2049 if (!Alignment)
2050 Alignment = shouldOptForSize()
2051 ? getDataLayout().getABITypeAlign(C->getType())
2052 : getDataLayout().getPrefTypeAlign(C->getType());
2053 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2054 SDVTList VTs = getVTList(VT);
2056 AddNodeIDNode(ID, Opc, VTs, {});
2057 ID.AddInteger(Alignment->value());
2058 ID.AddInteger(Offset);
2059 ID.AddPointer(C);
2060 ID.AddInteger(TargetFlags);
2061 void *IP = nullptr;
2062 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2063 return SDValue(E, 0);
2064
2065 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2066 TargetFlags);
2067 CSEMap.InsertNode(N, IP);
2068 InsertNode(N);
2069 SDValue V = SDValue(N, 0);
2070 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2071 return V;
2072}
2073
2075 MaybeAlign Alignment, int Offset,
2076 bool isTarget, unsigned TargetFlags) {
2077 assert((TargetFlags == 0 || isTarget) &&
2078 "Cannot set target flags on target-independent globals");
2079 if (!Alignment)
2080 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2081 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2082 SDVTList VTs = getVTList(VT);
2084 AddNodeIDNode(ID, Opc, VTs, {});
2085 ID.AddInteger(Alignment->value());
2086 ID.AddInteger(Offset);
2087 C->addSelectionDAGCSEId(ID);
2088 ID.AddInteger(TargetFlags);
2089 void *IP = nullptr;
2090 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2091 return SDValue(E, 0);
2092
2093 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2094 TargetFlags);
2095 CSEMap.InsertNode(N, IP);
2096 InsertNode(N);
2097 return SDValue(N, 0);
2098}
2099
2102 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), {});
2103 ID.AddPointer(MBB);
2104 void *IP = nullptr;
2105 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2106 return SDValue(E, 0);
2107
2108 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2109 CSEMap.InsertNode(N, IP);
2110 InsertNode(N);
2111 return SDValue(N, 0);
2112}
2113
2115 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2116 ValueTypeNodes.size())
2117 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2118
2119 SDNode *&N = VT.isExtended() ?
2120 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2121
2122 if (N) return SDValue(N, 0);
2123 N = newSDNode<VTSDNode>(VT);
2124 InsertNode(N);
2125 return SDValue(N, 0);
2126}
2127
2129 SDNode *&N = ExternalSymbols[Sym];
2130 if (N) return SDValue(N, 0);
2131 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2132 InsertNode(N);
2133 return SDValue(N, 0);
2134}
2135
2136SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2138 return getExternalSymbol(SymName.data(), VT);
2139}
2140
2142 SDNode *&N = MCSymbols[Sym];
2143 if (N)
2144 return SDValue(N, 0);
2145 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2146 InsertNode(N);
2147 return SDValue(N, 0);
2148}
2149
2151 unsigned TargetFlags) {
2152 SDNode *&N =
2153 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2154 if (N) return SDValue(N, 0);
2155 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2156 InsertNode(N);
2157 return SDValue(N, 0);
2158}
2159
2161 EVT VT, unsigned TargetFlags) {
2163 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2164}
2165
2167 if ((unsigned)Cond >= CondCodeNodes.size())
2168 CondCodeNodes.resize(Cond+1);
2169
2170 if (!CondCodeNodes[Cond]) {
2171 auto *N = newSDNode<CondCodeSDNode>(Cond);
2172 CondCodeNodes[Cond] = N;
2173 InsertNode(N);
2174 }
2175
2176 return SDValue(CondCodeNodes[Cond], 0);
2177}
2178
2180 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2181 "APInt size does not match type size!");
2182
2183 if (MulImm == 0)
2184 return getConstant(0, DL, VT);
2185
2186 const MachineFunction &MF = getMachineFunction();
2187 const Function &F = MF.getFunction();
2188 ConstantRange CR = getVScaleRange(&F, 64);
2189 if (const APInt *C = CR.getSingleElement())
2190 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2191
2192 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2193}
2194
2195/// \returns a value of type \p VT that represents the runtime value of \p
2196/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2197/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2198/// or TypeSize.
2199template <typename Ty>
2201 EVT VT, Ty Quantity) {
2202 if (Quantity.isScalable())
2203 return DAG.getVScale(
2204 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2205
2206 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2207}
2208
2210 ElementCount EC) {
2211 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2212}
2213
2215 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2216}
2217
2219 ElementCount EC) {
2220 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2221 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2222 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2223 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2224}
2225
2227 APInt One(ResVT.getScalarSizeInBits(), 1);
2228 return getStepVector(DL, ResVT, One);
2229}
2230
2232 const APInt &StepVal) {
2233 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2234 if (ResVT.isScalableVector())
2235 return getNode(
2236 ISD::STEP_VECTOR, DL, ResVT,
2237 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2238
2239 SmallVector<SDValue, 16> OpsStepConstants;
2240 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2241 OpsStepConstants.push_back(
2242 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2243 return getBuildVector(ResVT, DL, OpsStepConstants);
2244}
2245
2246/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2247/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2252
2254 SDValue N2, ArrayRef<int> Mask) {
2255 assert(VT.getVectorNumElements() == Mask.size() &&
2256 "Must have the same number of vector elements as mask elements!");
2257 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2258 "Invalid VECTOR_SHUFFLE");
2259
2260 // Canonicalize shuffle undef, undef -> undef
2261 if (N1.isUndef() && N2.isUndef()) {
2262 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2263 return getPOISON(VT);
2264 return getUNDEF(VT);
2265 }
2266
2267 // Validate that all indices in Mask are within the range of the elements
2268 // input to the shuffle.
2269 int NElts = Mask.size();
2270 assert(llvm::all_of(Mask,
2271 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2272 "Index out of range");
2273
2274 // Copy the mask so we can do any needed cleanup.
2275 SmallVector<int, 8> MaskVec(Mask);
2276
2277 // Canonicalize shuffle v, v -> v, poison
2278 if (N1 == N2) {
2279 N2 = getPOISON(VT);
2280 for (int i = 0; i != NElts; ++i)
2281 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2282 }
2283
2284 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2285 if (N1.isUndef())
2286 commuteShuffle(N1, N2, MaskVec);
2287
2288 if (TLI->hasVectorBlend()) {
2289 // If shuffling a splat, try to blend the splat instead. We do this here so
2290 // that even when this arises during lowering we don't have to re-handle it.
2291 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2292 BitVector UndefElements;
2293 SDValue Splat = BV->getSplatValue(&UndefElements);
2294 if (!Splat)
2295 return;
2296
2297 for (int i = 0; i < NElts; ++i) {
2298 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2299 continue;
2300
2301 // If this input comes from undef, mark it as such.
2302 if (UndefElements[MaskVec[i] - Offset]) {
2303 MaskVec[i] = -1;
2304 continue;
2305 }
2306
2307 // If we can blend a non-undef lane, use that instead.
2308 if (!UndefElements[i])
2309 MaskVec[i] = i + Offset;
2310 }
2311 };
2312 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2313 BlendSplat(N1BV, 0);
2314 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2315 BlendSplat(N2BV, NElts);
2316 }
2317
2318 // Canonicalize all index into lhs, -> shuffle lhs, poison
2319 // Canonicalize all index into rhs, -> shuffle rhs, poison
2320 bool AllLHS = true, AllRHS = true;
2321 bool N2Undef = N2.isUndef();
2322 for (int i = 0; i != NElts; ++i) {
2323 if (MaskVec[i] >= NElts) {
2324 if (N2Undef)
2325 MaskVec[i] = -1;
2326 else
2327 AllLHS = false;
2328 } else if (MaskVec[i] >= 0) {
2329 AllRHS = false;
2330 }
2331 }
2332 if (AllLHS && AllRHS)
2333 return getPOISON(VT);
2334 if (AllLHS && !N2Undef)
2335 N2 = getPOISON(VT);
2336 if (AllRHS) {
2337 N1 = getPOISON(VT);
2338 commuteShuffle(N1, N2, MaskVec);
2339 }
2340 // Reset our undef status after accounting for the mask.
2341 N2Undef = N2.isUndef();
2342 // Re-check whether both sides ended up undef.
2343 if (N1.isUndef() && N2Undef) {
2344 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2345 return getPOISON(VT);
2346 return getUNDEF(VT);
2347 }
2348
2349 // If Identity shuffle return that node.
2350 bool Identity = true, AllSame = true;
2351 for (int i = 0; i != NElts; ++i) {
2352 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2353 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2354 }
2355 if (Identity && NElts)
2356 return N1;
2357
2358 // Shuffling a constant splat doesn't change the result.
2359 if (N2Undef) {
2360 SDValue V = N1;
2361
2362 // Look through any bitcasts. We check that these don't change the number
2363 // (and size) of elements and just changes their types.
2364 while (V.getOpcode() == ISD::BITCAST)
2365 V = V->getOperand(0);
2366
2367 // A splat should always show up as a build vector node.
2368 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2369 BitVector UndefElements;
2370 SDValue Splat = BV->getSplatValue(&UndefElements);
2371 // If this is a splat of an undef, shuffling it is also undef.
2372 if (Splat && Splat.isUndef())
2373 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2374
2375 bool SameNumElts =
2376 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2377
2378 // We only have a splat which can skip shuffles if there is a splatted
2379 // value and no undef lanes rearranged by the shuffle.
2380 if (Splat && UndefElements.none()) {
2381 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2382 // number of elements match or the value splatted is a zero constant.
2383 if (SameNumElts || isNullConstant(Splat))
2384 return N1;
2385 }
2386
2387 // If the shuffle itself creates a splat, build the vector directly.
2388 if (AllSame && SameNumElts) {
2389 EVT BuildVT = BV->getValueType(0);
2390 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2391 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2392
2393 // We may have jumped through bitcasts, so the type of the
2394 // BUILD_VECTOR may not match the type of the shuffle.
2395 if (BuildVT != VT)
2396 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2397 return NewBV;
2398 }
2399 }
2400 }
2401
2402 SDVTList VTs = getVTList(VT);
2404 SDValue Ops[2] = { N1, N2 };
2406 for (int i = 0; i != NElts; ++i)
2407 ID.AddInteger(MaskVec[i]);
2408
2409 void* IP = nullptr;
2410 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2411 return SDValue(E, 0);
2412
2413 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2414 // SDNode doesn't have access to it. This memory will be "leaked" when
2415 // the node is deallocated, but recovered when the NodeAllocator is released.
2416 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2417 llvm::copy(MaskVec, MaskAlloc);
2418
2419 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2420 dl.getDebugLoc(), MaskAlloc);
2421 createOperands(N, Ops);
2422
2423 CSEMap.InsertNode(N, IP);
2424 InsertNode(N);
2425 SDValue V = SDValue(N, 0);
2426 NewSDValueDbgMsg(V, "Creating new node: ", this);
2427 return V;
2428}
2429
2431 EVT VT = SV.getValueType(0);
2432 SmallVector<int, 8> MaskVec(SV.getMask());
2434
2435 SDValue Op0 = SV.getOperand(0);
2436 SDValue Op1 = SV.getOperand(1);
2437 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2438}
2439
2441 SDVTList VTs = getVTList(VT);
2443 AddNodeIDNode(ID, ISD::Register, VTs, {});
2444 ID.AddInteger(Reg.id());
2445 void *IP = nullptr;
2446 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2447 return SDValue(E, 0);
2448
2449 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2450 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2451 CSEMap.InsertNode(N, IP);
2452 InsertNode(N);
2453 return SDValue(N, 0);
2454}
2455
2458 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), {});
2459 ID.AddPointer(RegMask);
2460 void *IP = nullptr;
2461 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2462 return SDValue(E, 0);
2463
2464 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2465 CSEMap.InsertNode(N, IP);
2466 InsertNode(N);
2467 return SDValue(N, 0);
2468}
2469
2471 MCSymbol *Label) {
2472 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2473}
2474
2475SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2476 SDValue Root, MCSymbol *Label) {
2478 SDValue Ops[] = { Root };
2479 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2480 ID.AddPointer(Label);
2481 void *IP = nullptr;
2482 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2483 return SDValue(E, 0);
2484
2485 auto *N =
2486 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2487 createOperands(N, Ops);
2488
2489 CSEMap.InsertNode(N, IP);
2490 InsertNode(N);
2491 return SDValue(N, 0);
2492}
2493
2495 int64_t Offset, bool isTarget,
2496 unsigned TargetFlags) {
2497 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2498 SDVTList VTs = getVTList(VT);
2499
2501 AddNodeIDNode(ID, Opc, VTs, {});
2502 ID.AddPointer(BA);
2503 ID.AddInteger(Offset);
2504 ID.AddInteger(TargetFlags);
2505 void *IP = nullptr;
2506 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2507 return SDValue(E, 0);
2508
2509 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2510 CSEMap.InsertNode(N, IP);
2511 InsertNode(N);
2512 return SDValue(N, 0);
2513}
2514
2517 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), {});
2518 ID.AddPointer(V);
2519
2520 void *IP = nullptr;
2521 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2522 return SDValue(E, 0);
2523
2524 auto *N = newSDNode<SrcValueSDNode>(V);
2525 CSEMap.InsertNode(N, IP);
2526 InsertNode(N);
2527 return SDValue(N, 0);
2528}
2529
2532 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2533 ID.AddPointer(MD);
2534
2535 void *IP = nullptr;
2536 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2537 return SDValue(E, 0);
2538
2539 auto *N = newSDNode<MDNodeSDNode>(MD);
2540 CSEMap.InsertNode(N, IP);
2541 InsertNode(N);
2542 return SDValue(N, 0);
2543}
2544
2546 if (VT == V.getValueType())
2547 return V;
2548
2549 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2550}
2551
2553 unsigned SrcAS, unsigned DestAS) {
2554 SDVTList VTs = getVTList(VT);
2555 SDValue Ops[] = {Ptr};
2558 ID.AddInteger(SrcAS);
2559 ID.AddInteger(DestAS);
2560
2561 void *IP = nullptr;
2562 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2563 return SDValue(E, 0);
2564
2565 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2566 VTs, SrcAS, DestAS);
2567 createOperands(N, Ops);
2568
2569 CSEMap.InsertNode(N, IP);
2570 InsertNode(N);
2571 return SDValue(N, 0);
2572}
2573
2575 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2576}
2577
2579 UndefPoisonKind Kind) {
2580 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2581 return V;
2582 return getFreeze(V);
2583}
2584
2585/// getShiftAmountOperand - Return the specified value casted to
2586/// the target's desired shift amount type.
2588 EVT OpTy = Op.getValueType();
2589 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2590 if (OpTy == ShTy || OpTy.isVector()) return Op;
2591
2592 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2593}
2594
2596 SDLoc dl(Node);
2598 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2599 EVT VT = Node->getValueType(0);
2600 SDValue Tmp1 = Node->getOperand(0);
2601 SDValue Tmp2 = Node->getOperand(1);
2602 const MaybeAlign MA(Node->getConstantOperandVal(3));
2603
2604 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2605 Tmp2, MachinePointerInfo(V));
2606 SDValue VAList = VAListLoad;
2607
2608 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2609 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2610 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2611
2612 VAList = getNode(
2613 ISD::AND, dl, VAList.getValueType(), VAList,
2614 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2615 }
2616
2617 // Increment the pointer, VAList, to the next vaarg
2618 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2619 getConstant(getDataLayout().getTypeAllocSize(
2620 VT.getTypeForEVT(*getContext())),
2621 dl, VAList.getValueType()));
2622 // Store the incremented VAList to the legalized pointer
2623 Tmp1 =
2624 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2625 // Load the actual argument out of the pointer VAList
2626 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2627}
2628
2630 SDLoc dl(Node);
2632 // This defaults to loading a pointer from the input and storing it to the
2633 // output, returning the chain.
2634 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2635 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2636 SDValue Tmp1 =
2637 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2638 Node->getOperand(2), MachinePointerInfo(VS));
2639 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2640 MachinePointerInfo(VD));
2641}
2642
2644 const DataLayout &DL = getDataLayout();
2645 Type *Ty = VT.getTypeForEVT(*getContext());
2646 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2647
2648 if (TLI->isTypeLegal(VT) || !VT.isVector())
2649 return RedAlign;
2650
2651 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2652 const Align StackAlign = TFI->getStackAlign();
2653
2654 // See if we can choose a smaller ABI alignment in cases where it's an
2655 // illegal vector type that will get broken down.
2656 if (RedAlign > StackAlign) {
2657 EVT IntermediateVT;
2658 MVT RegisterVT;
2659 unsigned NumIntermediates;
2660 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2661 NumIntermediates, RegisterVT);
2662 Ty = IntermediateVT.getTypeForEVT(*getContext());
2663 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2664 if (RedAlign2 < RedAlign)
2665 RedAlign = RedAlign2;
2666
2667 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2668 // If the stack is not realignable, the alignment should be limited to the
2669 // StackAlignment
2670 RedAlign = std::min(RedAlign, StackAlign);
2671 }
2672
2673 return RedAlign;
2674}
2675
2677 MachineFrameInfo &MFI = MF->getFrameInfo();
2678 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2679 int StackID = 0;
2680 if (Bytes.isScalable())
2681 StackID = TFI->getStackIDForScalableVectors();
2682 // The stack id gives an indication of whether the object is scalable or
2683 // not, so it's safe to pass in the minimum size here.
2684 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2685 false, nullptr, StackID);
2686 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2687}
2688
2690 Type *Ty = VT.getTypeForEVT(*getContext());
2691 Align StackAlign =
2692 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2693 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2694}
2695
2697 TypeSize VT1Size = VT1.getStoreSize();
2698 TypeSize VT2Size = VT2.getStoreSize();
2699 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2700 "Don't know how to choose the maximum size when creating a stack "
2701 "temporary");
2702 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2703 ? VT1Size
2704 : VT2Size;
2705
2706 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2707 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2708 const DataLayout &DL = getDataLayout();
2709 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2710 return CreateStackTemporary(Bytes, Align);
2711}
2712
2714 ISD::CondCode Cond, const SDLoc &dl,
2715 SDNodeFlags Flags) {
2716 EVT OpVT = N1.getValueType();
2717
2718 auto GetUndefBooleanConstant = [&]() {
2719 if (VT.getScalarType() == MVT::i1 ||
2720 TLI->getBooleanContents(OpVT) ==
2722 return getUNDEF(VT);
2723 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2724 // so we cannot use getUNDEF(). Return zero instead.
2725 return getConstant(0, dl, VT);
2726 };
2727
2728 // These setcc operations always fold.
2729 switch (Cond) {
2730 default: break;
2731 case ISD::SETFALSE:
2732 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2733 case ISD::SETTRUE:
2734 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2735
2736 case ISD::SETOEQ:
2737 case ISD::SETOGT:
2738 case ISD::SETOGE:
2739 case ISD::SETOLT:
2740 case ISD::SETOLE:
2741 case ISD::SETONE:
2742 case ISD::SETO:
2743 case ISD::SETUO:
2744 case ISD::SETUEQ:
2745 case ISD::SETUNE:
2746 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2747 break;
2748 }
2749
2750 if (OpVT.isInteger()) {
2751 // For EQ and NE, we can always pick a value for the undef to make the
2752 // predicate pass or fail, so we can return undef.
2753 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2754 // icmp eq/ne X, undef -> undef.
2755 if ((N1.isUndef() || N2.isUndef()) &&
2756 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2757 return GetUndefBooleanConstant();
2758
2759 // If both operands are undef, we can return undef for int comparison.
2760 // icmp undef, undef -> undef.
2761 if (N1.isUndef() && N2.isUndef())
2762 return GetUndefBooleanConstant();
2763
2764 // icmp X, X -> true/false
2765 // icmp X, undef -> true/false because undef could be X.
2766 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2767 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2768 }
2769
2771 const APInt &C2 = N2C->getAPIntValue();
2773 const APInt &C1 = N1C->getAPIntValue();
2774
2776 dl, VT, OpVT);
2777 }
2778 }
2779
2780 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2781 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2782
2783 if (N1CFP && N2CFP) {
2784 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2785 switch (Cond) {
2786 default: break;
2787 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2788 return GetUndefBooleanConstant();
2789 [[fallthrough]];
2790 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2791 OpVT);
2792 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2793 return GetUndefBooleanConstant();
2794 [[fallthrough]];
2796 R==APFloat::cmpLessThan, dl, VT,
2797 OpVT);
2798 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2799 return GetUndefBooleanConstant();
2800 [[fallthrough]];
2801 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2802 OpVT);
2803 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2804 return GetUndefBooleanConstant();
2805 [[fallthrough]];
2807 VT, OpVT);
2808 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2809 return GetUndefBooleanConstant();
2810 [[fallthrough]];
2812 R==APFloat::cmpEqual, dl, VT,
2813 OpVT);
2814 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2815 return GetUndefBooleanConstant();
2816 [[fallthrough]];
2818 R==APFloat::cmpEqual, dl, VT, OpVT);
2819 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2820 OpVT);
2821 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2822 OpVT);
2824 R==APFloat::cmpEqual, dl, VT,
2825 OpVT);
2826 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2827 OpVT);
2829 R==APFloat::cmpLessThan, dl, VT,
2830 OpVT);
2832 R==APFloat::cmpUnordered, dl, VT,
2833 OpVT);
2835 VT, OpVT);
2836 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2837 OpVT);
2838 }
2839 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2840 // Ensure that the constant occurs on the RHS.
2842 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2843 return SDValue();
2844 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2845 /*IsSignaling=*/false, Flags);
2846 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2847 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2848 // If an operand is known to be a nan (or undef that could be a nan), we can
2849 // fold it.
2850 // Choosing NaN for the undef will always make unordered comparison succeed
2851 // and ordered comparison fails.
2852 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2853 switch (ISD::getUnorderedFlavor(Cond)) {
2854 default:
2855 llvm_unreachable("Unknown flavor!");
2856 case 0: // Known false.
2857 return getBoolConstant(false, dl, VT, OpVT);
2858 case 1: // Known true.
2859 return getBoolConstant(true, dl, VT, OpVT);
2860 case 2: // Undefined.
2861 return GetUndefBooleanConstant();
2862 }
2863 }
2864
2865 // Could not fold it.
2866 return SDValue();
2867}
2868
2869/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2870/// use this predicate to simplify operations downstream.
2872 unsigned BitWidth = Op.getScalarValueSizeInBits();
2874}
2875
2876// TODO: Should have argument to specify if sign bit of nan is ignorable.
2878 if (Depth >= MaxRecursionDepth)
2879 return false; // Limit search depth.
2880
2881 unsigned Opc = Op.getOpcode();
2882 switch (Opc) {
2883 case ISD::FABS:
2884 return true;
2885 case ISD::AssertNoFPClass: {
2886 FPClassTest NoFPClass =
2887 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2888
2889 const FPClassTest TestMask = fcNan | fcNegative;
2890 return (NoFPClass & TestMask) == TestMask;
2891 }
2892 case ISD::ARITH_FENCE:
2893 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2894 case ISD::FEXP:
2895 case ISD::FEXP2:
2896 case ISD::FEXP10:
2897 return Op->getFlags().hasNoNaNs();
2898 case ISD::FMINNUM:
2899 case ISD::FMINNUM_IEEE:
2900 case ISD::FMINIMUM:
2901 case ISD::FMINIMUMNUM:
2902 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2903 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2904 case ISD::FMAXNUM:
2905 case ISD::FMAXNUM_IEEE:
2906 case ISD::FMAXIMUM:
2907 case ISD::FMAXIMUMNUM:
2908 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2909 // is sufficient.
2910 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2911 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2912 default:
2913 return false;
2914 }
2915
2916 llvm_unreachable("covered opcode switch");
2917}
2918
2919/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2920/// this predicate to simplify operations downstream. Mask is known to be zero
2921/// for bits that V cannot have.
2923 unsigned Depth) const {
2924 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2925}
2926
2927/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2928/// DemandedElts. We use this predicate to simplify operations downstream.
2929/// Mask is known to be zero for bits that V cannot have.
2931 const APInt &DemandedElts,
2932 unsigned Depth) const {
2933 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2934}
2935
2936/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2937/// DemandedElts. We use this predicate to simplify operations downstream.
2939 unsigned Depth /* = 0 */) const {
2940 return computeKnownBits(V, DemandedElts, Depth).isZero();
2941}
2942
2943/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2945 unsigned Depth) const {
2946 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2947}
2948
2950 const APInt &DemandedElts,
2951 unsigned Depth) const {
2952 EVT VT = Op.getValueType();
2953 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2954
2955 unsigned NumElts = VT.getVectorNumElements();
2956 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2957
2958 APInt KnownZeroElements = APInt::getZero(NumElts);
2959 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2960 if (!DemandedElts[EltIdx])
2961 continue; // Don't query elements that are not demanded.
2962 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2963 if (MaskedVectorIsZero(Op, Mask, Depth))
2964 KnownZeroElements.setBit(EltIdx);
2965 }
2966 return KnownZeroElements;
2967}
2968
2969/// isSplatValue - Return true if the vector V has the same value
2970/// across all DemandedElts. For scalable vectors, we don't know the
2971/// number of lanes at compile time. Instead, we use a 1 bit APInt
2972/// to represent a conservative value for all lanes; that is, that
2973/// one bit value is implicitly splatted across all lanes.
2974bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2975 APInt &UndefElts, unsigned Depth) const {
2976 unsigned Opcode = V.getOpcode();
2977 EVT VT = V.getValueType();
2978 assert(VT.isVector() && "Vector type expected");
2979 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2980 "scalable demanded bits are ignored");
2981
2982 if (!DemandedElts)
2983 return false; // No demanded elts, better to assume we don't know anything.
2984
2985 if (Depth >= MaxRecursionDepth)
2986 return false; // Limit search depth.
2987
2988 // Deal with some common cases here that work for both fixed and scalable
2989 // vector types.
2990 switch (Opcode) {
2991 case ISD::SPLAT_VECTOR:
2992 UndefElts = V.getOperand(0).isUndef()
2993 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2994 : APInt(DemandedElts.getBitWidth(), 0);
2995 return true;
2996 case ISD::ADD:
2997 case ISD::SUB:
2998 case ISD::AND:
2999 case ISD::XOR:
3000 case ISD::OR: {
3001 APInt UndefLHS, UndefRHS;
3002 SDValue LHS = V.getOperand(0);
3003 SDValue RHS = V.getOperand(1);
3004 // Only recognize splats with the same demanded undef elements for both
3005 // operands, otherwise we might fail to handle binop-specific undef
3006 // handling.
3007 // e.g. (and undef, 0) -> 0 etc.
3008 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
3009 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
3010 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
3011 UndefElts = UndefLHS | UndefRHS;
3012 return true;
3013 }
3014 return false;
3015 }
3016 case ISD::ABS:
3018 case ISD::TRUNCATE:
3019 case ISD::SIGN_EXTEND:
3020 case ISD::ZERO_EXTEND:
3021 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3022 default:
3023 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3024 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3025 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3026 Depth);
3027 break;
3028 }
3029
3030 // We don't support other cases than those above for scalable vectors at
3031 // the moment.
3032 if (VT.isScalableVector())
3033 return false;
3034
3035 unsigned NumElts = VT.getVectorNumElements();
3036 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3037 UndefElts = APInt::getZero(NumElts);
3038
3039 switch (Opcode) {
3040 case ISD::BUILD_VECTOR: {
3041 SDValue Scl;
3042 for (unsigned i = 0; i != NumElts; ++i) {
3043 SDValue Op = V.getOperand(i);
3044 if (Op.isUndef()) {
3045 UndefElts.setBit(i);
3046 continue;
3047 }
3048 if (!DemandedElts[i])
3049 continue;
3050 if (Scl && Scl != Op)
3051 return false;
3052 Scl = Op;
3053 }
3054 return true;
3055 }
3056 case ISD::VECTOR_SHUFFLE: {
3057 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3058 APInt DemandedLHS = APInt::getZero(NumElts);
3059 APInt DemandedRHS = APInt::getZero(NumElts);
3060 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3061 for (int i = 0; i != (int)NumElts; ++i) {
3062 int M = Mask[i];
3063 if (M < 0) {
3064 UndefElts.setBit(i);
3065 continue;
3066 }
3067 if (!DemandedElts[i])
3068 continue;
3069 if (M < (int)NumElts)
3070 DemandedLHS.setBit(M);
3071 else
3072 DemandedRHS.setBit(M - NumElts);
3073 }
3074
3075 // If we aren't demanding either op, assume there's no splat.
3076 // If we are demanding both ops, assume there's no splat.
3077 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3078 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3079 return false;
3080
3081 // See if the demanded elts of the source op is a splat or we only demand
3082 // one element, which should always be a splat.
3083 // TODO: Handle source ops splats with undefs.
3084 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3085 APInt SrcUndefs;
3086 return (SrcElts.popcount() == 1) ||
3087 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3088 (SrcElts & SrcUndefs).isZero());
3089 };
3090 if (!DemandedLHS.isZero())
3091 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3092 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3093 }
3095 // Offset the demanded elts by the subvector index.
3096 SDValue Src = V.getOperand(0);
3097 // We don't support scalable vectors at the moment.
3098 if (Src.getValueType().isScalableVector())
3099 return false;
3100 uint64_t Idx = V.getConstantOperandVal(1);
3101 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3102 APInt UndefSrcElts;
3103 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3104 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3105 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3106 return true;
3107 }
3108 break;
3109 }
3113 // Widen the demanded elts by the src element count.
3114 SDValue Src = V.getOperand(0);
3115 // We don't support scalable vectors at the moment.
3116 if (Src.getValueType().isScalableVector())
3117 return false;
3118 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3119 APInt UndefSrcElts;
3120 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3121 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3122 UndefElts = UndefSrcElts.trunc(NumElts);
3123 return true;
3124 }
3125 break;
3126 }
3127 case ISD::BITCAST: {
3128 SDValue Src = V.getOperand(0);
3129 EVT SrcVT = Src.getValueType();
3130 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3131 unsigned BitWidth = VT.getScalarSizeInBits();
3132
3133 // Ignore bitcasts from unsupported types.
3134 // TODO: Add fp support?
3135 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3136 break;
3137
3138 // Bitcast 'small element' vector to 'large element' vector.
3139 if ((BitWidth % SrcBitWidth) == 0) {
3140 // See if each sub element is a splat.
3141 unsigned Scale = BitWidth / SrcBitWidth;
3142 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3143 APInt ScaledDemandedElts =
3144 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3145 for (unsigned I = 0; I != Scale; ++I) {
3146 APInt SubUndefElts;
3147 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3148 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3149 SubDemandedElts &= ScaledDemandedElts;
3150 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3151 return false;
3152 // TODO: Add support for merging sub undef elements.
3153 if (!SubUndefElts.isZero())
3154 return false;
3155 }
3156 return true;
3157 }
3158 break;
3159 }
3160 }
3161
3162 return false;
3163}
3164
3165/// Helper wrapper to main isSplatValue function.
3166bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3167 EVT VT = V.getValueType();
3168 assert(VT.isVector() && "Vector type expected");
3169
3170 APInt UndefElts;
3171 // Since the number of lanes in a scalable vector is unknown at compile time,
3172 // we track one bit which is implicitly broadcast to all lanes. This means
3173 // that all lanes in a scalable vector are considered demanded.
3174 APInt DemandedElts
3176 return isSplatValue(V, DemandedElts, UndefElts) &&
3177 (AllowUndefs || !UndefElts);
3178}
3179
3182
3183 EVT VT = V.getValueType();
3184 unsigned Opcode = V.getOpcode();
3185 switch (Opcode) {
3186 default: {
3187 APInt UndefElts;
3188 // Since the number of lanes in a scalable vector is unknown at compile time,
3189 // we track one bit which is implicitly broadcast to all lanes. This means
3190 // that all lanes in a scalable vector are considered demanded.
3191 APInt DemandedElts
3193
3194 if (isSplatValue(V, DemandedElts, UndefElts)) {
3195 if (VT.isScalableVector()) {
3196 // DemandedElts and UndefElts are ignored for scalable vectors, since
3197 // the only supported cases are SPLAT_VECTOR nodes.
3198 SplatIdx = 0;
3199 } else {
3200 // Handle case where all demanded elements are UNDEF.
3201 if (DemandedElts.isSubsetOf(UndefElts)) {
3202 SplatIdx = 0;
3203 return getUNDEF(VT);
3204 }
3205 SplatIdx = (UndefElts & DemandedElts).countr_one();
3206 }
3207 return V;
3208 }
3209 break;
3210 }
3211 case ISD::SPLAT_VECTOR:
3212 SplatIdx = 0;
3213 return V;
3214 case ISD::VECTOR_SHUFFLE: {
3215 assert(!VT.isScalableVector());
3216 // Check if this is a shuffle node doing a splat.
3217 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3218 // getTargetVShiftNode currently struggles without the splat source.
3219 auto *SVN = cast<ShuffleVectorSDNode>(V);
3220 if (!SVN->isSplat())
3221 break;
3222 int Idx = SVN->getSplatIndex();
3223 int NumElts = V.getValueType().getVectorNumElements();
3224 SplatIdx = Idx % NumElts;
3225 return V.getOperand(Idx / NumElts);
3226 }
3227 }
3228
3229 return SDValue();
3230}
3231
3233 int SplatIdx;
3234 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3235 EVT SVT = SrcVector.getValueType().getScalarType();
3236 EVT LegalSVT = SVT;
3237 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3238 if (!SVT.isInteger())
3239 return SDValue();
3240 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3241 if (LegalSVT.bitsLT(SVT))
3242 return SDValue();
3243 }
3244 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3245 }
3246 return SDValue();
3247}
3248
3249std::optional<ConstantRange>
3251 unsigned Depth) const {
3252 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3253 V.getOpcode() == ISD::SRA) &&
3254 "Unknown shift node");
3255 // Shifting more than the bitwidth is not valid.
3256 unsigned BitWidth = V.getScalarValueSizeInBits();
3257
3258 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3259 const APInt &ShAmt = Cst->getAPIntValue();
3260 if (ShAmt.uge(BitWidth))
3261 return std::nullopt;
3262 return ConstantRange(ShAmt);
3263 }
3264
3265 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3266 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3267 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3268 if (!DemandedElts[i])
3269 continue;
3270 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3271 if (!SA) {
3272 MinAmt = MaxAmt = nullptr;
3273 break;
3274 }
3275 const APInt &ShAmt = SA->getAPIntValue();
3276 if (ShAmt.uge(BitWidth))
3277 return std::nullopt;
3278 if (!MinAmt || MinAmt->ugt(ShAmt))
3279 MinAmt = &ShAmt;
3280 if (!MaxAmt || MaxAmt->ult(ShAmt))
3281 MaxAmt = &ShAmt;
3282 }
3283 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3284 "Failed to find matching min/max shift amounts");
3285 if (MinAmt && MaxAmt)
3286 return ConstantRange(*MinAmt, *MaxAmt + 1);
3287 }
3288
3289 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3290 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3291 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3292 if (KnownAmt.getMaxValue().ult(BitWidth))
3293 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3294
3295 return std::nullopt;
3296}
3297
3298std::optional<unsigned>
3300 unsigned Depth) const {
3301 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3302 V.getOpcode() == ISD::SRA) &&
3303 "Unknown shift node");
3304 if (std::optional<ConstantRange> AmtRange =
3305 getValidShiftAmountRange(V, DemandedElts, Depth))
3306 if (const APInt *ShAmt = AmtRange->getSingleElement())
3307 return ShAmt->getZExtValue();
3308 return std::nullopt;
3309}
3310
3311std::optional<unsigned>
3313 APInt DemandedElts = getDemandAllEltsMask(V);
3314 return getValidShiftAmount(V, DemandedElts, Depth);
3315}
3316
3317std::optional<unsigned>
3319 unsigned Depth) const {
3320 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3321 V.getOpcode() == ISD::SRA) &&
3322 "Unknown shift node");
3323 if (std::optional<ConstantRange> AmtRange =
3324 getValidShiftAmountRange(V, DemandedElts, Depth))
3325 return AmtRange->getUnsignedMin().getZExtValue();
3326 return std::nullopt;
3327}
3328
3329std::optional<unsigned>
3331 APInt DemandedElts = getDemandAllEltsMask(V);
3332 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3333}
3334
3335std::optional<unsigned>
3337 unsigned Depth) const {
3338 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3339 V.getOpcode() == ISD::SRA) &&
3340 "Unknown shift node");
3341 if (std::optional<ConstantRange> AmtRange =
3342 getValidShiftAmountRange(V, DemandedElts, Depth))
3343 return AmtRange->getUnsignedMax().getZExtValue();
3344 return std::nullopt;
3345}
3346
3347std::optional<unsigned>
3349 APInt DemandedElts = getDemandAllEltsMask(V);
3350 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3351}
3352
3353/// Determine which bits of Op are known to be either zero or one and return
3354/// them in Known. For vectors, the known bits are those that are shared by
3355/// every vector element.
3357 APInt DemandedElts = getDemandAllEltsMask(Op);
3358 return computeKnownBits(Op, DemandedElts, Depth);
3359}
3360
3361/// Determine which bits of Op are known to be either zero or one and return
3362/// them in Known. The DemandedElts argument allows us to only collect the known
3363/// bits that are shared by the requested vector elements.
3365 unsigned Depth) const {
3366 unsigned BitWidth = Op.getScalarValueSizeInBits();
3367
3368 KnownBits Known(BitWidth); // Don't know anything.
3369
3370 if (auto OptAPInt = Op->bitcastToAPInt()) {
3371 // We know all of the bits for a constant!
3372 return KnownBits::makeConstant(*std::move(OptAPInt));
3373 }
3374
3375 if (Depth >= MaxRecursionDepth)
3376 return Known; // Limit search depth.
3377
3378 KnownBits Known2;
3379 unsigned NumElts = DemandedElts.getBitWidth();
3380 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3381 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3382 assert((!Op.getValueType().isFixedLengthVector() ||
3383 NumElts == Op.getValueType().getVectorNumElements()) &&
3384 "Unexpected vector size");
3385
3386 if (!DemandedElts)
3387 return Known; // No demanded elts, better to assume we don't know anything.
3388
3389 unsigned Opcode = Op.getOpcode();
3390 switch (Opcode) {
3391 case ISD::MERGE_VALUES:
3392 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3393 Depth + 1);
3394 case ISD::SPLAT_VECTOR: {
3395 SDValue SrcOp = Op.getOperand(0);
3396 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3397 "Expected SPLAT_VECTOR implicit truncation");
3398 // Implicitly truncate the bits to match the official semantics of
3399 // SPLAT_VECTOR.
3401 break;
3402 }
3404 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3405 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3406 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3407 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3408 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3409 }
3410 break;
3411 }
3412 case ISD::STEP_VECTOR: {
3413 const APInt &Step = Op.getConstantOperandAPInt(0);
3414
3415 if (Step.isPowerOf2())
3416 Known.Zero.setLowBits(Step.logBase2());
3417
3419
3420 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3421 break;
3422 const APInt MinNumElts =
3423 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3424
3425 bool Overflow;
3426 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3428 .umul_ov(MinNumElts, Overflow);
3429 if (Overflow)
3430 break;
3431
3432 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3433 if (Overflow)
3434 break;
3435
3436 Known.Zero.setHighBits(MaxValue.countl_zero());
3437 break;
3438 }
3439 case ISD::BUILD_VECTOR:
3440 assert(!Op.getValueType().isScalableVector());
3441 // Collect the known bits that are shared by every demanded vector element.
3442 Known.setAllConflict();
3443 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3444 if (!DemandedElts[i])
3445 continue;
3446
3447 SDValue SrcOp = Op.getOperand(i);
3448 Known2 = computeKnownBits(SrcOp, Depth + 1);
3449
3450 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3451 if (SrcOp.getValueSizeInBits() != BitWidth) {
3452 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3453 "Expected BUILD_VECTOR implicit truncation");
3454 Known2 = Known2.trunc(BitWidth);
3455 }
3456
3457 // Known bits are the values that are shared by every demanded element.
3458 Known = Known.intersectWith(Known2);
3459
3460 // If we don't know any bits, early out.
3461 if (Known.isUnknown())
3462 break;
3463 }
3464 break;
3465 case ISD::VECTOR_COMPRESS: {
3466 SDValue Vec = Op.getOperand(0);
3467 SDValue PassThru = Op.getOperand(2);
3468 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3469 // If we don't know any bits, early out.
3470 if (Known.isUnknown())
3471 break;
3472 Known2 = computeKnownBits(Vec, Depth + 1);
3473 Known = Known.intersectWith(Known2);
3474 break;
3475 }
3476 case ISD::VECTOR_SHUFFLE: {
3477 assert(!Op.getValueType().isScalableVector());
3478 // Collect the known bits that are shared by every vector element referenced
3479 // by the shuffle.
3480 APInt DemandedLHS, DemandedRHS;
3482 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3483 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3484 DemandedLHS, DemandedRHS))
3485 break;
3486
3487 // Known bits are the values that are shared by every demanded element.
3488 Known.setAllConflict();
3489 if (!!DemandedLHS) {
3490 SDValue LHS = Op.getOperand(0);
3491 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3492 Known = Known.intersectWith(Known2);
3493 }
3494 // If we don't know any bits, early out.
3495 if (Known.isUnknown())
3496 break;
3497 if (!!DemandedRHS) {
3498 SDValue RHS = Op.getOperand(1);
3499 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3500 Known = Known.intersectWith(Known2);
3501 }
3502 break;
3503 }
3504 case ISD::VSCALE: {
3506 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3508 break;
3509 }
3510 case ISD::CONCAT_VECTORS: {
3511 if (Op.getValueType().isScalableVector())
3512 break;
3513 // Split DemandedElts and test each of the demanded subvectors.
3514 Known.setAllConflict();
3515 EVT SubVectorVT = Op.getOperand(0).getValueType();
3516 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3517 unsigned NumSubVectors = Op.getNumOperands();
3518 for (unsigned i = 0; i != NumSubVectors; ++i) {
3519 APInt DemandedSub =
3520 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3521 if (!!DemandedSub) {
3522 SDValue Sub = Op.getOperand(i);
3523 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3524 Known = Known.intersectWith(Known2);
3525 }
3526 // If we don't know any bits, early out.
3527 if (Known.isUnknown())
3528 break;
3529 }
3530 break;
3531 }
3532 case ISD::INSERT_SUBVECTOR: {
3533 if (Op.getValueType().isScalableVector())
3534 break;
3535 // Demand any elements from the subvector and the remainder from the src its
3536 // inserted into.
3537 SDValue Src = Op.getOperand(0);
3538 SDValue Sub = Op.getOperand(1);
3539 uint64_t Idx = Op.getConstantOperandVal(2);
3540 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3541 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3542 APInt DemandedSrcElts = DemandedElts;
3543 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3544
3545 Known.setAllConflict();
3546 if (!!DemandedSubElts) {
3547 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3548 if (Known.isUnknown())
3549 break; // early-out.
3550 }
3551 if (!!DemandedSrcElts) {
3552 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3553 Known = Known.intersectWith(Known2);
3554 }
3555 break;
3556 }
3558 // Offset the demanded elts by the subvector index.
3559 SDValue Src = Op.getOperand(0);
3560
3561 APInt DemandedSrcElts;
3562 if (Src.getValueType().isScalableVector())
3563 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3564 else {
3565 uint64_t Idx = Op.getConstantOperandVal(1);
3566 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3567 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3568 }
3569 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3570 break;
3571 }
3572 case ISD::SCALAR_TO_VECTOR: {
3573 if (Op.getValueType().isScalableVector())
3574 break;
3575 // We know about scalar_to_vector as much as we know about it source,
3576 // which becomes the first element of otherwise unknown vector.
3577 if (DemandedElts != 1)
3578 break;
3579
3580 SDValue N0 = Op.getOperand(0);
3581 Known = computeKnownBits(N0, Depth + 1);
3582 if (N0.getValueSizeInBits() != BitWidth)
3583 Known = Known.trunc(BitWidth);
3584
3585 break;
3586 }
3587 case ISD::BITCAST: {
3588 if (Op.getValueType().isScalableVector())
3589 break;
3590
3591 SDValue N0 = Op.getOperand(0);
3592 EVT SubVT = N0.getValueType();
3593 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3594
3595 // Ignore bitcasts from unsupported types.
3596 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3597 break;
3598
3599 // Fast handling of 'identity' bitcasts.
3600 if (BitWidth == SubBitWidth) {
3601 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3602 break;
3603 }
3604
3605 bool IsLE = getDataLayout().isLittleEndian();
3606
3607 // Bitcast 'small element' vector to 'large element' scalar/vector.
3608 if ((BitWidth % SubBitWidth) == 0) {
3609 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3610
3611 // Collect known bits for the (larger) output by collecting the known
3612 // bits from each set of sub elements and shift these into place.
3613 // We need to separately call computeKnownBits for each set of
3614 // sub elements as the knownbits for each is likely to be different.
3615 unsigned SubScale = BitWidth / SubBitWidth;
3616 APInt SubDemandedElts(NumElts * SubScale, 0);
3617 for (unsigned i = 0; i != NumElts; ++i)
3618 if (DemandedElts[i])
3619 SubDemandedElts.setBit(i * SubScale);
3620
3621 for (unsigned i = 0; i != SubScale; ++i) {
3622 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3623 Depth + 1);
3624 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3625 Known.insertBits(Known2, SubBitWidth * Shifts);
3626 }
3627 }
3628
3629 // Bitcast 'large element' scalar/vector to 'small element' vector.
3630 if ((SubBitWidth % BitWidth) == 0) {
3631 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3632
3633 // Collect known bits for the (smaller) output by collecting the known
3634 // bits from the overlapping larger input elements and extracting the
3635 // sub sections we actually care about.
3636 unsigned SubScale = SubBitWidth / BitWidth;
3637 APInt SubDemandedElts =
3638 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3639 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3640
3641 Known.setAllConflict();
3642 for (unsigned i = 0; i != NumElts; ++i)
3643 if (DemandedElts[i]) {
3644 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3645 unsigned Offset = (Shifts % SubScale) * BitWidth;
3646 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3647 // If we don't know any bits, early out.
3648 if (Known.isUnknown())
3649 break;
3650 }
3651 }
3652 break;
3653 }
3654 case ISD::AND:
3655 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3656 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3657
3658 Known &= Known2;
3659 break;
3660 case ISD::OR:
3661 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3662 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3663
3664 Known |= Known2;
3665 break;
3666 case ISD::XOR:
3667 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3668 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3669
3670 Known ^= Known2;
3671 break;
3672 case ISD::MUL: {
3673 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3674 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3675 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3676 // TODO: SelfMultiply can be poison, but not undef.
3677 if (SelfMultiply)
3678 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3679 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3680 Depth + 1);
3681 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3682
3683 // If the multiplication is known not to overflow, the product of a number
3684 // with itself is non-negative. Only do this if we didn't already computed
3685 // the opposite value for the sign bit.
3686 if (Op->getFlags().hasNoSignedWrap() &&
3687 Op.getOperand(0) == Op.getOperand(1) &&
3688 !Known.isNegative())
3689 Known.makeNonNegative();
3690 break;
3691 }
3692 case ISD::MULHU: {
3693 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3694 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3695 Known = KnownBits::mulhu(Known, Known2);
3696 break;
3697 }
3698 case ISD::MULHS: {
3699 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3700 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3701 Known = KnownBits::mulhs(Known, Known2);
3702 break;
3703 }
3704 case ISD::ABDU: {
3705 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3706 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3707 Known = KnownBits::abdu(Known, Known2);
3708 break;
3709 }
3710 case ISD::ABDS: {
3711 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3712 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3713 Known = KnownBits::abds(Known, Known2);
3714 unsigned SignBits1 =
3715 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3716 if (SignBits1 == 1)
3717 break;
3718 unsigned SignBits0 =
3719 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3720 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3721 break;
3722 }
3723 case ISD::UMUL_LOHI: {
3724 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3725 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3726 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3727 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3728 if (Op.getResNo() == 0)
3729 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3730 else
3731 Known = KnownBits::mulhu(Known, Known2);
3732 break;
3733 }
3734 case ISD::SMUL_LOHI: {
3735 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3736 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3737 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3738 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3739 if (Op.getResNo() == 0)
3740 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3741 else
3742 Known = KnownBits::mulhs(Known, Known2);
3743 break;
3744 }
3745 case ISD::AVGFLOORU: {
3746 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3747 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3748 Known = KnownBits::avgFloorU(Known, Known2);
3749 break;
3750 }
3751 case ISD::AVGCEILU: {
3752 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3753 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3754 Known = KnownBits::avgCeilU(Known, Known2);
3755 break;
3756 }
3757 case ISD::AVGFLOORS: {
3758 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3759 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3760 Known = KnownBits::avgFloorS(Known, Known2);
3761 break;
3762 }
3763 case ISD::AVGCEILS: {
3764 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3765 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3766 Known = KnownBits::avgCeilS(Known, Known2);
3767 break;
3768 }
3769 case ISD::SELECT:
3770 case ISD::VSELECT:
3771 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3772 // If we don't know any bits, early out.
3773 if (Known.isUnknown())
3774 break;
3775 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3776
3777 // Only known if known in both the LHS and RHS.
3778 Known = Known.intersectWith(Known2);
3779 break;
3780 case ISD::SELECT_CC:
3781 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3782 // If we don't know any bits, early out.
3783 if (Known.isUnknown())
3784 break;
3785 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3786
3787 // Only known if known in both the LHS and RHS.
3788 Known = Known.intersectWith(Known2);
3789 break;
3790 case ISD::SMULO:
3791 case ISD::UMULO:
3792 if (Op.getResNo() != 1)
3793 break;
3794 // The boolean result conforms to getBooleanContents.
3795 // If we know the result of a setcc has the top bits zero, use this info.
3796 // We know that we have an integer-based boolean since these operations
3797 // are only available for integer.
3798 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3800 BitWidth > 1)
3801 Known.Zero.setBitsFrom(1);
3802 break;
3803 case ISD::SETCC:
3804 case ISD::SETCCCARRY:
3805 case ISD::STRICT_FSETCC:
3806 case ISD::STRICT_FSETCCS: {
3807 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3808 // If we know the result of a setcc has the top bits zero, use this info.
3809 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3811 BitWidth > 1)
3812 Known.Zero.setBitsFrom(1);
3813 break;
3814 }
3815 case ISD::SHL: {
3816 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3817 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3818
3819 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3820 bool NSW = Op->getFlags().hasNoSignedWrap();
3821
3822 bool ShAmtNonZero = Known2.isNonZero();
3823
3824 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3825
3826 // Minimum shift low bits are known zero.
3827 if (std::optional<unsigned> ShMinAmt =
3828 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3829 Known.Zero.setLowBits(*ShMinAmt);
3830 break;
3831 }
3832 case ISD::SRL:
3833 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3834 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3835 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3836 Op->getFlags().hasExact());
3837
3838 // Minimum shift high bits are known zero.
3839 if (std::optional<unsigned> ShMinAmt =
3840 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3841 Known.Zero.setHighBits(*ShMinAmt);
3842 break;
3843 case ISD::SRA:
3844 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3845 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3846 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3847 Op->getFlags().hasExact());
3848 break;
3849 case ISD::ROTL:
3850 case ISD::ROTR:
3851 if (ConstantSDNode *C =
3852 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3853 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3854
3855 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3856
3857 // Canonicalize to ROTR.
3858 if (Opcode == ISD::ROTL && Amt != 0)
3859 Amt = BitWidth - Amt;
3860
3861 Known.Zero = Known.Zero.rotr(Amt);
3862 Known.One = Known.One.rotr(Amt);
3863 }
3864 break;
3865 case ISD::FSHL:
3866 case ISD::FSHR:
3867 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3868 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3869
3870 // For fshl, 0-shift returns the 1st arg.
3871 // For fshr, 0-shift returns the 2nd arg.
3872 if (Amt == 0) {
3873 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3874 DemandedElts, Depth + 1);
3875 break;
3876 }
3877
3878 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3879 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3880 const APInt ShAmt(BitWidth, Amt);
3881 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3882 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3883 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3884 : KnownBits::fshr(Known, Known2, ShAmt);
3885 }
3886 break;
3887 case ISD::SHL_PARTS:
3888 case ISD::SRA_PARTS:
3889 case ISD::SRL_PARTS: {
3890 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3891
3892 // Collect lo/hi source values and concatenate.
3893 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3894 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3895 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3896 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3897 Known = Known2.concat(Known);
3898
3899 // Collect shift amount.
3900 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3901
3902 if (Opcode == ISD::SHL_PARTS)
3903 Known = KnownBits::shl(Known, Known2);
3904 else if (Opcode == ISD::SRA_PARTS)
3905 Known = KnownBits::ashr(Known, Known2);
3906 else // if (Opcode == ISD::SRL_PARTS)
3907 Known = KnownBits::lshr(Known, Known2);
3908
3909 // TODO: Minimum shift low/high bits are known zero.
3910
3911 if (Op.getResNo() == 0)
3912 Known = Known.extractBits(LoBits, 0);
3913 else
3914 Known = Known.extractBits(HiBits, LoBits);
3915 break;
3916 }
3918 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3919 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3920 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3921 break;
3922 }
3923 case ISD::CTTZ:
3924 case ISD::CTTZ_ZERO_POISON: {
3925 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3926 // If we have a known 1, its position is our upper bound.
3927 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3928 unsigned LowBits = llvm::bit_width(PossibleTZ);
3929 Known.Zero.setBitsFrom(LowBits);
3930 break;
3931 }
3932 case ISD::CTLZ:
3933 case ISD::CTLZ_ZERO_POISON: {
3934 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3935 // If we have a known 1, its position is our upper bound.
3936 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3937 unsigned LowBits = llvm::bit_width(PossibleLZ);
3938 Known.Zero.setBitsFrom(LowBits);
3939 break;
3940 }
3941 case ISD::CTLS: {
3942 unsigned MinRedundantSignBits =
3943 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3944 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3946 Known = Range.toKnownBits();
3947 break;
3948 }
3949 case ISD::CTPOP: {
3950 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3951 // If we know some of the bits are zero, they can't be one.
3952 unsigned PossibleOnes = Known2.countMaxPopulation();
3953 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3954 break;
3955 }
3956 case ISD::PARITY: {
3957 // Parity returns 0 everywhere but the LSB.
3958 Known.Zero.setBitsFrom(1);
3959 break;
3960 }
3961 case ISD::PDEP: {
3962 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3963 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3964 Known = KnownBits::pdep(Known2, Known);
3965 break;
3966 }
3967 case ISD::PEXT: {
3968 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3969 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3970 Known = KnownBits::pext(Known2, Known);
3971 break;
3972 }
3973 case ISD::CLMUL: {
3974 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3975 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3976 Known = KnownBits::clmul(Known, Known2);
3977 break;
3978 }
3979 case ISD::MGATHER:
3980 case ISD::MLOAD: {
3981 ISD::LoadExtType ETy =
3982 (Opcode == ISD::MGATHER)
3983 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3984 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3985 if (ETy == ISD::ZEXTLOAD) {
3986 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3987 KnownBits Known0(MemVT.getScalarSizeInBits());
3988 return Known0.zext(BitWidth);
3989 }
3990 break;
3991 }
3992 case ISD::LOAD: {
3994 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3995 if (ISD::isNON_EXTLoad(LD) && Cst) {
3996 // Determine any common known bits from the loaded constant pool value.
3997 Type *CstTy = Cst->getType();
3998 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3999 !Op.getValueType().isScalableVector()) {
4000 // If its a vector splat, then we can (quickly) reuse the scalar path.
4001 // NOTE: We assume all elements match and none are UNDEF.
4002 if (CstTy->isVectorTy()) {
4003 if (const Constant *Splat = Cst->getSplatValue()) {
4004 Cst = Splat;
4005 CstTy = Cst->getType();
4006 }
4007 }
4008 // TODO - do we need to handle different bitwidths?
4009 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4010 // Iterate across all vector elements finding common known bits.
4011 Known.setAllConflict();
4012 for (unsigned i = 0; i != NumElts; ++i) {
4013 if (!DemandedElts[i])
4014 continue;
4015 if (Constant *Elt = Cst->getAggregateElement(i)) {
4016 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4017 const APInt &Value = CInt->getValue();
4018 Known.One &= Value;
4019 Known.Zero &= ~Value;
4020 continue;
4021 }
4022 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4023 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4024 Known.One &= Value;
4025 Known.Zero &= ~Value;
4026 continue;
4027 }
4028 }
4029 Known.One.clearAllBits();
4030 Known.Zero.clearAllBits();
4031 break;
4032 }
4033 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4034 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4035 Known = KnownBits::makeConstant(CInt->getValue());
4036 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4037 Known =
4038 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4039 }
4040 }
4041 }
4042 } else if (Op.getResNo() == 0) {
4043 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4044 KnownBits KnownScalarMemory(ScalarMemorySize);
4045 if (const MDNode *MD = LD->getRanges())
4046 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4047
4048 // Extend the Known bits from memory to the size of the scalar result.
4049 if (ISD::isZEXTLoad(Op.getNode()))
4050 Known = KnownScalarMemory.zext(BitWidth);
4051 else if (ISD::isSEXTLoad(Op.getNode()))
4052 Known = KnownScalarMemory.sext(BitWidth);
4053 else if (ISD::isEXTLoad(Op.getNode()))
4054 Known = KnownScalarMemory.anyext(BitWidth);
4055 else
4056 Known = KnownScalarMemory;
4057 assert(Known.getBitWidth() == BitWidth);
4058 return Known;
4059 }
4060 break;
4061 }
4063 if (Op.getValueType().isScalableVector())
4064 break;
4065 EVT InVT = Op.getOperand(0).getValueType();
4066 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4067 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4068 Known = Known.zext(BitWidth);
4069 break;
4070 }
4071 case ISD::ZERO_EXTEND: {
4072 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4073 Known = Known.zext(BitWidth);
4074 break;
4075 }
4077 if (Op.getValueType().isScalableVector())
4078 break;
4079 EVT InVT = Op.getOperand(0).getValueType();
4080 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4081 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4082 // If the sign bit is known to be zero or one, then sext will extend
4083 // it to the top bits, else it will just zext.
4084 Known = Known.sext(BitWidth);
4085 break;
4086 }
4087 case ISD::SIGN_EXTEND: {
4088 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4089 // If the sign bit is known to be zero or one, then sext will extend
4090 // it to the top bits, else it will just zext.
4091 Known = Known.sext(BitWidth);
4092 break;
4093 }
4095 if (Op.getValueType().isScalableVector())
4096 break;
4097 EVT InVT = Op.getOperand(0).getValueType();
4098 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4099 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4100 Known = Known.anyext(BitWidth);
4101 break;
4102 }
4103 case ISD::ANY_EXTEND: {
4104 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4105 Known = Known.anyext(BitWidth);
4106 break;
4107 }
4108 case ISD::TRUNCATE: {
4109 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4110 Known = Known.trunc(BitWidth);
4111 break;
4112 }
4113 case ISD::TRUNCATE_SSAT_S: {
4114 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4115 Known = Known.truncSSat(BitWidth);
4116 break;
4117 }
4118 case ISD::TRUNCATE_SSAT_U: {
4119 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4120 Known = Known.truncSSatU(BitWidth);
4121 break;
4122 }
4123 case ISD::TRUNCATE_USAT_U: {
4124 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4125 Known = Known.truncUSat(BitWidth);
4126 break;
4127 }
4128 case ISD::AssertZext: {
4129 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4131 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4132 Known.Zero |= (~InMask);
4133 Known.One &= (~Known.Zero);
4134 break;
4135 }
4136 case ISD::AssertAlign: {
4137 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4138 assert(LogOfAlign != 0);
4139
4140 // TODO: Should use maximum with source
4141 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4142 // well as clearing one bits.
4143 Known.Zero.setLowBits(LogOfAlign);
4144 Known.One.clearLowBits(LogOfAlign);
4145 break;
4146 }
4147 case ISD::AssertNoFPClass: {
4148 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4149
4150 FPClassTest NoFPClass =
4151 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4152 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4153 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4154 // Cannot be negative.
4155 Known.makeNonNegative();
4156 }
4157
4158 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4159 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4160 // Cannot be positive.
4161 Known.makeNegative();
4162 }
4163
4164 break;
4165 }
4166 case ISD::FABS:
4167 // fabs clears the sign bit
4168 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4169 Known.makeNonNegative();
4170 break;
4171 case ISD::FGETSIGN:
4172 // All bits are zero except the low bit.
4173 Known.Zero.setBitsFrom(1);
4174 break;
4175 case ISD::ADD: {
4176 SDNodeFlags Flags = Op.getNode()->getFlags();
4177 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4178 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4179 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4181 Op.getOperand(0), DemandedElts,
4183 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4184 Flags.hasNoUnsignedWrap(), SelfAdd);
4185 break;
4186 }
4187 case ISD::SUB: {
4188 SDNodeFlags Flags = Op.getNode()->getFlags();
4189 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4190 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4191 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4192 Flags.hasNoUnsignedWrap());
4193 break;
4194 }
4195 case ISD::USUBO:
4196 case ISD::SSUBO:
4197 case ISD::USUBO_CARRY:
4198 case ISD::SSUBO_CARRY:
4199 if (Op.getResNo() == 1) {
4200 // If we know the result of a setcc has the top bits zero, use this info.
4201 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4203 BitWidth > 1)
4204 Known.Zero.setBitsFrom(1);
4205 break;
4206 }
4207 [[fallthrough]];
4208 case ISD::SUBC: {
4209 assert(Op.getResNo() == 0 &&
4210 "We only compute knownbits for the difference here.");
4211
4212 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4213 KnownBits Borrow(1);
4214 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4215 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4216 // Borrow has bit width 1
4217 Borrow = Borrow.trunc(1);
4218 } else {
4219 Borrow.setAllZero();
4220 }
4221
4222 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4223 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4224 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4225 break;
4226 }
4227 case ISD::UADDO:
4228 case ISD::SADDO:
4229 case ISD::UADDO_CARRY:
4230 case ISD::SADDO_CARRY:
4231 if (Op.getResNo() == 1) {
4232 // If we know the result of a setcc has the top bits zero, use this info.
4233 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4235 BitWidth > 1)
4236 Known.Zero.setBitsFrom(1);
4237 break;
4238 }
4239 [[fallthrough]];
4240 case ISD::ADDC:
4241 case ISD::ADDE: {
4242 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4243
4244 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4245 KnownBits Carry(1);
4246 if (Opcode == ISD::ADDE)
4247 // Can't track carry from glue, set carry to unknown.
4248 Carry.resetAll();
4249 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4250 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4251 // Carry has bit width 1
4252 Carry = Carry.trunc(1);
4253 } else {
4254 Carry.setAllZero();
4255 }
4256
4257 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4258 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4259 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4260 break;
4261 }
4262 case ISD::UDIV: {
4263 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4264 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4265 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4266 break;
4267 }
4268 case ISD::SDIV: {
4269 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4270 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4271 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4272 break;
4273 }
4274 case ISD::SREM: {
4275 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4276 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4277 Known = KnownBits::srem(Known, Known2);
4278 break;
4279 }
4280 case ISD::UREM: {
4281 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4282 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4283 Known = KnownBits::urem(Known, Known2);
4284 break;
4285 }
4286 case ISD::EXTRACT_ELEMENT: {
4287 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4288 const unsigned Index = Op.getConstantOperandVal(1);
4289 const unsigned EltBitWidth = Op.getValueSizeInBits();
4290
4291 // Remove low part of known bits mask
4292 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4293 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4294
4295 // Remove high part of known bit mask
4296 Known = Known.trunc(EltBitWidth);
4297 break;
4298 }
4300 SDValue InVec = Op.getOperand(0);
4301 SDValue EltNo = Op.getOperand(1);
4302 EVT VecVT = InVec.getValueType();
4303 // computeKnownBits not yet implemented for scalable vectors.
4304 if (VecVT.isScalableVector())
4305 break;
4306 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4307 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4308
4309 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4310 // anything about the extended bits.
4311 if (BitWidth > EltBitWidth)
4312 Known = Known.trunc(EltBitWidth);
4313
4314 // If we know the element index, just demand that vector element, else for
4315 // an unknown element index, ignore DemandedElts and demand them all.
4316 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4317 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4318 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4319 DemandedSrcElts =
4320 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4321
4322 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4323 if (BitWidth > EltBitWidth)
4324 Known = Known.anyext(BitWidth);
4325 break;
4326 }
4328 if (Op.getValueType().isScalableVector())
4329 break;
4330
4331 // If we know the element index, split the demand between the
4332 // source vector and the inserted element, otherwise assume we need
4333 // the original demanded vector elements and the value.
4334 SDValue InVec = Op.getOperand(0);
4335 SDValue InVal = Op.getOperand(1);
4336 SDValue EltNo = Op.getOperand(2);
4337 bool DemandedVal = true;
4338 APInt DemandedVecElts = DemandedElts;
4339 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4340 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4341 unsigned EltIdx = CEltNo->getZExtValue();
4342 DemandedVal = !!DemandedElts[EltIdx];
4343 DemandedVecElts.clearBit(EltIdx);
4344 }
4345 Known.setAllConflict();
4346 if (DemandedVal) {
4347 Known2 = computeKnownBits(InVal, Depth + 1);
4348 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4349 }
4350 if (!!DemandedVecElts) {
4351 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4352 Known = Known.intersectWith(Known2);
4353 }
4354 break;
4355 }
4356 case ISD::BITREVERSE: {
4357 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4358 Known = Known2.reverseBits();
4359 break;
4360 }
4361 case ISD::BSWAP: {
4362 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4363 Known = Known2.byteSwap();
4364 break;
4365 }
4366 case ISD::ABS:
4367 case ISD::ABS_MIN_POISON: {
4368 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4369 Known = Known2.abs();
4370 Known.Zero.setHighBits(
4371 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4372 break;
4373 }
4374 case ISD::USUBSAT: {
4375 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4376 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4377 Known = KnownBits::usub_sat(Known, Known2);
4378 break;
4379 }
4380 case ISD::UMIN: {
4381 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4382 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4383 Known = KnownBits::umin(Known, Known2);
4384 break;
4385 }
4386 case ISD::UMAX: {
4387 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4388 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4389 Known = KnownBits::umax(Known, Known2);
4390 break;
4391 }
4392 case ISD::SMIN:
4393 case ISD::SMAX: {
4394 // If we have a clamp pattern, we know that the number of sign bits will be
4395 // the minimum of the clamp min/max range.
4396 bool IsMax = (Opcode == ISD::SMAX);
4397 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4398 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4399 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4400 CstHigh =
4401 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4402 if (CstLow && CstHigh) {
4403 if (!IsMax)
4404 std::swap(CstLow, CstHigh);
4405
4406 const APInt &ValueLow = CstLow->getAPIntValue();
4407 const APInt &ValueHigh = CstHigh->getAPIntValue();
4408 if (ValueLow.sle(ValueHigh)) {
4409 unsigned LowSignBits = ValueLow.getNumSignBits();
4410 unsigned HighSignBits = ValueHigh.getNumSignBits();
4411 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4412 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4413 Known.One.setHighBits(MinSignBits);
4414 break;
4415 }
4416 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4417 Known.Zero.setHighBits(MinSignBits);
4418 break;
4419 }
4420 }
4421 }
4422
4423 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4424 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4425 if (IsMax)
4426 Known = KnownBits::smax(Known, Known2);
4427 else
4428 Known = KnownBits::smin(Known, Known2);
4429
4430 // For SMAX, if CstLow is non-negative we know the result will be
4431 // non-negative and thus all sign bits are 0.
4432 // TODO: There's an equivalent of this for smin with negative constant for
4433 // known ones.
4434 if (IsMax && CstLow) {
4435 const APInt &ValueLow = CstLow->getAPIntValue();
4436 if (ValueLow.isNonNegative()) {
4437 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4438 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4439 }
4440 }
4441
4442 break;
4443 }
4444 case ISD::UINT_TO_FP: {
4445 Known.makeNonNegative();
4446 break;
4447 }
4448 case ISD::SINT_TO_FP: {
4449 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4450 if (Known2.isNonNegative())
4451 Known.makeNonNegative();
4452 else if (Known2.isNegative())
4453 Known.makeNegative();
4454 break;
4455 }
4456 case ISD::FP_TO_UINT_SAT: {
4457 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4458 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4460 break;
4461 }
4462 case ISD::ATOMIC_LOAD: {
4463 // If we are looking at the loaded value.
4464 if (Op.getResNo() == 0) {
4465 auto *AT = cast<AtomicSDNode>(Op);
4466 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4467 KnownBits KnownScalarMemory(ScalarMemorySize);
4468 if (const MDNode *MD = AT->getRanges())
4469 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4470
4471 switch (AT->getExtensionType()) {
4472 case ISD::ZEXTLOAD:
4473 Known = KnownScalarMemory.zext(BitWidth);
4474 break;
4475 case ISD::SEXTLOAD:
4476 Known = KnownScalarMemory.sext(BitWidth);
4477 break;
4478 case ISD::EXTLOAD:
4479 switch (TLI->getExtendForAtomicOps()) {
4480 case ISD::ZERO_EXTEND:
4481 Known = KnownScalarMemory.zext(BitWidth);
4482 break;
4483 case ISD::SIGN_EXTEND:
4484 Known = KnownScalarMemory.sext(BitWidth);
4485 break;
4486 default:
4487 Known = KnownScalarMemory.anyext(BitWidth);
4488 break;
4489 }
4490 break;
4491 case ISD::NON_EXTLOAD:
4492 Known = KnownScalarMemory;
4493 break;
4494 }
4495 assert(Known.getBitWidth() == BitWidth);
4496 }
4497 break;
4498 }
4500 if (Op.getResNo() == 1) {
4501 // The boolean result conforms to getBooleanContents.
4502 // If we know the result of a setcc has the top bits zero, use this info.
4503 // We know that we have an integer-based boolean since these operations
4504 // are only available for integer.
4505 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4507 BitWidth > 1)
4508 Known.Zero.setBitsFrom(1);
4509 break;
4510 }
4511 [[fallthrough]];
4513 case ISD::ATOMIC_SWAP:
4524 case ISD::ATOMIC_LOAD_UMAX: {
4525 // If we are looking at the loaded value.
4526 if (Op.getResNo() == 0) {
4527 auto *AT = cast<AtomicSDNode>(Op);
4528 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4529
4530 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4531 Known.Zero.setBitsFrom(MemBits);
4532 }
4533 break;
4534 }
4535 case ISD::FrameIndex:
4536 case ISD::TargetFrameIndex: {
4537 const MachineFunction &MF = getMachineFunction();
4538 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4539 TLI->computeKnownBitsForStackObjectPointer(
4540 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4541 break;
4542 }
4543
4544 default:
4545 if (Opcode < ISD::BUILTIN_OP_END)
4546 break;
4547 [[fallthrough]];
4551 // Allow the target to implement this method for its nodes.
4552 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4553 break;
4554 }
4555
4556 return Known;
4557}
4558
4559/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4572
4575 // X + 0 never overflow
4576 if (isNullConstant(N1))
4577 return OFK_Never;
4578
4579 // If both operands each have at least two sign bits, the addition
4580 // cannot overflow.
4581 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4582 return OFK_Never;
4583
4584 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4585 return OFK_Sometime;
4586}
4587
4590 // X + 0 never overflow
4591 if (isNullConstant(N1))
4592 return OFK_Never;
4593
4594 // mulhi + 1 never overflow
4595 KnownBits N1Known = computeKnownBits(N1);
4596 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4597 N1Known.getMaxValue().ult(2))
4598 return OFK_Never;
4599
4600 KnownBits N0Known = computeKnownBits(N0);
4601 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4602 N0Known.getMaxValue().ult(2))
4603 return OFK_Never;
4604
4605 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4606 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4607 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4608 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4609}
4610
4613 // X - 0 never overflow
4614 if (isNullConstant(N1))
4615 return OFK_Never;
4616
4617 // If both operands each have at least two sign bits, the subtraction
4618 // cannot overflow.
4619 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4620 return OFK_Never;
4621
4622 KnownBits N0Known = computeKnownBits(N0);
4623 KnownBits N1Known = computeKnownBits(N1);
4624 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4625 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4626 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4627}
4628
4631 // X - 0 never overflow
4632 if (isNullConstant(N1))
4633 return OFK_Never;
4634
4635 ConstantRange N0Range =
4636 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4637 ConstantRange N1Range =
4638 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4639 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4640}
4641
4644 // X * 0 and X * 1 never overflow.
4645 if (isNullConstant(N1) || isOneConstant(N1))
4646 return OFK_Never;
4647
4650 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4651}
4652
4655 // X * 0 and X * 1 never overflow.
4656 if (isNullConstant(N1) || isOneConstant(N1))
4657 return OFK_Never;
4658
4659 // Get the size of the result.
4660 unsigned BitWidth = N0.getScalarValueSizeInBits();
4661
4662 // Sum of the sign bits.
4663 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4664
4665 // If we have enough sign bits, then there's no overflow.
4666 if (SignBits > BitWidth + 1)
4667 return OFK_Never;
4668
4669 if (SignBits == BitWidth + 1) {
4670 // The overflow occurs when the true multiplication of the
4671 // the operands is the minimum negative number.
4672 KnownBits N0Known = computeKnownBits(N0);
4673 KnownBits N1Known = computeKnownBits(N1);
4674 // If one of the operands is non-negative, then there's no
4675 // overflow.
4676 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4677 return OFK_Never;
4678 }
4679
4680 return OFK_Sometime;
4681}
4682
4684 unsigned Depth) const {
4685 APInt DemandedElts = getDemandAllEltsMask(Op);
4686 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4687}
4688
4690 const APInt &DemandedElts,
4691 bool ForSigned,
4692 unsigned Depth) const {
4693 EVT VT = Op.getValueType();
4694 unsigned BitWidth = VT.getScalarSizeInBits();
4695
4696 if (Depth >= MaxRecursionDepth)
4697 return ConstantRange::getFull(BitWidth);
4698
4699 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4700 return ConstantRange(C->getAPIntValue());
4701
4702 unsigned Opcode = Op.getOpcode();
4703 switch (Opcode) {
4704 case ISD::VSCALE: {
4706 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4707 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4708 }
4709 default:
4710 break;
4711 }
4712
4713 return ConstantRange::getFull(BitWidth);
4714}
4715
4718 unsigned Depth) const {
4719 APInt DemandedElts = getDemandAllEltsMask(Op);
4720 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4721 Depth);
4722}
4723
4725 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4726 unsigned Depth) const {
4727 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4729 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4732 return CR1.intersectWith(CR2, RangeType);
4733}
4734
4736 unsigned Depth) const {
4737 APInt DemandedElts = getDemandAllEltsMask(Val);
4738 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4739}
4740
4742 const APInt &DemandedElts,
4743 bool OrZero, unsigned Depth) const {
4744 if (Depth >= MaxRecursionDepth)
4745 return false; // Limit search depth.
4746
4747 EVT OpVT = Val.getValueType();
4748 unsigned BitWidth = OpVT.getScalarSizeInBits();
4749 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4750 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4751 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4752 assert(
4753 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4754 "Unexpected vector size");
4755
4756 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4757 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4758 return (OrZero && V.isZero()) || V.isPowerOf2();
4759 };
4760
4761 // Is the constant a known power of 2 or zero?
4762 if (ISD::matchUnaryPredicate(Val, IsPowerOfTwoOrZero))
4763 return true;
4764
4765 switch (Val.getOpcode()) {
4766 case ISD::BUILD_VECTOR:
4767 // Are all operands of a build vector constant powers of two or zero?
4768 if (all_of(enumerate(Val->ops()), [&](auto P) {
4769 auto *C = dyn_cast<ConstantSDNode>(P.value());
4770 return !DemandedElts[P.index()] || (C && IsPowerOfTwoOrZero(C));
4771 }))
4772 return true;
4773 break;
4774
4775 case ISD::SPLAT_VECTOR:
4776 // Is the operand of a splat vector a constant power of two?
4777 if (auto *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
4778 if (IsPowerOfTwoOrZero(C))
4779 return true;
4780 break;
4781
4783 SDValue InVec = Val.getOperand(0);
4784 SDValue EltNo = Val.getOperand(1);
4785 EVT VecVT = InVec.getValueType();
4786
4787 // Skip scalable vectors or implicit extensions.
4788 if (VecVT.isScalableVector() ||
4789 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4790 break;
4791
4792 // If we know the element index, just demand that vector element, else for
4793 // an unknown element index, ignore DemandedElts and demand them all.
4794 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4795 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4796 APInt DemandedSrcElts =
4797 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4798 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4799 : APInt::getAllOnes(NumSrcElts);
4800 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4801 }
4802
4803 case ISD::AND: {
4804 // Looking for `x & -x` pattern:
4805 // If x == 0:
4806 // x & -x -> 0
4807 // If x != 0:
4808 // x & -x -> non-zero pow2
4809 // so if we find the pattern return whether we know `x` is non-zero.
4810 SDValue X, Z;
4811 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4812 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4813 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4814 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4815 break;
4816 }
4817
4818 case ISD::SHL: {
4819 // A left-shift of a constant one will have exactly one bit set because
4820 // shifting the bit off the end is undefined.
4821 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4822 if (C && C->getAPIntValue() == 1)
4823 return true;
4824 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4825 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4826 Depth + 1);
4827 }
4828
4829 case ISD::SRL: {
4830 // A logical right-shift of a constant sign-bit will have exactly
4831 // one bit set.
4832 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4833 if (C && C->getAPIntValue().isSignMask())
4834 return true;
4835 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4836 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4837 Depth + 1);
4838 }
4839
4840 case ISD::TRUNCATE:
4841 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4842 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4843 Depth + 1);
4844
4845 case ISD::ROTL:
4846 case ISD::ROTR:
4847 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4848 Depth + 1);
4849 case ISD::BSWAP:
4850 case ISD::BITREVERSE:
4851 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4852 Depth + 1);
4853
4854 case ISD::SMIN:
4855 case ISD::SMAX:
4856 case ISD::UMIN:
4857 case ISD::UMAX:
4858 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4859 Depth + 1) &&
4860 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4861 Depth + 1);
4862
4863 case ISD::SELECT:
4864 case ISD::VSELECT:
4865 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4866 Depth + 1) &&
4867 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4868 Depth + 1);
4869
4870 case ISD::ZERO_EXTEND:
4871 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4872 Depth + 1);
4873
4874 case ISD::VSCALE:
4875 // vscale(power-of-two) is a power-of-two
4876 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4877 Depth + 1);
4878
4879 case ISD::VECTOR_SHUFFLE: {
4881 // Demanded elements with undef shuffle mask elements are unknown
4882 // - we cannot guarantee they are a power of two, so return false.
4883 APInt DemandedLHS, DemandedRHS;
4885 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4886 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4887 DemandedLHS, DemandedRHS))
4888 return false;
4889
4890 // All demanded elements from LHS must be known power of two.
4891 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4892 OrZero, Depth + 1))
4893 return false;
4894
4895 // All demanded elements from RHS must be known power of two.
4896 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4897 OrZero, Depth + 1))
4898 return false;
4899
4900 return true;
4901 }
4902 }
4903
4904 // More could be done here, though the above checks are enough
4905 // to handle some common cases.
4906 return false;
4907}
4908
4910 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4911 return C1->getValueAPF().getExactLog2Abs() >= 0;
4912
4913 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4914 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4915
4916 return false;
4917}
4918
4920 APInt DemandedElts = getDemandAllEltsMask(Op);
4921 return ComputeNumSignBits(Op, DemandedElts, Depth);
4922}
4923
4924unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4925 unsigned Depth) const {
4926 EVT VT = Op.getValueType();
4927 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4928 unsigned VTBits = VT.getScalarSizeInBits();
4929 unsigned NumElts = DemandedElts.getBitWidth();
4930 unsigned Tmp, Tmp2;
4931 unsigned FirstAnswer = 1;
4932
4933 assert((!VT.isScalableVector() || NumElts == 1) &&
4934 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4935
4936 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4937 const APInt &Val = C->getAPIntValue();
4938 return Val.getNumSignBits();
4939 }
4940
4941 if (Depth >= MaxRecursionDepth)
4942 return 1; // Limit search depth.
4943
4944 if (!DemandedElts)
4945 return 1; // No demanded elts, better to assume we don't know anything.
4946
4947 unsigned Opcode = Op.getOpcode();
4948 switch (Opcode) {
4949 default: break;
4950 case ISD::AssertSext:
4951 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4952 return VTBits-Tmp+1;
4953 case ISD::AssertZext:
4954 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4955 return VTBits-Tmp;
4956 case ISD::FREEZE:
4957 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4959 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4960 break;
4961 case ISD::MERGE_VALUES:
4962 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4963 Depth + 1);
4964 case ISD::SPLAT_VECTOR: {
4965 // Check if the sign bits of source go down as far as the truncated value.
4966 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4967 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4968 if (NumSrcSignBits > (NumSrcBits - VTBits))
4969 return NumSrcSignBits - (NumSrcBits - VTBits);
4970 break;
4971 }
4972 case ISD::BUILD_VECTOR:
4973 assert(!VT.isScalableVector());
4974 Tmp = VTBits;
4975 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4976 if (!DemandedElts[i])
4977 continue;
4978
4979 SDValue SrcOp = Op.getOperand(i);
4980 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4981 // for constant nodes to ensure we only look at the sign bits.
4983 APInt T = C->getAPIntValue().trunc(VTBits);
4984 Tmp2 = T.getNumSignBits();
4985 } else {
4986 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4987
4988 if (SrcOp.getValueSizeInBits() != VTBits) {
4989 assert(SrcOp.getValueSizeInBits() > VTBits &&
4990 "Expected BUILD_VECTOR implicit truncation");
4991 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4992 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4993 }
4994 }
4995 Tmp = std::min(Tmp, Tmp2);
4996 }
4997 return Tmp;
4998
4999 case ISD::VECTOR_COMPRESS: {
5000 SDValue Vec = Op.getOperand(0);
5001 SDValue PassThru = Op.getOperand(2);
5002 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5003 if (Tmp == 1)
5004 return 1;
5005 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5006 Tmp = std::min(Tmp, Tmp2);
5007 return Tmp;
5008 }
5009
5010 case ISD::VECTOR_SHUFFLE: {
5011 // Collect the minimum number of sign bits that are shared by every vector
5012 // element referenced by the shuffle.
5013 APInt DemandedLHS, DemandedRHS;
5015 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5016 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5017 DemandedLHS, DemandedRHS))
5018 return 1;
5019
5020 Tmp = std::numeric_limits<unsigned>::max();
5021 if (!!DemandedLHS)
5022 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5023 if (!!DemandedRHS) {
5024 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5025 Tmp = std::min(Tmp, Tmp2);
5026 }
5027 // If we don't know anything, early out and try computeKnownBits fall-back.
5028 if (Tmp == 1)
5029 break;
5030 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5031 return Tmp;
5032 }
5033
5034 case ISD::BITCAST: {
5035 if (VT.isScalableVector())
5036 break;
5037 SDValue N0 = Op.getOperand(0);
5038 EVT SrcVT = N0.getValueType();
5039 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5040
5041 // Ignore bitcasts from unsupported types..
5042 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5043 break;
5044
5045 // Fast handling of 'identity' bitcasts.
5046 if (VTBits == SrcBits)
5047 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5048
5049 bool IsLE = getDataLayout().isLittleEndian();
5050
5051 // Bitcast 'large element' scalar/vector to 'small element' vector.
5052 if ((SrcBits % VTBits) == 0) {
5053 assert(VT.isVector() && "Expected bitcast to vector");
5054
5055 unsigned Scale = SrcBits / VTBits;
5056 APInt SrcDemandedElts =
5057 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5058
5059 // Fast case - sign splat can be simply split across the small elements.
5060 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5061 if (Tmp == SrcBits)
5062 return VTBits;
5063
5064 // Slow case - determine how far the sign extends into each sub-element.
5065 Tmp2 = VTBits;
5066 for (unsigned i = 0; i != NumElts; ++i)
5067 if (DemandedElts[i]) {
5068 unsigned SubOffset = i % Scale;
5069 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5070 SubOffset = SubOffset * VTBits;
5071 if (Tmp <= SubOffset)
5072 return 1;
5073 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5074 }
5075 return Tmp2;
5076 }
5077 break;
5078 }
5079
5081 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5082 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5083 return VTBits - Tmp + 1;
5084 case ISD::SIGN_EXTEND:
5085 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5086 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5088 // Max of the input and what this extends.
5089 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5090 Tmp = VTBits-Tmp+1;
5091 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5092 return std::max(Tmp, Tmp2);
5094 if (VT.isScalableVector())
5095 break;
5096 SDValue Src = Op.getOperand(0);
5097 EVT SrcVT = Src.getValueType();
5098 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5099 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5100 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5101 }
5102 case ISD::SRA:
5103 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5104 // SRA X, C -> adds C sign bits.
5105 if (std::optional<unsigned> ShAmt =
5106 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5107 Tmp = std::min(Tmp + *ShAmt, VTBits);
5108 return Tmp;
5109 case ISD::SHL:
5110 if (std::optional<ConstantRange> ShAmtRange =
5111 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5112 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5113 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5114 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5115 // shifted out, then we can compute the number of sign bits for the
5116 // operand being extended. A future improvement could be to pass along the
5117 // "shifted left by" information in the recursive calls to
5118 // ComputeKnownSignBits. Allowing us to handle this more generically.
5119 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5120 SDValue Ext = Op.getOperand(0);
5121 EVT ExtVT = Ext.getValueType();
5122 SDValue Extendee = Ext.getOperand(0);
5123 EVT ExtendeeVT = Extendee.getValueType();
5124 unsigned SizeDifference =
5125 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5126 if (SizeDifference <= MinShAmt) {
5127 Tmp = SizeDifference +
5128 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5129 if (MaxShAmt < Tmp)
5130 return Tmp - MaxShAmt;
5131 }
5132 }
5133 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5134 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5135 if (MaxShAmt < Tmp)
5136 return Tmp - MaxShAmt;
5137 }
5138 break;
5139 case ISD::AND:
5140 case ISD::OR:
5141 case ISD::XOR: // NOT is handled here.
5142 // Logical binary ops preserve the number of sign bits at the worst.
5143 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5144 if (Tmp != 1) {
5145 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5146 FirstAnswer = std::min(Tmp, Tmp2);
5147 // We computed what we know about the sign bits as our first
5148 // answer. Now proceed to the generic code that uses
5149 // computeKnownBits, and pick whichever answer is better.
5150 }
5151 break;
5152
5153 case ISD::SELECT:
5154 case ISD::VSELECT:
5155 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5156 if (Tmp == 1) return 1; // Early out.
5157 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5158 return std::min(Tmp, Tmp2);
5159 case ISD::SELECT_CC:
5160 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5161 if (Tmp == 1) return 1; // Early out.
5162 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5163 return std::min(Tmp, Tmp2);
5164
5165 case ISD::SMIN:
5166 case ISD::SMAX: {
5167 // If we have a clamp pattern, we know that the number of sign bits will be
5168 // the minimum of the clamp min/max range.
5169 bool IsMax = (Opcode == ISD::SMAX);
5170 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5171 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5172 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5173 CstHigh =
5174 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5175 if (CstLow && CstHigh) {
5176 if (!IsMax)
5177 std::swap(CstLow, CstHigh);
5178 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5179 Tmp = CstLow->getAPIntValue().getNumSignBits();
5180 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5181 return std::min(Tmp, Tmp2);
5182 }
5183 }
5184
5185 // Fallback - just get the minimum number of sign bits of the operands.
5186 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5187 if (Tmp == 1)
5188 return 1; // Early out.
5189 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5190 return std::min(Tmp, Tmp2);
5191 }
5192 case ISD::UMIN:
5193 case ISD::UMAX:
5194 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5195 if (Tmp == 1)
5196 return 1; // Early out.
5197 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5198 return std::min(Tmp, Tmp2);
5199 case ISD::SSUBO_CARRY:
5200 case ISD::USUBO_CARRY:
5201 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5202 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5203 return VTBits;
5204 [[fallthrough]];
5205 case ISD::SADDO:
5206 case ISD::UADDO:
5207 case ISD::SADDO_CARRY:
5208 case ISD::UADDO_CARRY:
5209 case ISD::SSUBO:
5210 case ISD::USUBO:
5211 case ISD::SMULO:
5212 case ISD::UMULO:
5213 if (Op.getResNo() != 1)
5214 break;
5215 // The boolean result conforms to getBooleanContents. Fall through.
5216 // If setcc returns 0/-1, all bits are sign bits.
5217 // We know that we have an integer-based boolean since these operations
5218 // are only available for integer.
5219 if (TLI->getBooleanContents(VT.isVector(), false) ==
5221 return VTBits;
5222 break;
5223 case ISD::SETCC:
5224 case ISD::SETCCCARRY:
5225 case ISD::STRICT_FSETCC:
5226 case ISD::STRICT_FSETCCS: {
5227 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5228 // If setcc returns 0/-1, all bits are sign bits.
5229 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5231 return VTBits;
5232 break;
5233 }
5235 // Semantically similar to icmp ult.
5236 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5238 return VTBits;
5239 break;
5240 case ISD::ROTL:
5241 case ISD::ROTR:
5242 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5243
5244 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
5245 if (Tmp == VTBits)
5246 return VTBits;
5247
5248 if (ConstantSDNode *C =
5249 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
5250 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
5251
5252 // Handle rotate right by N like a rotate left by 32-N.
5253 if (Opcode == ISD::ROTR)
5254 RotAmt = (VTBits - RotAmt) % VTBits;
5255
5256 // If we aren't rotating out all of the known-in sign bits, return the
5257 // number that are left. This handles rotl(sext(x), 1) for example.
5258 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
5259 }
5260 break;
5261 case ISD::ADD:
5262 case ISD::ADDC:
5263 // TODO: Move Operand 1 check before Operand 0 check
5264 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5265 if (Tmp == 1) return 1; // Early out.
5266
5267 // Special case decrementing a value (ADD X, -1):
5268 if (ConstantSDNode *CRHS =
5269 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5270 if (CRHS->isAllOnes()) {
5272 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5273
5274 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5275 // sign bits set.
5276 if ((Known.Zero | 1).isAllOnes())
5277 return VTBits;
5278
5279 // If we are subtracting one from a positive number, there is no carry
5280 // out of the result.
5281 if (Known.isNonNegative())
5282 return Tmp;
5283 }
5284
5285 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5286 if (Tmp2 == 1) return 1; // Early out.
5287
5288 // Add can have at most one carry bit. Thus we know that the output
5289 // is, at worst, one more bit than the inputs.
5290 return std::min(Tmp, Tmp2) - 1;
5291 case ISD::SUB:
5292 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5293 if (Tmp2 == 1) return 1; // Early out.
5294
5295 // Handle NEG.
5296 if (ConstantSDNode *CLHS =
5297 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5298 if (CLHS->isZero()) {
5300 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5301 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5302 // sign bits set.
5303 if ((Known.Zero | 1).isAllOnes())
5304 return VTBits;
5305
5306 // If the input is known to be positive (the sign bit is known clear),
5307 // the output of the NEG has the same number of sign bits as the input.
5308 if (Known.isNonNegative())
5309 return Tmp2;
5310
5311 // Otherwise, we treat this like a SUB.
5312 }
5313
5314 // Sub can have at most one carry bit. Thus we know that the output
5315 // is, at worst, one more bit than the inputs.
5316 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5317 if (Tmp == 1) return 1; // Early out.
5318 return std::min(Tmp, Tmp2) - 1;
5319 case ISD::MUL: {
5320 // The output of the Mul can be at most twice the valid bits in the inputs.
5321 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5322 if (SignBitsOp0 == 1)
5323 break;
5324 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5325 if (SignBitsOp1 == 1)
5326 break;
5327 unsigned OutValidBits =
5328 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5329 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5330 }
5331 case ISD::AVGCEILS:
5332 case ISD::AVGFLOORS:
5333 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5334 if (Tmp == 1)
5335 return 1; // Early out.
5336 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5337 return std::min(Tmp, Tmp2);
5338 case ISD::SREM:
5339 // The sign bit is the LHS's sign bit, except when the result of the
5340 // remainder is zero. The magnitude of the result should be less than or
5341 // equal to the magnitude of the LHS. Therefore, the result should have
5342 // at least as many sign bits as the left hand side.
5343 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5344 case ISD::TRUNCATE: {
5345 // Check if the sign bits of source go down as far as the truncated value.
5346 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5347 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5348 if (NumSrcSignBits > (NumSrcBits - VTBits))
5349 return NumSrcSignBits - (NumSrcBits - VTBits);
5350 break;
5351 }
5352 case ISD::EXTRACT_ELEMENT: {
5353 if (VT.isScalableVector())
5354 break;
5355 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5356 const int BitWidth = Op.getValueSizeInBits();
5357 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5358
5359 // Get reverse index (starting from 1), Op1 value indexes elements from
5360 // little end. Sign starts at big end.
5361 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5362
5363 // If the sign portion ends in our element the subtraction gives correct
5364 // result. Otherwise it gives either negative or > bitwidth result
5365 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5366 }
5368 if (VT.isScalableVector())
5369 break;
5370 // If we know the element index, split the demand between the
5371 // source vector and the inserted element, otherwise assume we need
5372 // the original demanded vector elements and the value.
5373 SDValue InVec = Op.getOperand(0);
5374 SDValue InVal = Op.getOperand(1);
5375 SDValue EltNo = Op.getOperand(2);
5376 bool DemandedVal = true;
5377 APInt DemandedVecElts = DemandedElts;
5378 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5379 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5380 unsigned EltIdx = CEltNo->getZExtValue();
5381 DemandedVal = !!DemandedElts[EltIdx];
5382 DemandedVecElts.clearBit(EltIdx);
5383 }
5384 Tmp = std::numeric_limits<unsigned>::max();
5385 if (DemandedVal) {
5386 // TODO - handle implicit truncation of inserted elements.
5387 if (InVal.getScalarValueSizeInBits() != VTBits)
5388 break;
5389 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5390 Tmp = std::min(Tmp, Tmp2);
5391 }
5392 if (!!DemandedVecElts) {
5393 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5394 Tmp = std::min(Tmp, Tmp2);
5395 }
5396 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5397 return Tmp;
5398 }
5400 SDValue InVec = Op.getOperand(0);
5401 SDValue EltNo = Op.getOperand(1);
5402 EVT VecVT = InVec.getValueType();
5403 // ComputeNumSignBits not yet implemented for scalable vectors.
5404 if (VecVT.isScalableVector())
5405 break;
5406 const unsigned BitWidth = Op.getValueSizeInBits();
5407 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5408 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5409
5410 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5411 // anything about sign bits. But if the sizes match we can derive knowledge
5412 // about sign bits from the vector operand.
5413 if (BitWidth != EltBitWidth)
5414 break;
5415
5416 // If we know the element index, just demand that vector element, else for
5417 // an unknown element index, ignore DemandedElts and demand them all.
5418 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5419 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5420 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5421 DemandedSrcElts =
5422 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5423
5424 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5425 }
5427 // Offset the demanded elts by the subvector index.
5428 SDValue Src = Op.getOperand(0);
5429
5430 APInt DemandedSrcElts;
5431 if (Src.getValueType().isScalableVector())
5432 DemandedSrcElts = APInt(1, 1);
5433 else {
5434 uint64_t Idx = Op.getConstantOperandVal(1);
5435 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5436 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5437 }
5438 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5439 }
5440 case ISD::CONCAT_VECTORS: {
5441 if (VT.isScalableVector())
5442 break;
5443 // Determine the minimum number of sign bits across all demanded
5444 // elts of the input vectors. Early out if the result is already 1.
5445 Tmp = std::numeric_limits<unsigned>::max();
5446 EVT SubVectorVT = Op.getOperand(0).getValueType();
5447 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5448 unsigned NumSubVectors = Op.getNumOperands();
5449 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5450 APInt DemandedSub =
5451 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5452 if (!DemandedSub)
5453 continue;
5454 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5455 Tmp = std::min(Tmp, Tmp2);
5456 }
5457 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5458 return Tmp;
5459 }
5460 case ISD::INSERT_SUBVECTOR: {
5461 if (VT.isScalableVector())
5462 break;
5463 // Demand any elements from the subvector and the remainder from the src its
5464 // inserted into.
5465 SDValue Src = Op.getOperand(0);
5466 SDValue Sub = Op.getOperand(1);
5467 uint64_t Idx = Op.getConstantOperandVal(2);
5468 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5469 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5470 APInt DemandedSrcElts = DemandedElts;
5471 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5472
5473 Tmp = std::numeric_limits<unsigned>::max();
5474 if (!!DemandedSubElts) {
5475 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5476 if (Tmp == 1)
5477 return 1; // early-out
5478 }
5479 if (!!DemandedSrcElts) {
5480 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5481 Tmp = std::min(Tmp, Tmp2);
5482 }
5483 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5484 return Tmp;
5485 }
5486 case ISD::LOAD: {
5487 // If we are looking at the loaded value of the SDNode.
5488 if (Op.getResNo() != 0)
5489 break;
5490
5492 if (const MDNode *Ranges = LD->getRanges()) {
5493 if (DemandedElts != 1)
5494 break;
5495
5497 if (VTBits > CR.getBitWidth()) {
5498 switch (LD->getExtensionType()) {
5499 case ISD::SEXTLOAD:
5500 CR = CR.signExtend(VTBits);
5501 break;
5502 case ISD::ZEXTLOAD:
5503 CR = CR.zeroExtend(VTBits);
5504 break;
5505 default:
5506 break;
5507 }
5508 }
5509
5510 if (VTBits != CR.getBitWidth())
5511 break;
5512 return std::min(CR.getSignedMin().getNumSignBits(),
5514 }
5515
5516 unsigned ExtType = LD->getExtensionType();
5517 switch (ExtType) {
5518 default:
5519 break;
5520 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5521 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5522 return VTBits - Tmp + 1;
5523 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5524 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5525 return VTBits - Tmp;
5526 case ISD::NON_EXTLOAD:
5527 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5528 // We only need to handle vectors - computeKnownBits should handle
5529 // scalar cases.
5530 Type *CstTy = Cst->getType();
5531 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5532 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5533 VTBits == CstTy->getScalarSizeInBits()) {
5534 Tmp = VTBits;
5535 for (unsigned i = 0; i != NumElts; ++i) {
5536 if (!DemandedElts[i])
5537 continue;
5538 if (Constant *Elt = Cst->getAggregateElement(i)) {
5539 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5540 const APInt &Value = CInt->getValue();
5541 Tmp = std::min(Tmp, Value.getNumSignBits());
5542 continue;
5543 }
5544 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5545 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5546 Tmp = std::min(Tmp, Value.getNumSignBits());
5547 continue;
5548 }
5549 }
5550 // Unknown type. Conservatively assume no bits match sign bit.
5551 return 1;
5552 }
5553 return Tmp;
5554 }
5555 }
5556 break;
5557 }
5558
5559 break;
5560 }
5563 case ISD::ATOMIC_SWAP:
5575 case ISD::ATOMIC_LOAD: {
5576 auto *AT = cast<AtomicSDNode>(Op);
5577 // If we are looking at the loaded value.
5578 if (Op.getResNo() == 0) {
5579 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5580 if (Tmp == VTBits)
5581 return 1; // early-out
5582
5583 // For atomic_load, prefer to use the extension type.
5584 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5585 switch (AT->getExtensionType()) {
5586 default:
5587 break;
5588 case ISD::SEXTLOAD:
5589 return VTBits - Tmp + 1;
5590 case ISD::ZEXTLOAD:
5591 return VTBits - Tmp;
5592 }
5593 }
5594
5595 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5596 return VTBits - Tmp + 1;
5597 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5598 return VTBits - Tmp;
5599 }
5600 break;
5601 }
5602 }
5603
5604 // Allow the target to implement this method for its nodes.
5605 if (Opcode >= ISD::BUILTIN_OP_END ||
5606 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5607 Opcode == ISD::INTRINSIC_W_CHAIN ||
5608 Opcode == ISD::INTRINSIC_VOID) {
5609 // TODO: This can probably be removed once target code is audited. This
5610 // is here purely to reduce patch size and review complexity.
5611 if (!VT.isScalableVector()) {
5612 unsigned NumBits =
5613 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5614 if (NumBits > 1)
5615 FirstAnswer = std::max(FirstAnswer, NumBits);
5616 }
5617 }
5618
5619 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5620 // use this information.
5621 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5622 return std::max(FirstAnswer, Known.countMinSignBits());
5623}
5624
5626 unsigned Depth) const {
5627 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5628 return Op.getScalarValueSizeInBits() - SignBits + 1;
5629}
5630
5632 const APInt &DemandedElts,
5633 unsigned Depth) const {
5634 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5635 return Op.getScalarValueSizeInBits() - SignBits + 1;
5636}
5637
5639 UndefPoisonKind Kind,
5640 unsigned Depth) const {
5641 // Early out for FREEZE.
5642 if (Op.getOpcode() == ISD::FREEZE)
5643 return true;
5644
5645 APInt DemandedElts = getDemandAllEltsMask(Op);
5646 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5647}
5648
5650 const APInt &DemandedElts,
5651 UndefPoisonKind Kind,
5652 unsigned Depth) const {
5653 unsigned Opcode = Op.getOpcode();
5654
5655 // Early out for FREEZE.
5656 if (Opcode == ISD::FREEZE)
5657 return true;
5658
5659 if (Depth >= MaxRecursionDepth)
5660 return false; // Limit search depth.
5661
5662 if (isIntOrFPConstant(Op))
5663 return true;
5664
5665 switch (Opcode) {
5666 case ISD::CONDCODE:
5667 case ISD::VALUETYPE:
5668 case ISD::FrameIndex:
5670 case ISD::CopyFromReg:
5671 return true;
5672
5673 case ISD::POISON:
5674 return !includesPoison(Kind);
5675
5676 case ISD::UNDEF:
5677 return !includesUndef(Kind);
5678
5679 case ISD::BITCAST: {
5680 SDValue Src = Op.getOperand(0);
5681 EVT SrcVT = Src.getValueType();
5682 EVT DstVT = Op.getValueType();
5683
5684 if (!SrcVT.isVector() || !DstVT.isVector())
5685 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5686
5687 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5688 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5689 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5690 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5691
5692 if (SrcEltBits == DstEltBits)
5693 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5694 Depth + 1);
5695
5696 if (SrcEltBits < DstEltBits) {
5697 if (DstEltBits % SrcEltBits != 0)
5698 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5699
5700 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5701 "Unexpected vector bitcast");
5702 APInt DemandedSrcElts =
5703 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5704 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5705 Depth + 1);
5706 }
5707
5708 if (SrcEltBits % DstEltBits != 0)
5709 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5710
5711 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5712 "Unexpected vector bitcast");
5713 APInt DemandedSrcElts =
5714 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5715 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5716 Depth + 1);
5717 }
5718
5719 case ISD::BUILD_VECTOR:
5720 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5721 // this shouldn't affect the result.
5722 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5723 if (!DemandedElts[i])
5724 continue;
5725 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5726 return false;
5727 }
5728 return true;
5729
5730 case ISD::CONCAT_VECTORS: {
5731 EVT VT = Op.getValueType();
5732 if (!VT.isFixedLengthVector())
5733 break;
5734
5735 EVT SubVT = Op.getOperand(0).getValueType();
5736 unsigned NumSubElts = SubVT.getVectorNumElements();
5737 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5738 APInt DemandedSubElts =
5739 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5740 if (!!DemandedSubElts &&
5741 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5742 Kind, Depth + 1))
5743 return false;
5744 }
5745 return true;
5746 }
5747
5749 SDValue Src = Op.getOperand(0);
5750 if (Src.getValueType().isScalableVector())
5751 break;
5752 uint64_t Idx = Op.getConstantOperandVal(1);
5753 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5754 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5755 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5756 Depth + 1);
5757 }
5758
5759 case ISD::INSERT_SUBVECTOR: {
5760 if (Op.getValueType().isScalableVector())
5761 break;
5762 SDValue Src = Op.getOperand(0);
5763 SDValue Sub = Op.getOperand(1);
5764 uint64_t Idx = Op.getConstantOperandVal(2);
5765 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5766 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5767 APInt DemandedSrcElts = DemandedElts;
5768 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5769
5770 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5771 Sub, DemandedSubElts, Kind, Depth + 1))
5772 return false;
5773 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5774 Src, DemandedSrcElts, Kind, Depth + 1))
5775 return false;
5776 return true;
5777 }
5778
5780 SDValue Src = Op.getOperand(0);
5781 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5782 EVT SrcVT = Src.getValueType();
5783 if (SrcVT.isFixedLengthVector() && IndexC &&
5784 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5785 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5786 IndexC->getZExtValue());
5787 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5788 Depth + 1);
5789 }
5790 break;
5791 }
5792
5794 SDValue InVec = Op.getOperand(0);
5795 SDValue InVal = Op.getOperand(1);
5796 SDValue EltNo = Op.getOperand(2);
5797 EVT VT = InVec.getValueType();
5798 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5799 if (IndexC && VT.isFixedLengthVector() &&
5800 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5801 if (DemandedElts[IndexC->getZExtValue()] &&
5802 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5803 return false;
5804 APInt InVecDemandedElts = DemandedElts;
5805 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5806 if (!!InVecDemandedElts &&
5808 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5809 InVecDemandedElts, Kind, Depth + 1))
5810 return false;
5811 return true;
5812 }
5813 break;
5814 }
5815
5817 // Check upper (known undef) elements.
5818 if (DemandedElts.ugt(1) && includesUndef(Kind))
5819 return false;
5820 // Check element zero.
5821 if (DemandedElts[0] &&
5822 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5823 return false;
5824 return true;
5825
5826 case ISD::SPLAT_VECTOR:
5827 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5828
5829 case ISD::SELECT: {
5830 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5831 /*ConsiderFlags*/ true, Depth) &&
5832 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5833 Depth + 1) &&
5834 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5835 Kind, Depth + 1) &&
5836 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5837 Kind, Depth + 1);
5838 }
5839
5840 case ISD::VECTOR_SHUFFLE: {
5841 APInt DemandedLHS, DemandedRHS;
5842 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5843 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5844 DemandedElts, DemandedLHS, DemandedRHS,
5845 /*AllowUndefElts=*/false))
5846 return false;
5847 if (!DemandedLHS.isZero() &&
5848 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5849 Depth + 1))
5850 return false;
5851 if (!DemandedRHS.isZero() &&
5852 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5853 Depth + 1))
5854 return false;
5855 return true;
5856 }
5857
5858 case ISD::SHL:
5859 case ISD::SRL:
5860 case ISD::SRA:
5861 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5862 // enough to check operand 0 if Op can't create undef/poison.
5863 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5864 /*ConsiderFlags*/ true, Depth) &&
5865 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5866 Kind, Depth + 1);
5867
5868 case ISD::BSWAP:
5869 case ISD::CTPOP:
5870 case ISD::BITREVERSE:
5871 case ISD::AND:
5872 case ISD::OR:
5873 case ISD::XOR:
5874 case ISD::ADD:
5875 case ISD::SUB:
5876 case ISD::MUL:
5877 case ISD::SADDSAT:
5878 case ISD::UADDSAT:
5879 case ISD::SSUBSAT:
5880 case ISD::USUBSAT:
5881 case ISD::SSHLSAT:
5882 case ISD::USHLSAT:
5883 case ISD::SMIN:
5884 case ISD::SMAX:
5885 case ISD::UMIN:
5886 case ISD::UMAX:
5887 case ISD::ZERO_EXTEND:
5888 case ISD::SIGN_EXTEND:
5889 case ISD::ANY_EXTEND:
5890 case ISD::TRUNCATE:
5891 case ISD::VSELECT: {
5892 // If Op can't create undef/poison and none of its operands are undef/poison
5893 // then Op is never undef/poison. A difference from the more common check
5894 // below, outside the switch, is that we handle elementwise operations for
5895 // which the DemandedElts mask is valid for all operands here.
5896 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5897 /*ConsiderFlags*/ true, Depth) &&
5898 all_of(Op->ops(), [&](SDValue V) {
5899 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5900 Depth + 1);
5901 });
5902 }
5903
5904 // TODO: Search for noundef attributes from library functions.
5905
5906 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5907
5908 default:
5909 // Allow the target to implement this method for its nodes.
5910 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5911 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5912 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5913 Op, DemandedElts, *this, Kind, Depth);
5914 break;
5915 }
5916
5917 // If Op can't create undef/poison and none of its operands are undef/poison
5918 // then Op is never undef/poison.
5919 // NOTE: TargetNodes can handle this in themselves in
5920 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5921 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5922 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5923 all_of(Op->ops(), [&](SDValue V) {
5924 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5925 });
5926}
5927
5929 bool ConsiderFlags,
5930 unsigned Depth) const {
5931 APInt DemandedElts = getDemandAllEltsMask(Op);
5932 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5933}
5934
5936 UndefPoisonKind Kind,
5937 bool ConsiderFlags,
5938 unsigned Depth) const {
5939 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5940 return true;
5941
5942 unsigned Opcode = Op.getOpcode();
5943 switch (Opcode) {
5944 case ISD::AssertSext:
5945 case ISD::AssertZext:
5946 case ISD::AssertAlign:
5948 // Assertion nodes can create poison if the assertion fails.
5949 return includesPoison(Kind);
5950
5951 case ISD::FREEZE:
5955 case ISD::SADDSAT:
5956 case ISD::UADDSAT:
5957 case ISD::SSUBSAT:
5958 case ISD::USUBSAT:
5959 case ISD::MULHU:
5960 case ISD::MULHS:
5961 case ISD::AVGFLOORS:
5962 case ISD::AVGFLOORU:
5963 case ISD::AVGCEILS:
5964 case ISD::AVGCEILU:
5965 case ISD::ABDU:
5966 case ISD::ABDS:
5967 case ISD::SMIN:
5968 case ISD::SMAX:
5969 case ISD::SCMP:
5970 case ISD::UMIN:
5971 case ISD::UMAX:
5972 case ISD::UCMP:
5973 case ISD::AND:
5974 case ISD::XOR:
5975 case ISD::ROTL:
5976 case ISD::ROTR:
5977 case ISD::FSHL:
5978 case ISD::FSHR:
5979 case ISD::BSWAP:
5980 case ISD::CTTZ:
5981 case ISD::CTLZ:
5982 case ISD::CTLS:
5983 case ISD::CTPOP:
5984 case ISD::BITREVERSE:
5985 case ISD::PARITY:
5986 case ISD::SIGN_EXTEND:
5987 case ISD::TRUNCATE:
5991 case ISD::BITCAST:
5992 case ISD::BUILD_VECTOR:
5993 case ISD::BUILD_PAIR:
5994 case ISD::SPLAT_VECTOR:
5995 case ISD::FABS:
5996 case ISD::FCEIL:
5997 case ISD::FFLOOR:
5998 case ISD::FTRUNC:
5999 case ISD::FRINT:
6000 case ISD::FNEARBYINT:
6001 case ISD::FROUND:
6002 case ISD::FROUNDEVEN:
6003 return false;
6004
6005 case ISD::ABS:
6006 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6007 // Different to Intrinsic::abs.
6008 return false;
6010 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6011 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6012
6013 case ISD::ADDC:
6014 case ISD::SUBC:
6015 case ISD::ADDE:
6016 case ISD::SUBE:
6017 case ISD::SADDO:
6018 case ISD::SSUBO:
6019 case ISD::SMULO:
6020 case ISD::SADDO_CARRY:
6021 case ISD::SSUBO_CARRY:
6022 case ISD::UADDO:
6023 case ISD::USUBO:
6024 case ISD::UMULO:
6025 case ISD::UADDO_CARRY:
6026 case ISD::USUBO_CARRY:
6027 // No poison on result or overflow flags.
6028 return false;
6029
6030 case ISD::SELECT_CC:
6031 case ISD::SETCC: {
6032 // Integer setcc cannot create undef or poison.
6033 if (Op.getOperand(0).getValueType().isInteger())
6034 return false;
6035
6036 // FP compares are more complicated. They can create poison for nan/infinity
6037 // based on options and flags. The options and flags also cause special
6038 // nonan condition codes to be used. Those condition codes may be preserved
6039 // even if the nonan flag is dropped somewhere.
6040 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6041 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6042 return (unsigned)CCCode & 0x10U;
6043 }
6044
6045 case ISD::OR:
6046 case ISD::ZERO_EXTEND:
6047 case ISD::SELECT:
6048 case ISD::VSELECT:
6049 case ISD::ADD:
6050 case ISD::SUB:
6051 case ISD::MUL:
6052 case ISD::FNEG:
6053 case ISD::FADD:
6054 case ISD::FSUB:
6055 case ISD::FMUL:
6056 case ISD::FDIV:
6057 case ISD::FREM:
6058 case ISD::FCOPYSIGN:
6059 case ISD::FMA:
6060 case ISD::FMAD:
6061 case ISD::FMULADD:
6062 case ISD::FP_EXTEND:
6063 case ISD::FMINNUM:
6064 case ISD::FMAXNUM:
6065 case ISD::FMINNUM_IEEE:
6066 case ISD::FMAXNUM_IEEE:
6067 case ISD::FMINIMUM:
6068 case ISD::FMAXIMUM:
6069 case ISD::FMINIMUMNUM:
6070 case ISD::FMAXIMUMNUM:
6076 // No poison except from flags (which is handled above)
6077 return false;
6078
6079 case ISD::SHL:
6080 case ISD::SRL:
6081 case ISD::SRA:
6082 // If the max shift amount isn't in range, then the shift can
6083 // create poison.
6084 return includesPoison(Kind) &&
6085 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6086
6089 // If the amount is zero then the result will be poison.
6090 // TODO: Add isKnownNeverZero DemandedElts handling.
6091 return includesPoison(Kind) &&
6092 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6093
6095 // Check if we demand any upper (undef) elements.
6096 return includesUndef(Kind) && DemandedElts.ugt(1);
6097
6100 // Ensure that the element index is in bounds.
6101 if (includesPoison(Kind)) {
6102 EVT VecVT = Op.getOperand(0).getValueType();
6103 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6104 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6105 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6106 }
6107 return false;
6108 }
6109
6110 case ISD::VECTOR_SHUFFLE: {
6111 // Check for any demanded shuffle element that is undef.
6112 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6113 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6114 if (Elt < 0 && DemandedElts[Idx])
6115 return true;
6116 return false;
6117 }
6118
6120 return false;
6121
6122 default:
6123 // Allow the target to implement this method for its nodes.
6124 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6125 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6126 return TLI->canCreateUndefOrPoisonForTargetNode(
6127 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6128 break;
6129 }
6130
6131 // Be conservative and return true.
6132 return true;
6133}
6134
6135bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6136 unsigned Opcode = Op.getOpcode();
6137 if (Opcode == ISD::OR)
6138 return Op->getFlags().hasDisjoint() ||
6139 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6140 if (Opcode == ISD::XOR)
6141 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6142 return false;
6143}
6144
6146 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6147 (Op.isAnyAdd() || isADDLike(Op));
6148}
6149
6151 FPClassTest InterestedClasses,
6152 unsigned Depth) const {
6153 APInt DemandedElts = getDemandAllEltsMask(Op);
6154 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6155}
6156
6158 const APInt &DemandedElts,
6159 FPClassTest InterestedClasses,
6160 unsigned Depth) const {
6162
6163 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6164 return KnownFPClass(CFP->getValueAPF());
6165
6166 if (Depth >= MaxRecursionDepth)
6167 return Known;
6168
6169 if (Op.getOpcode() == ISD::UNDEF)
6170 return Known;
6171
6172 EVT VT = Op.getValueType();
6173 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6174 assert((!VT.isFixedLengthVector() ||
6175 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6176 "Unexpected vector size");
6177
6178 if (!DemandedElts)
6179 return Known;
6180
6181 unsigned Opcode = Op.getOpcode();
6182 switch (Opcode) {
6183 case ISD::POISON: {
6184 Known.KnownFPClasses = fcNone;
6185 Known.SignBit = false;
6186 break;
6187 }
6188 case ISD::FNEG: {
6189 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6190 InterestedClasses, Depth + 1);
6191 Known.fneg();
6192 break;
6193 }
6194 case ISD::BUILD_VECTOR: {
6195 assert(!VT.isScalableVector());
6196 bool First = true;
6197 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6198 if (!DemandedElts[I])
6199 continue;
6200
6201 if (First) {
6202 Known =
6203 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6204 First = false;
6205 } else {
6206 Known |=
6207 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6208 }
6209
6210 if (Known.isUnknown())
6211 break;
6212 }
6213 break;
6214 }
6216 SDValue Src = Op.getOperand(0);
6217 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6218 EVT SrcVT = Src.getValueType();
6219 if (SrcVT.isFixedLengthVector() && CIdx) {
6220 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6221 APInt DemandedSrcElts = APInt::getOneBitSet(
6222 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6223 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6224 Depth + 1);
6225 } else {
6226 // Out of bounds index is poison.
6227 Known.KnownFPClasses = fcNone;
6228 }
6229 } else {
6230 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6231 }
6232 break;
6233 }
6234 case ISD::SPLAT_VECTOR: {
6235 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6236 break;
6237 }
6238 case ISD::BITCAST: {
6239 // FIXME: It should not be necessary to check for an elementwise bitcast.
6240 // If a bitcast is not elementwise between vector / scalar types,
6241 // computeKnownBits already splices the known bits of the source elements
6242 // appropriately so as to line up with the bits of the result's demanded
6243 // elements.
6244 EVT SrcVT = Op.getOperand(0).getValueType();
6245 if (VT.isScalableVector() || SrcVT.isScalableVector())
6246 break;
6247 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6248 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6249 if (VTNumElts != SrcVTNumElts)
6250 break;
6251
6252 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6254 break;
6255 }
6256 case ISD::FABS: {
6257 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6258 InterestedClasses, Depth + 1);
6259 Known.fabs();
6260 break;
6261 }
6262 case ISD::FCOPYSIGN: {
6263 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6264 InterestedClasses, Depth + 1);
6265 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6266 InterestedClasses, Depth + 1);
6267 Known.copysign(KnownSign);
6268 break;
6269 }
6270 case ISD::AssertNoFPClass: {
6271 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6272 InterestedClasses, Depth + 1);
6273 FPClassTest AssertedClasses =
6274 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6275 Known.KnownFPClasses &= ~AssertedClasses;
6276 break;
6277 }
6279 SDValue Src = Op.getOperand(0);
6280 EVT SrcVT = Src.getValueType();
6281 if (SrcVT.isFixedLengthVector()) {
6282 unsigned Idx = Op.getConstantOperandVal(1);
6283 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6284
6285 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6286 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6287 Depth + 1);
6288 } else {
6289 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6290 }
6291 break;
6292 }
6293 case ISD::INSERT_SUBVECTOR: {
6294 SDValue BaseVector = Op.getOperand(0);
6295 SDValue SubVector = Op.getOperand(1);
6296 EVT BaseVT = BaseVector.getValueType();
6297 if (BaseVT.isFixedLengthVector()) {
6298 unsigned Idx = Op.getConstantOperandVal(2);
6299 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6300 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6301
6302 APInt DemandedMask =
6303 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6304 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6305 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6306
6307 if (!DemandedSrcElts.isZero())
6308 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6309 InterestedClasses, Depth + 1);
6310 if (!DemandedSubElts.isZero()) {
6312 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6313 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6314 }
6315 } else {
6316 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6317 if (!Known.isUnknown())
6318 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6319 }
6320 break;
6321 }
6322 case ISD::SELECT:
6323 case ISD::VSELECT: {
6324 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6325 // IR-level ValueTracking.
6326 KnownFPClass KnownFalseClass = computeKnownFPClass(
6327 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6328 if (KnownFalseClass.isUnknown())
6329 break;
6330 KnownFPClass KnownTrueClass = computeKnownFPClass(
6331 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6332 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6333 break;
6334 }
6335 default:
6336 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6337 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6338 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6339 Depth);
6340 }
6341 break;
6342 }
6343
6344 return Known;
6345}
6346
6348 unsigned Depth) const {
6349 APInt DemandedElts = getDemandAllEltsMask(Op);
6350 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6351}
6352
6354 bool SNaN, unsigned Depth) const {
6355 assert(!DemandedElts.isZero() && "No demanded elements");
6356
6357 // If we're told that NaNs won't happen, assume they won't.
6358 if (Op->getFlags().hasNoNaNs())
6359 return true;
6360
6361 if (Depth >= MaxRecursionDepth)
6362 return false; // Limit search depth.
6363
6364 unsigned Opcode = Op.getOpcode();
6365 switch (Opcode) {
6366 case ISD::FADD:
6367 case ISD::FSUB:
6368 case ISD::FMUL:
6369 case ISD::FDIV:
6370 case ISD::FREM:
6371 case ISD::FSIN:
6372 case ISD::FCOS:
6373 case ISD::FTAN:
6374 case ISD::FASIN:
6375 case ISD::FACOS:
6376 case ISD::FATAN:
6377 case ISD::FATAN2:
6378 case ISD::FSINH:
6379 case ISD::FCOSH:
6380 case ISD::FTANH:
6381 case ISD::FMA:
6382 case ISD::FMULADD:
6383 case ISD::FMAD: {
6384 if (SNaN)
6385 return true;
6386 // TODO: Need isKnownNeverInfinity
6387 return false;
6388 }
6389 case ISD::FCANONICALIZE:
6390 case ISD::FEXP:
6391 case ISD::FEXP2:
6392 case ISD::FEXP10:
6393 case ISD::FTRUNC:
6394 case ISD::FFLOOR:
6395 case ISD::FCEIL:
6396 case ISD::FROUND:
6397 case ISD::FROUNDEVEN:
6398 case ISD::LROUND:
6399 case ISD::LLROUND:
6400 case ISD::FRINT:
6401 case ISD::LRINT:
6402 case ISD::LLRINT:
6403 case ISD::FNEARBYINT:
6404 case ISD::FLDEXP: {
6405 if (SNaN)
6406 return true;
6407 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6408 }
6409 case ISD::FABS:
6410 case ISD::FNEG:
6411 case ISD::FCOPYSIGN: {
6412 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6413 }
6414 case ISD::SELECT:
6415 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6416 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6417 case ISD::FP_EXTEND:
6418 case ISD::FP_ROUND: {
6419 if (SNaN)
6420 return true;
6421 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6422 }
6423 case ISD::SINT_TO_FP:
6424 case ISD::UINT_TO_FP:
6425 return true;
6426 case ISD::FSQRT: // Need is known positive
6427 case ISD::FLOG:
6428 case ISD::FLOG2:
6429 case ISD::FLOG10:
6430 case ISD::FPOWI:
6431 case ISD::FPOW: {
6432 if (SNaN)
6433 return true;
6434 // TODO: Refine on operand
6435 return false;
6436 }
6437 case ISD::FMINNUM:
6438 case ISD::FMAXNUM:
6439 case ISD::FMINIMUMNUM:
6440 case ISD::FMAXIMUMNUM: {
6441 // Only one needs to be known not-nan, since it will be returned if the
6442 // other ends up being one.
6443 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6444 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6445 }
6446 case ISD::FMINNUM_IEEE:
6447 case ISD::FMAXNUM_IEEE: {
6448 if (SNaN)
6449 return true;
6450 // This can return a NaN if either operand is an sNaN, or if both operands
6451 // are NaN.
6452 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6453 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6454 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6455 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6456 }
6457 case ISD::FMINIMUM:
6458 case ISD::FMAXIMUM: {
6459 // TODO: Does this quiet or return the origina NaN as-is?
6460 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6461 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6462 }
6464 SDValue Src = Op.getOperand(0);
6465 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6466 EVT SrcVT = Src.getValueType();
6467 if (SrcVT.isFixedLengthVector() && Idx &&
6468 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6469 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6470 Idx->getZExtValue());
6471 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6472 }
6473 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6474 }
6476 SDValue Src = Op.getOperand(0);
6477 if (Src.getValueType().isFixedLengthVector()) {
6478 unsigned Idx = Op.getConstantOperandVal(1);
6479 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6480 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6481 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6482 }
6483 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6484 }
6485 case ISD::INSERT_SUBVECTOR: {
6486 SDValue BaseVector = Op.getOperand(0);
6487 SDValue SubVector = Op.getOperand(1);
6488 EVT BaseVectorVT = BaseVector.getValueType();
6489 if (BaseVectorVT.isFixedLengthVector()) {
6490 unsigned Idx = Op.getConstantOperandVal(2);
6491 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6492 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6493
6494 // Clear/Extract the bits at the position where the subvector will be
6495 // inserted.
6496 APInt DemandedMask =
6497 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6498 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6499 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6500
6501 bool NeverNaN = true;
6502 if (!DemandedSrcElts.isZero())
6503 NeverNaN &=
6504 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6505 if (NeverNaN && !DemandedSubElts.isZero())
6506 NeverNaN &=
6507 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6508 return NeverNaN;
6509 }
6510 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6511 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6512 }
6513 case ISD::BUILD_VECTOR: {
6514 unsigned NumElts = Op.getNumOperands();
6515 for (unsigned I = 0; I != NumElts; ++I)
6516 if (DemandedElts[I] &&
6517 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6518 return false;
6519 return true;
6520 }
6521 case ISD::SPLAT_VECTOR:
6522 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6523 case ISD::AssertNoFPClass: {
6524 FPClassTest NoFPClass =
6525 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6526 if ((NoFPClass & fcNan) == fcNan)
6527 return true;
6528 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6529 return true;
6530 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6531 }
6532 default:
6533 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6534 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6535 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6536 Depth);
6537 }
6538 break;
6539 }
6540
6541 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6542 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6543 return Known.isKnownNever(NanMask);
6544}
6545
6547 APInt DemandedElts = getDemandAllEltsMask(Op);
6548 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6549}
6550
6552 const APInt &DemandedElts,
6553 unsigned Depth) const {
6554 assert(!DemandedElts.isZero() && "No demanded elements");
6555 EVT VT = Op.getValueType();
6557 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6558 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6559}
6560
6562 APInt DemandedElts = getDemandAllEltsMask(Op);
6563 return isKnownNeverZero(Op, DemandedElts, Depth);
6564}
6565
6567 unsigned Depth) const {
6568 if (Depth >= MaxRecursionDepth)
6569 return false; // Limit search depth.
6570
6571 EVT OpVT = Op.getValueType();
6572 unsigned BitWidth = OpVT.getScalarSizeInBits();
6573
6574 assert(!Op.getValueType().isFloatingPoint() &&
6575 "Floating point types unsupported - use isKnownNeverLogicalZero");
6576
6577 // If the value is a constant, we can obviously see if it is a zero or not.
6578 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6579 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6580 return !V.isZero();
6581 };
6582
6583 if (ISD::matchUnaryPredicate(Op, IsNeverZero))
6584 return true;
6585
6586 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6587 // some degree.
6588 switch (Op.getOpcode()) {
6589 default:
6590 break;
6591
6592 case ISD::BUILD_VECTOR:
6593 // Are all operands of a build vector constant non-zero?
6594 if (all_of(enumerate(Op->ops()), [&](auto P) {
6595 auto *C = dyn_cast<ConstantSDNode>(P.value());
6596 return !DemandedElts[P.index()] || (C && IsNeverZero(C));
6597 }))
6598 return true;
6599 break;
6600
6601 case ISD::SPLAT_VECTOR:
6602 // Is the operand of a splat vector a constant non-zero?
6603 if (auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(0)))
6604 if (IsNeverZero(C))
6605 return true;
6606 break;
6607
6609 SDValue InVec = Op.getOperand(0);
6610 SDValue EltNo = Op.getOperand(1);
6611 EVT VecVT = InVec.getValueType();
6612
6613 // Skip scalable vectors or implicit extensions.
6614 if (VecVT.isScalableVector() ||
6615 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6616 break;
6617
6618 // If we know the element index, just demand that vector element, else for
6619 // an unknown element index, ignore DemandedElts and demand them all.
6620 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6621 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6622 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6623 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6624 DemandedSrcElts =
6625 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6626
6627 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6628 }
6629
6630 case ISD::OR:
6631 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6632 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6633
6634 case ISD::VSELECT:
6635 case ISD::SELECT:
6636 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6637 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6638
6639 case ISD::SHL: {
6640 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6641 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6642 KnownBits ValKnown =
6643 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6644 // 1 << X is never zero.
6645 if (ValKnown.One[0])
6646 return true;
6647 // If max shift cnt of known ones is non-zero, result is non-zero.
6648 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6649 .getMaxValue();
6650 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6651 !ValKnown.One.shl(MaxCnt).isZero())
6652 return true;
6653 break;
6654 }
6655
6656 case ISD::VECTOR_SHUFFLE: {
6657 if (Op.getValueType().isScalableVector())
6658 return false;
6659
6660 unsigned NumElts = DemandedElts.getBitWidth();
6661
6662 // All demanded elements from LHS and RHS must be known non-zero.
6663 // Demanded elements with undef shuffle mask elements are unknown.
6664
6665 APInt DemandedLHS, DemandedRHS;
6666 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6667 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6668 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6669 DemandedLHS, DemandedRHS))
6670 return false;
6671
6672 return (!DemandedLHS ||
6673 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6674 (!DemandedRHS ||
6675 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6676 }
6677
6678 case ISD::UADDSAT:
6679 case ISD::UMAX:
6680 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6681 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6682
6683 case ISD::UMIN:
6684 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6685 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6686
6687 // For smin/smax: If either operand is known negative/positive
6688 // respectively we don't need the other to be known at all.
6689 case ISD::SMAX: {
6690 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6691 if (Op1.isStrictlyPositive())
6692 return true;
6693
6694 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6695 if (Op0.isStrictlyPositive())
6696 return true;
6697
6698 if (Op1.isNonZero() && Op0.isNonZero())
6699 return true;
6700
6701 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6702 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6703 }
6704 case ISD::SMIN: {
6705 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6706 if (Op1.isNegative())
6707 return true;
6708
6709 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6710 if (Op0.isNegative())
6711 return true;
6712
6713 if (Op1.isNonZero() && Op0.isNonZero())
6714 return true;
6715
6716 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6717 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6718 }
6719
6720 case ISD::ROTL:
6721 case ISD::ROTR:
6722 case ISD::BITREVERSE:
6723 case ISD::BSWAP:
6724 case ISD::CTPOP:
6725 case ISD::ABS:
6727 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6728
6729 case ISD::SRA:
6730 case ISD::SRL: {
6731 if (Op->getFlags().hasExact())
6732 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6733 KnownBits ValKnown =
6734 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6735 if (ValKnown.isNegative())
6736 return true;
6737 // If max shift cnt of known ones is non-zero, result is non-zero.
6738 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6739 .getMaxValue();
6740 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6741 !ValKnown.One.lshr(MaxCnt).isZero())
6742 return true;
6743 break;
6744 }
6745 case ISD::UDIV:
6746 case ISD::SDIV:
6747 // div exact can only produce a zero if the dividend is zero.
6748 // TODO: For udiv this is also true if Op1 u<= Op0
6749 if (Op->getFlags().hasExact())
6750 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6751 break;
6752
6753 case ISD::ADD:
6754 if (Op->getFlags().hasNoUnsignedWrap())
6755 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6756 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6757 return true;
6758 // TODO: There are a lot more cases we can prove for add.
6759 break;
6760
6761 case ISD::SUB: {
6762 if (isNullConstant(Op.getOperand(0)))
6763 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6764
6765 std::optional<bool> ne = KnownBits::ne(
6766 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6767 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6768 return ne && *ne;
6769 }
6770
6771 case ISD::MUL:
6772 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6773 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6774 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6775 return true;
6776 break;
6777
6778 case ISD::ZERO_EXTEND:
6779 case ISD::SIGN_EXTEND:
6780 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6781 case ISD::VSCALE: {
6783 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6784 ConstantRange CR =
6785 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6786 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6787 return true;
6788 break;
6789 }
6790 }
6791
6792 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6793}
6794
6796 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6797 return !C1->isNegative();
6798
6799 switch (Op.getOpcode()) {
6800 case ISD::FABS:
6801 case ISD::FEXP:
6802 case ISD::FEXP2:
6803 case ISD::FEXP10:
6804 return true;
6805 default:
6806 return false;
6807 }
6808
6809 llvm_unreachable("covered opcode switch");
6810}
6811
6813 assert(Use.getValueType().isFloatingPoint());
6814 const SDNode *User = Use.getUser();
6815 if (User->getFlags().hasNoSignedZeros())
6816 return true;
6817
6818 unsigned OperandNo = Use.getOperandNo();
6819 // Check if this use is insensitive to the sign of zero
6820 switch (User->getOpcode()) {
6821 case ISD::SETCC:
6822 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6823 case ISD::FABS:
6824 // fabs always produces +0.0.
6825 return true;
6826 case ISD::FCOPYSIGN:
6827 // copysign overwrites the sign bit of the first operand.
6828 return OperandNo == 0;
6829 case ISD::FADD:
6830 case ISD::FSUB: {
6831 // Arithmetic with non-zero constants fixes the uncertainty around the
6832 // sign bit.
6833 SDValue Other = User->getOperand(1 - OperandNo);
6835 }
6836 case ISD::FP_TO_SINT:
6837 case ISD::FP_TO_UINT:
6838 // fp-to-int conversions normalize signed zeros.
6839 return true;
6840 default:
6841 return false;
6842 }
6843}
6844
6846 if (Op->getFlags().hasNoSignedZeros())
6847 return true;
6848 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6849 // regression. Ideally, this should be implemented as a demanded-bits
6850 // optimization that stems from the users.
6851 if (Op->use_size() > 2)
6852 return false;
6853 return all_of(Op->uses(),
6854 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6855}
6856
6858 // Check the obvious case.
6859 if (A == B) return true;
6860
6861 // For negative and positive zero.
6864 if (CA->isZero() && CB->isZero()) return true;
6865
6866 // Otherwise they may not be equal.
6867 return false;
6868}
6869
6870// Only bits set in Mask must be negated, other bits may be arbitrary.
6872 if (isBitwiseNot(V, AllowUndefs))
6873 return V.getOperand(0);
6874
6875 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6876 // bits in the non-extended part.
6877 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6878 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6879 return SDValue();
6880 SDValue ExtArg = V.getOperand(0);
6881 if (ExtArg.getScalarValueSizeInBits() >=
6882 MaskC->getAPIntValue().getActiveBits() &&
6883 isBitwiseNot(ExtArg, AllowUndefs) &&
6884 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6885 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6886 return ExtArg.getOperand(0).getOperand(0);
6887 return SDValue();
6888}
6889
6891 // Match masked merge pattern (X & ~M) op (Y & M)
6892 // Including degenerate case (X & ~M) op M
6893 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6894 SDValue Other) {
6895 if (SDValue NotOperand =
6896 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6897 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6898 NotOperand->getOpcode() == ISD::TRUNCATE)
6899 NotOperand = NotOperand->getOperand(0);
6900
6901 if (Other == NotOperand)
6902 return true;
6903 if (Other->getOpcode() == ISD::AND)
6904 return NotOperand == Other->getOperand(0) ||
6905 NotOperand == Other->getOperand(1);
6906 }
6907 return false;
6908 };
6909
6910 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6911 A = A->getOperand(0);
6912
6913 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6914 B = B->getOperand(0);
6915
6916 if (A->getOpcode() == ISD::AND)
6917 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6918 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6919 return false;
6920}
6921
6922// FIXME: unify with llvm::haveNoCommonBitsSet.
6924 assert(A.getValueType() == B.getValueType() &&
6925 "Values must have the same type");
6928 return true;
6931}
6932
6933static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6934 SelectionDAG &DAG) {
6935 if (cast<ConstantSDNode>(Step)->isZero())
6936 return DAG.getConstant(0, DL, VT);
6937
6938 return SDValue();
6939}
6940
6943 SelectionDAG &DAG) {
6944 int NumOps = Ops.size();
6945 assert(NumOps != 0 && "Can't build an empty vector!");
6946 assert(!VT.isScalableVector() &&
6947 "BUILD_VECTOR cannot be used with scalable types");
6948 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6949 "Incorrect element count in BUILD_VECTOR!");
6950
6951 // BUILD_VECTOR of UNDEFs is UNDEF.
6952 bool AllPoison = true;
6953 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6954 AllPoison &= Op.getOpcode() == ISD::POISON;
6955 return Op.isUndef();
6956 }))
6957 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6958
6959 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6960 SDValue IdentitySrc;
6961 bool IsIdentity = true;
6962 for (int i = 0; i != NumOps; ++i) {
6963 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6964 Ops[i].getOperand(0).getValueType() != VT ||
6965 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6966 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6967 Ops[i].getConstantOperandAPInt(1) != i) {
6968 IsIdentity = false;
6969 break;
6970 }
6971 IdentitySrc = Ops[i].getOperand(0);
6972 }
6973 if (IsIdentity)
6974 return IdentitySrc;
6975
6976 return SDValue();
6977}
6978
6979/// Try to simplify vector concatenation to an input value, undef, or build
6980/// vector.
6983 SelectionDAG &DAG) {
6984 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6986 [Ops](SDValue Op) {
6987 return Ops[0].getValueType() == Op.getValueType();
6988 }) &&
6989 "Concatenation of vectors with inconsistent value types!");
6990 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6991 VT.getVectorElementCount() &&
6992 "Incorrect element count in vector concatenation!");
6993
6994 if (Ops.size() == 1)
6995 return Ops[0];
6996
6997 // Concat of UNDEFs is UNDEF.
6998 bool AllPoison = true;
6999 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7000 AllPoison &= Op.getOpcode() == ISD::POISON;
7001 return Op.isUndef();
7002 }))
7003 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7004
7005 // Scan the operands and look for extract operations from a single source
7006 // that correspond to insertion at the same location via this concatenation:
7007 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7008 SDValue IdentitySrc;
7009 bool IsIdentity = true;
7010 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7011 SDValue Op = Ops[i];
7012 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7013 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7014 Op.getOperand(0).getValueType() != VT ||
7015 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7016 Op.getConstantOperandVal(1) != IdentityIndex) {
7017 IsIdentity = false;
7018 break;
7019 }
7020 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7021 "Unexpected identity source vector for concat of extracts");
7022 IdentitySrc = Op.getOperand(0);
7023 }
7024 if (IsIdentity) {
7025 assert(IdentitySrc && "Failed to set source vector of extracts");
7026 return IdentitySrc;
7027 }
7028
7029 // The code below this point is only designed to work for fixed width
7030 // vectors, so we bail out for now.
7031 if (VT.isScalableVector())
7032 return SDValue();
7033
7034 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7035 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7036 // BUILD_VECTOR.
7037 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7038 EVT SVT = VT.getScalarType();
7040 for (SDValue Op : Ops) {
7041 EVT OpVT = Op.getValueType();
7042 if (Op.getOpcode() == ISD::POISON)
7043 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7044 else if (Op.getOpcode() == ISD::UNDEF)
7045 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7046 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7047 Elts.append(Op->op_begin(), Op->op_end());
7048 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7049 OpVT.getVectorNumElements() == 1 &&
7050 isNullConstant(Op.getOperand(2)))
7051 Elts.push_back(Op.getOperand(1));
7052 else
7053 return SDValue();
7054 }
7055
7056 // BUILD_VECTOR requires all inputs to be of the same type, find the
7057 // maximum type and extend them all.
7058 for (SDValue Op : Elts)
7059 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7060
7061 if (SVT.bitsGT(VT.getScalarType())) {
7062 for (SDValue &Op : Elts) {
7063 if (Op.getOpcode() == ISD::POISON)
7064 Op = DAG.getPOISON(SVT);
7065 else if (Op.getOpcode() == ISD::UNDEF)
7066 Op = DAG.getUNDEF(SVT);
7067 else
7068 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7069 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7070 : DAG.getSExtOrTrunc(Op, DL, SVT);
7071 }
7072 }
7073
7074 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7075 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7076 return V;
7077}
7078
7079/// Gets or creates the specified node.
7080SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7081 SDVTList VTs = getVTList(VT);
7083 AddNodeIDNode(ID, Opcode, VTs, {});
7084 void *IP = nullptr;
7085 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7086 return SDValue(E, 0);
7087
7088 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7089 CSEMap.InsertNode(N, IP);
7090
7091 InsertNode(N);
7092 SDValue V = SDValue(N, 0);
7093 NewSDValueDbgMsg(V, "Creating new node: ", this);
7094 return V;
7095}
7096
7097SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7098 SDValue N1) {
7099 SDNodeFlags Flags;
7100 if (Inserter)
7101 Flags = Inserter->getFlags();
7102 return getNode(Opcode, DL, VT, N1, Flags);
7103}
7104
7105SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7106 SDValue N1, const SDNodeFlags Flags) {
7107 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7108
7109 // Constant fold unary operations with a vector integer or float operand.
7110 switch (Opcode) {
7111 default:
7112 // FIXME: Entirely reasonable to perform folding of other unary
7113 // operations here as the need arises.
7114 break;
7115 case ISD::FNEG:
7116 case ISD::FABS:
7117 case ISD::FCEIL:
7118 case ISD::FTRUNC:
7119 case ISD::FFLOOR:
7120 case ISD::FP_EXTEND:
7121 case ISD::FP_TO_SINT:
7122 case ISD::FP_TO_UINT:
7123 case ISD::FP_TO_FP16:
7124 case ISD::FP_TO_BF16:
7125 case ISD::TRUNCATE:
7126 case ISD::ANY_EXTEND:
7127 case ISD::ZERO_EXTEND:
7128 case ISD::SIGN_EXTEND:
7129 case ISD::UINT_TO_FP:
7130 case ISD::SINT_TO_FP:
7131 case ISD::FP16_TO_FP:
7132 case ISD::BF16_TO_FP:
7133 case ISD::BITCAST:
7134 case ISD::ABS:
7136 case ISD::BITREVERSE:
7137 case ISD::BSWAP:
7138 case ISD::CTLZ:
7140 case ISD::CTTZ:
7142 case ISD::CTPOP:
7143 case ISD::CTLS:
7144 case ISD::VECREDUCE_ADD:
7149 case ISD::VECREDUCE_MUL:
7150 case ISD::VECREDUCE_AND:
7151 case ISD::VECREDUCE_OR:
7152 case ISD::VECREDUCE_XOR:
7153 case ISD::STEP_VECTOR: {
7154 SDValue Ops = {N1};
7155 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7156 return Fold;
7157 }
7158 }
7159
7160 unsigned OpOpcode = N1.getNode()->getOpcode();
7161 switch (Opcode) {
7162 case ISD::STEP_VECTOR:
7163 assert(VT.isScalableVector() &&
7164 "STEP_VECTOR can only be used with scalable types");
7165 assert(OpOpcode == ISD::TargetConstant &&
7166 VT.getVectorElementType() == N1.getValueType() &&
7167 "Unexpected step operand");
7168 break;
7169 case ISD::FREEZE:
7170 assert(VT == N1.getValueType() && "Unexpected VT!");
7172 return N1;
7173 break;
7174 case ISD::TokenFactor:
7175 case ISD::MERGE_VALUES:
7177 return N1; // Factor, merge or concat of one node? No need.
7178 case ISD::BUILD_VECTOR: {
7179 // Attempt to simplify BUILD_VECTOR.
7180 SDValue Ops[] = {N1};
7181 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7182 return V;
7183 break;
7184 }
7185 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7186 case ISD::FP_EXTEND:
7188 "Invalid FP cast!");
7189 if (N1.getValueType() == VT) return N1; // noop conversion.
7190 assert((!VT.isVector() || VT.getVectorElementCount() ==
7192 "Vector element count mismatch!");
7193 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7194 if (N1.isUndef())
7195 return getUNDEF(VT);
7196 break;
7197 case ISD::FP_TO_SINT:
7198 case ISD::FP_TO_UINT:
7199 if (N1.isUndef())
7200 return getUNDEF(VT);
7201 break;
7202 case ISD::SINT_TO_FP:
7203 case ISD::UINT_TO_FP:
7204 // [us]itofp(undef) = 0, because the result value is bounded.
7205 if (N1.isUndef())
7206 return getConstantFP(0.0, DL, VT);
7207 break;
7208 case ISD::SIGN_EXTEND:
7209 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7210 "Invalid SIGN_EXTEND!");
7211 assert(VT.isVector() == N1.getValueType().isVector() &&
7212 "SIGN_EXTEND result type type should be vector iff the operand "
7213 "type is vector!");
7214 if (N1.getValueType() == VT) return N1; // noop extension
7215 assert((!VT.isVector() || VT.getVectorElementCount() ==
7217 "Vector element count mismatch!");
7218 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7219 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7220 SDNodeFlags Flags;
7221 if (OpOpcode == ISD::ZERO_EXTEND)
7222 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7223 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7224 transferDbgValues(N1, NewVal);
7225 return NewVal;
7226 }
7227
7228 if (OpOpcode == ISD::POISON)
7229 return getPOISON(VT);
7230
7231 if (N1.isUndef())
7232 // sext(undef) = 0, because the top bits will all be the same.
7233 return getConstant(0, DL, VT);
7234
7235 // Skip unnecessary sext_inreg pattern:
7236 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7237 if (OpOpcode == ISD::TRUNCATE) {
7238 SDValue OpOp = N1.getOperand(0);
7239 if (OpOp.getValueType() == VT) {
7240 unsigned NumSignExtBits =
7242 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7243 transferDbgValues(N1, OpOp);
7244 return OpOp;
7245 }
7246 }
7247 }
7248 break;
7249 case ISD::ZERO_EXTEND:
7250 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7251 "Invalid ZERO_EXTEND!");
7252 assert(VT.isVector() == N1.getValueType().isVector() &&
7253 "ZERO_EXTEND result type type should be vector iff the operand "
7254 "type is vector!");
7255 if (N1.getValueType() == VT) return N1; // noop extension
7256 assert((!VT.isVector() || VT.getVectorElementCount() ==
7258 "Vector element count mismatch!");
7259 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7260 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7261 SDNodeFlags Flags;
7262 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7263 SDValue NewVal =
7264 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7265 transferDbgValues(N1, NewVal);
7266 return NewVal;
7267 }
7268
7269 if (OpOpcode == ISD::POISON)
7270 return getPOISON(VT);
7271
7272 if (N1.isUndef())
7273 // zext(undef) = 0, because the top bits will be zero.
7274 return getConstant(0, DL, VT);
7275
7276 // Skip unnecessary zext_inreg pattern:
7277 // (zext (trunc x)) -> x iff the upper bits are known zero.
7278 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7279 // use to recognise zext_inreg patterns.
7280 if (OpOpcode == ISD::TRUNCATE) {
7281 SDValue OpOp = N1.getOperand(0);
7282 if (OpOp.getValueType() == VT) {
7283 if (OpOp.getOpcode() != ISD::AND) {
7286 if (MaskedValueIsZero(OpOp, HiBits)) {
7287 transferDbgValues(N1, OpOp);
7288 return OpOp;
7289 }
7290 }
7291 }
7292 }
7293 break;
7294 case ISD::ANY_EXTEND:
7295 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7296 "Invalid ANY_EXTEND!");
7297 assert(VT.isVector() == N1.getValueType().isVector() &&
7298 "ANY_EXTEND result type type should be vector iff the operand "
7299 "type is vector!");
7300 if (N1.getValueType() == VT) return N1; // noop extension
7301 assert((!VT.isVector() || VT.getVectorElementCount() ==
7303 "Vector element count mismatch!");
7304 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7305
7306 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7307 OpOpcode == ISD::ANY_EXTEND) {
7308 SDNodeFlags Flags;
7309 if (OpOpcode == ISD::ZERO_EXTEND)
7310 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7311 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7312 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7313 }
7314 if (N1.isUndef())
7315 return getUNDEF(VT);
7316
7317 // (ext (trunc x)) -> x
7318 if (OpOpcode == ISD::TRUNCATE) {
7319 SDValue OpOp = N1.getOperand(0);
7320 if (OpOp.getValueType() == VT) {
7321 transferDbgValues(N1, OpOp);
7322 return OpOp;
7323 }
7324 }
7325 break;
7326 case ISD::TRUNCATE:
7327 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7328 "Invalid TRUNCATE!");
7329 assert(VT.isVector() == N1.getValueType().isVector() &&
7330 "TRUNCATE result type type should be vector iff the operand "
7331 "type is vector!");
7332 if (N1.getValueType() == VT) return N1; // noop truncate
7333 assert((!VT.isVector() || VT.getVectorElementCount() ==
7335 "Vector element count mismatch!");
7336 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7337 if (OpOpcode == ISD::TRUNCATE)
7338 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7339 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7340 OpOpcode == ISD::ANY_EXTEND) {
7341 // If the source is smaller than the dest, we still need an extend.
7343 VT.getScalarType())) {
7344 SDNodeFlags Flags;
7345 if (OpOpcode == ISD::ZERO_EXTEND)
7346 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7347 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7348 }
7349 if (N1.getOperand(0).getValueType().bitsGT(VT))
7350 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7351 return N1.getOperand(0);
7352 }
7353 if (N1.isUndef())
7354 return getUNDEF(VT);
7355 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7356 return getVScale(DL, VT,
7358 break;
7362 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7363 assert(N1.getValueType().bitsLE(VT) &&
7364 "The input must be the same size or smaller than the result.");
7367 "The destination vector type must have fewer lanes than the input.");
7368 break;
7369 case ISD::ABS:
7370 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7371 if (N1.isUndef())
7372 return getConstant(0, DL, VT);
7373 break;
7375 assert(VT.isInteger() && VT == N1.getValueType() &&
7376 "Invalid ABS_MIN_POISON!");
7377 if (N1.isUndef())
7378 return getConstant(0, DL, VT);
7379 break;
7380 case ISD::BSWAP:
7381 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7382 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7383 "BSWAP types must be a multiple of 16 bits!");
7384 if (N1.isUndef())
7385 return getUNDEF(VT);
7386 // bswap(bswap(X)) -> X.
7387 if (OpOpcode == ISD::BSWAP)
7388 return N1.getOperand(0);
7389 break;
7390 case ISD::BITREVERSE:
7391 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7392 if (N1.isUndef())
7393 return getUNDEF(VT);
7394 break;
7395 case ISD::BITCAST:
7397 "Cannot BITCAST between types of different sizes!");
7398 if (VT == N1.getValueType()) return N1; // noop conversion.
7399 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7400 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7401 if (N1.isUndef())
7402 return getUNDEF(VT);
7403 break;
7405 assert(VT.isVector() && !N1.getValueType().isVector() &&
7406 (VT.getVectorElementType() == N1.getValueType() ||
7408 N1.getValueType().isInteger() &&
7410 "Illegal SCALAR_TO_VECTOR node!");
7411 if (N1.isUndef())
7412 return getUNDEF(VT);
7413 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7414 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7416 N1.getConstantOperandVal(1) == 0 &&
7417 N1.getOperand(0).getValueType() == VT)
7418 return N1.getOperand(0);
7419 break;
7420 case ISD::FNEG:
7421 // Negation of an unknown bag of bits is still completely undefined.
7422 if (N1.isUndef())
7423 return getUNDEF(VT);
7424
7425 if (OpOpcode == ISD::FNEG) // --X -> X
7426 return N1.getOperand(0);
7427 break;
7428 case ISD::FABS:
7429 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7430 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7431 break;
7432 case ISD::VSCALE:
7433 assert(VT == N1.getValueType() && "Unexpected VT!");
7434 break;
7435 case ISD::CTPOP:
7436 if (N1.getValueType().getScalarType() == MVT::i1)
7437 return N1;
7438 break;
7439 case ISD::CTLZ:
7440 case ISD::CTTZ:
7441 if (N1.getValueType().getScalarType() == MVT::i1)
7442 return getNOT(DL, N1, N1.getValueType());
7443 break;
7444 case ISD::CTLS:
7445 if (N1.getValueType().getScalarType() == MVT::i1)
7446 return getConstant(0, DL, VT);
7447 break;
7448 case ISD::VECREDUCE_ADD:
7449 if (N1.getValueType().getScalarType() == MVT::i1)
7450 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7451 break;
7454 if (N1.getValueType().getScalarType() == MVT::i1)
7455 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7456 break;
7459 if (N1.getValueType().getScalarType() == MVT::i1)
7460 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7461 break;
7462 case ISD::SPLAT_VECTOR:
7463 assert(VT.isVector() && "Wrong return type!");
7464 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7465 // that for now.
7467 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7469 N1.getValueType().isInteger() &&
7471 "Wrong operand type!");
7472 break;
7473 }
7474
7475 SDNode *N;
7476 SDVTList VTs = getVTList(VT);
7477 SDValue Ops[] = {N1};
7478 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7480 AddNodeIDNode(ID, Opcode, VTs, Ops);
7481 void *IP = nullptr;
7482 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7483 E->intersectFlagsWith(Flags);
7484 return SDValue(E, 0);
7485 }
7486
7487 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7488 N->setFlags(Flags);
7489 createOperands(N, Ops);
7490 CSEMap.InsertNode(N, IP);
7491 } else {
7492 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7493 createOperands(N, Ops);
7494 }
7495
7496 InsertNode(N);
7497 SDValue V = SDValue(N, 0);
7498 NewSDValueDbgMsg(V, "Creating new node: ", this);
7499 return V;
7500}
7501
7502static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7503 switch (Opcode) {
7504 default:
7505 llvm_unreachable("Unexpected integer identity opcode");
7506 case ISD::ADD:
7507 case ISD::OR:
7508 case ISD::XOR:
7509 case ISD::UMAX:
7510 return APInt::getZero(BitWidth);
7511 case ISD::MUL:
7512 return APInt(BitWidth, 1);
7513 case ISD::AND:
7514 case ISD::UMIN:
7516 case ISD::SMAX:
7518 case ISD::SMIN:
7520 }
7521}
7522
7523static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7524 const APInt &C2) {
7525 switch (Opcode) {
7526 case ISD::ADD: return C1 + C2;
7527 case ISD::SUB: return C1 - C2;
7528 case ISD::MUL: return C1 * C2;
7529 case ISD::AND: return C1 & C2;
7530 case ISD::OR: return C1 | C2;
7531 case ISD::XOR: return C1 ^ C2;
7532 case ISD::SHL: return C1 << C2;
7533 case ISD::SRL: return C1.lshr(C2);
7534 case ISD::SRA: return C1.ashr(C2);
7535 case ISD::ROTL: return C1.rotl(C2);
7536 case ISD::ROTR: return C1.rotr(C2);
7537 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7538 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7539 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7540 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7541 case ISD::SADDSAT: return C1.sadd_sat(C2);
7542 case ISD::UADDSAT: return C1.uadd_sat(C2);
7543 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7544 case ISD::USUBSAT: return C1.usub_sat(C2);
7545 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7546 case ISD::USHLSAT: return C1.ushl_sat(C2);
7547 case ISD::UDIV:
7548 if (!C2.getBoolValue())
7549 break;
7550 return C1.udiv(C2);
7551 case ISD::UREM:
7552 if (!C2.getBoolValue())
7553 break;
7554 return C1.urem(C2);
7555 case ISD::SDIV:
7556 if (!C2.getBoolValue())
7557 break;
7558 return C1.sdiv(C2);
7559 case ISD::SREM:
7560 if (!C2.getBoolValue())
7561 break;
7562 return C1.srem(C2);
7563 case ISD::AVGFLOORS:
7564 return APIntOps::avgFloorS(C1, C2);
7565 case ISD::AVGFLOORU:
7566 return APIntOps::avgFloorU(C1, C2);
7567 case ISD::AVGCEILS:
7568 return APIntOps::avgCeilS(C1, C2);
7569 case ISD::AVGCEILU:
7570 return APIntOps::avgCeilU(C1, C2);
7571 case ISD::ABDS:
7572 return APIntOps::abds(C1, C2);
7573 case ISD::ABDU:
7574 return APIntOps::abdu(C1, C2);
7575 case ISD::MULHS:
7576 return APIntOps::mulhs(C1, C2);
7577 case ISD::MULHU:
7578 return APIntOps::mulhu(C1, C2);
7579 case ISD::CLMUL:
7580 return APIntOps::clmul(C1, C2);
7581 case ISD::CLMULR:
7582 return APIntOps::clmulr(C1, C2);
7583 case ISD::CLMULH:
7584 return APIntOps::clmulh(C1, C2);
7585 case ISD::PEXT:
7586 return APIntOps::pext(C1, C2);
7587 case ISD::PDEP:
7588 return APIntOps::pdep(C1, C2);
7589 }
7590 return std::nullopt;
7591}
7592// Handle constant folding with UNDEF.
7593// TODO: Handle more cases.
7594static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7595 bool IsUndef1, const APInt &C2,
7596 bool IsUndef2) {
7597 if (!(IsUndef1 || IsUndef2))
7598 return FoldValue(Opcode, C1, C2);
7599
7600 // Fold and(x, undef) -> 0
7601 // Fold mul(x, undef) -> 0
7602 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7603 return APInt::getZero(C1.getBitWidth());
7604
7605 return std::nullopt;
7606}
7607
7609 const GlobalAddressSDNode *GA,
7610 const SDNode *N2) {
7611 if (GA->getOpcode() != ISD::GlobalAddress)
7612 return SDValue();
7613 if (!TLI->isOffsetFoldingLegal(GA))
7614 return SDValue();
7615 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7616 if (!C2)
7617 return SDValue();
7618 int64_t Offset = C2->getSExtValue();
7619 switch (Opcode) {
7620 case ISD::ADD:
7621 case ISD::PTRADD:
7622 break;
7623 case ISD::SUB: Offset = -uint64_t(Offset); break;
7624 default: return SDValue();
7625 }
7626 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7627 GA->getOffset() + uint64_t(Offset));
7628}
7629
7631 switch (Opcode) {
7632 case ISD::SDIV:
7633 case ISD::UDIV:
7634 case ISD::SREM:
7635 case ISD::UREM: {
7636 // If a divisor is zero/undef or any element of a divisor vector is
7637 // zero/undef, the whole op is undef.
7638 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7639 SDValue Divisor = Ops[1];
7640 if (Divisor.isUndef() || isNullConstant(Divisor))
7641 return true;
7642
7643 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7644 llvm::any_of(Divisor->op_values(),
7645 [](SDValue V) { return V.isUndef() ||
7646 isNullConstant(V); });
7647 // TODO: Handle signed overflow.
7648 }
7649 // TODO: Handle oversized shifts.
7650 default:
7651 return false;
7652 }
7653}
7654
7657 SDNodeFlags Flags) {
7658 // If the opcode is a target-specific ISD node, there's nothing we can
7659 // do here and the operand rules may not line up with the below, so
7660 // bail early.
7661 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7662 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7663 // foldCONCAT_VECTORS in getNode before this is called.
7664 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7665 return SDValue();
7666
7667 unsigned NumOps = Ops.size();
7668 if (NumOps == 0)
7669 return SDValue();
7670
7671 if (isUndef(Opcode, Ops))
7672 return getUNDEF(VT);
7673
7674 // Handle unary special cases.
7675 if (NumOps == 1) {
7676 SDValue N1 = Ops[0];
7677
7678 // Constant fold unary operations with an integer constant operand. Even
7679 // opaque constant will be folded, because the folding of unary operations
7680 // doesn't create new constants with different values. Nevertheless, the
7681 // opaque flag is preserved during folding to prevent future folding with
7682 // other constants.
7683 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7684 const APInt &Val = C->getAPIntValue();
7685 switch (Opcode) {
7686 case ISD::SIGN_EXTEND:
7687 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7688 C->isTargetOpcode(), C->isOpaque());
7689 case ISD::TRUNCATE:
7690 if (C->isOpaque())
7691 break;
7692 [[fallthrough]];
7693 case ISD::ZERO_EXTEND:
7694 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7695 C->isTargetOpcode(), C->isOpaque());
7696 case ISD::ANY_EXTEND:
7697 // Some targets like RISCV prefer to sign extend some types.
7698 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7699 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7700 C->isTargetOpcode(), C->isOpaque());
7701 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7702 C->isTargetOpcode(), C->isOpaque());
7703 case ISD::ABS:
7704 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7705 C->isOpaque());
7707 if (Val.isMinSignedValue())
7708 return getPOISON(VT);
7709 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7710 C->isOpaque());
7711 case ISD::BITREVERSE:
7712 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7713 C->isOpaque());
7714 case ISD::BSWAP:
7715 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7716 C->isOpaque());
7717 case ISD::CTPOP:
7718 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7719 C->isOpaque());
7720 case ISD::CTLZ:
7722 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7723 C->isOpaque());
7724 case ISD::CTTZ:
7726 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7727 C->isOpaque());
7728 case ISD::CTLS:
7729 // CTLS returns the number of extra sign bits so subtract one.
7730 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7731 C->isTargetOpcode(), C->isOpaque());
7732 case ISD::UINT_TO_FP:
7733 case ISD::SINT_TO_FP: {
7735 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7737 return getConstantFP(FPV, DL, VT);
7738 }
7739 case ISD::FP16_TO_FP:
7740 case ISD::BF16_TO_FP: {
7741 bool Ignored;
7742 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7743 : APFloat::BFloat(),
7744 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7745
7746 // This can return overflow, underflow, or inexact; we don't care.
7747 // FIXME need to be more flexible about rounding mode.
7749 &Ignored);
7750 return getConstantFP(FPV, DL, VT);
7751 }
7752 case ISD::STEP_VECTOR:
7753 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7754 return V;
7755 break;
7756 case ISD::BITCAST:
7757 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7758 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7759 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7760 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7761 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7762 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7763 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7764 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7765 break;
7766 }
7767 }
7768
7769 // Constant fold unary operations with a floating point constant operand.
7770 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7771 APFloat V = C->getValueAPF(); // make copy
7772 switch (Opcode) {
7773 case ISD::FNEG:
7774 V.changeSign();
7775 return getConstantFP(V, DL, VT);
7776 case ISD::FABS:
7777 V.clearSign();
7778 return getConstantFP(V, DL, VT);
7779 case ISD::FCEIL: {
7780 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7782 return getConstantFP(V, DL, VT);
7783 return SDValue();
7784 }
7785 case ISD::FTRUNC: {
7786 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7788 return getConstantFP(V, DL, VT);
7789 return SDValue();
7790 }
7791 case ISD::FFLOOR: {
7792 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7794 return getConstantFP(V, DL, VT);
7795 return SDValue();
7796 }
7797 case ISD::FP_EXTEND: {
7798 bool ignored;
7799 // This can return overflow, underflow, or inexact; we don't care.
7800 // FIXME need to be more flexible about rounding mode.
7801 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7802 &ignored);
7803 return getConstantFP(V, DL, VT);
7804 }
7805 case ISD::FP_TO_SINT:
7806 case ISD::FP_TO_UINT: {
7807 bool ignored;
7808 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7809 // FIXME need to be more flexible about rounding mode.
7811 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7812 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7813 break;
7814 return getConstant(IntVal, DL, VT);
7815 }
7816 case ISD::FP_TO_FP16:
7817 case ISD::FP_TO_BF16: {
7818 bool Ignored;
7819 // This can return overflow, underflow, or inexact; we don't care.
7820 // FIXME need to be more flexible about rounding mode.
7821 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7822 : APFloat::BFloat(),
7824 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7825 }
7826 case ISD::BITCAST:
7827 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7828 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7829 VT);
7830 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7831 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7832 VT);
7833 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7834 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7835 VT);
7836 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7837 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7838 break;
7839 }
7840 }
7841
7842 // Early-out if we failed to constant fold a bitcast.
7843 if (Opcode == ISD::BITCAST)
7844 return SDValue();
7845
7846 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7847 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7848 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7849 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7850 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7851 Opcode == ISD::VECREDUCE_AND) &&
7853 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7854 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7855 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7856 for (SDValue Elt : N1->op_values()) {
7857 if (Elt.getOpcode() == ISD::POISON)
7858 return getPOISON(VT);
7859 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7860 return SDValue();
7861 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7862 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7863 assert(Folded &&
7864 "Expected vector reduction base opcode to be foldable");
7865 Acc = *Folded;
7866 }
7867 EVT EltVT = N1.getValueType().getScalarType();
7868 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7869 }
7870 }
7871
7872 // Handle binops special cases.
7873 if (NumOps == 2) {
7874 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7875 return CFP;
7876
7877 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7878 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7879 if (C1->isOpaque() || C2->isOpaque())
7880 return SDValue();
7881
7882 std::optional<APInt> FoldAttempt =
7883 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7884 if (!FoldAttempt)
7885 return SDValue();
7886
7887 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7888 assert((!Folded || !VT.isVector()) &&
7889 "Can't fold vectors ops with scalar operands");
7890 return Folded;
7891 }
7892 }
7893
7894 // fold (add Sym, c) -> Sym+c
7896 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7897 if (TLI->isCommutativeBinOp(Opcode))
7899 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7900
7901 // fold (sext_in_reg c1) -> c2
7902 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7903 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7904
7905 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7906 unsigned FromBits = EVT.getScalarSizeInBits();
7907 Val <<= Val.getBitWidth() - FromBits;
7908 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7909 return getConstant(Val, DL, ConstantVT);
7910 };
7911
7912 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7913 const APInt &Val = C1->getAPIntValue();
7914 return SignExtendInReg(Val, VT);
7915 }
7916
7918 SmallVector<SDValue, 8> ScalarOps;
7919 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7920 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7921 SDValue Op = Ops[0].getOperand(I);
7922 if (Op.isUndef()) {
7923 ScalarOps.push_back(getUNDEF(OpVT));
7924 continue;
7925 }
7926 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7927 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7928 }
7929 return getBuildVector(VT, DL, ScalarOps);
7930 }
7931
7932 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7933 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7934 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7935 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7936 Ops[0].getOperand(0).getValueType()));
7937 }
7938 }
7939
7940 // Handle fshl/fshr special cases.
7941 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7942 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7943 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7944 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7945
7946 if (C1 && C2 && C3) {
7947 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7948 return SDValue();
7949 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7950 &V3 = C3->getAPIntValue();
7951
7952 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7953 : APIntOps::fshr(V1, V2, V3);
7954 return getConstant(FoldedVal, DL, VT);
7955 }
7956 }
7957
7958 // Handle fma/fmad special cases.
7959 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7960 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7961 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7962 Ops[2].getValueType() == VT && "FMA types must match!");
7966 if (C1 && C2 && C3) {
7967 APFloat V1 = C1->getValueAPF();
7968 const APFloat &V2 = C2->getValueAPF();
7969 const APFloat &V3 = C3->getValueAPF();
7970 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7971 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7973 } else
7974 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7975 return getConstantFP(V1, DL, VT);
7976 }
7977 }
7978
7979 // This is for vector folding only from here on.
7980 if (!VT.isVector())
7981 return SDValue();
7982
7983 ElementCount NumElts = VT.getVectorElementCount();
7984
7985 // See if we can fold through any bitcasted integer ops.
7986 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
7987 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7988 (Ops[0].getOpcode() == ISD::BITCAST ||
7989 Ops[1].getOpcode() == ISD::BITCAST)) {
7992 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7993 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
7994 if (BV1 && BV2 && N1.getValueType().isInteger() &&
7995 N2.getValueType().isInteger()) {
7996 bool IsLE = getDataLayout().isLittleEndian();
7997 unsigned EltBits = VT.getScalarSizeInBits();
7998 SmallVector<APInt> RawBits1, RawBits2;
7999 BitVector UndefElts1, UndefElts2;
8000 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8001 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8002 SmallVector<APInt> RawBits;
8003 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8004 std::optional<APInt> Fold = FoldValueWithUndef(
8005 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8006 if (!Fold)
8007 break;
8008 RawBits.push_back(*Fold);
8009 }
8010 if (RawBits.size() == NumElts.getFixedValue()) {
8011 // We have constant folded, but we might need to cast this again back
8012 // to the original (possibly legalized) type.
8013 EVT BVVT, BVEltVT;
8014 if (N1.getValueType() == VT) {
8015 BVVT = N1.getValueType();
8016 BVEltVT = BV1->getOperand(0).getValueType();
8017 } else {
8018 BVVT = N2.getValueType();
8019 BVEltVT = BV2->getOperand(0).getValueType();
8020 }
8021 unsigned BVEltBits = BVEltVT.getSizeInBits();
8022 SmallVector<APInt> DstBits;
8023 BitVector DstUndefs;
8025 DstBits, RawBits, DstUndefs,
8026 BitVector(RawBits.size(), false));
8027 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8028 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8029 if (DstUndefs[I])
8030 continue;
8031 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8032 }
8033 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8034 }
8035 }
8036 }
8037 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8038 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8039 isa<ConstantSDNode>(N2)) {
8040 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8041 {N1, N2}, Flags))
8042 return getBitcast(VT, Res);
8043 }
8044 }
8045
8046 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8047 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8048 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8049 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8050 APInt RHSVal;
8051 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8052 APInt NewStep = Opcode == ISD::MUL
8053 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8054 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8055 return getStepVector(DL, VT, NewStep);
8056 }
8057 }
8058
8059 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8060 return !Op.getValueType().isVector() ||
8061 Op.getValueType().getVectorElementCount() == NumElts;
8062 };
8063
8064 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8065 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8066 Op.getOpcode() == ISD::BUILD_VECTOR ||
8067 Op.getOpcode() == ISD::SPLAT_VECTOR;
8068 };
8069
8070 // All operands must be vector types with the same number of elements as
8071 // the result type and must be either UNDEF or a build/splat vector
8072 // or UNDEF scalars.
8073 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8074 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8075 return SDValue();
8076
8077 // If we are comparing vectors, then the result needs to be a i1 boolean that
8078 // is then extended back to the legal result type depending on how booleans
8079 // are represented.
8080 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8081 ISD::NodeType ExtendCode =
8082 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8083 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8085
8086 // Find legal integer scalar type for constant promotion and
8087 // ensure that its scalar size is at least as large as source.
8088 EVT LegalSVT = VT.getScalarType();
8089 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8090 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8091 if (LegalSVT.bitsLT(VT.getScalarType()))
8092 return SDValue();
8093 }
8094
8095 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8096 // only have one operand to check. For fixed-length vector types we may have
8097 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8098 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8099
8100 // Constant fold each scalar lane separately.
8101 SmallVector<SDValue, 4> ScalarResults;
8102 for (unsigned I = 0; I != NumVectorElts; I++) {
8103 SmallVector<SDValue, 4> ScalarOps;
8104 for (SDValue Op : Ops) {
8105 EVT InSVT = Op.getValueType().getScalarType();
8106 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8107 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8108 if (Op.isUndef())
8109 ScalarOps.push_back(getUNDEF(InSVT));
8110 else
8111 ScalarOps.push_back(Op);
8112 continue;
8113 }
8114
8115 SDValue ScalarOp =
8116 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8117 EVT ScalarVT = ScalarOp.getValueType();
8118
8119 // Build vector (integer) scalar operands may need implicit
8120 // truncation - do this before constant folding.
8121 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8122 // Don't create illegally-typed nodes unless they're constants or undef
8123 // - if we fail to constant fold we can't guarantee the (dead) nodes
8124 // we're creating will be cleaned up before being visited for
8125 // legalization.
8126 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8127 !isa<ConstantSDNode>(ScalarOp) &&
8128 TLI->getTypeAction(*getContext(), InSVT) !=
8130 return SDValue();
8131 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8132 }
8133
8134 ScalarOps.push_back(ScalarOp);
8135 }
8136
8137 // Constant fold the scalar operands.
8138 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8139
8140 // Scalar folding only succeeded if the result is a constant or UNDEF.
8141 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8142 ScalarResult.getOpcode() != ISD::ConstantFP)
8143 return SDValue();
8144
8145 // Legalize the (integer) scalar constant if necessary. We only do
8146 // this once we know the folding succeeded, since otherwise we would
8147 // get a node with illegal type which has a user.
8148 if (LegalSVT != SVT)
8149 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8150
8151 ScalarResults.push_back(ScalarResult);
8152 }
8153
8154 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8155 : getBuildVector(VT, DL, ScalarResults);
8156 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8157 return V;
8158}
8159
8162 // TODO: Add support for unary/ternary fp opcodes.
8163 if (Ops.size() != 2)
8164 return SDValue();
8165
8166 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8167 // should. That will require dealing with a potentially non-default
8168 // rounding mode, checking the "opStatus" return value from the APFloat
8169 // math calculations, and possibly other variations.
8170 SDValue N1 = Ops[0];
8171 SDValue N2 = Ops[1];
8172 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8173 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8174 if (N1CFP && N2CFP) {
8175 APFloat C1 = N1CFP->getValueAPF(); // make copy
8176 const APFloat &C2 = N2CFP->getValueAPF();
8177 switch (Opcode) {
8178 case ISD::FADD:
8180 return getConstantFP(C1, DL, VT);
8181 case ISD::FSUB:
8183 return getConstantFP(C1, DL, VT);
8184 case ISD::FMUL:
8186 return getConstantFP(C1, DL, VT);
8187 case ISD::FDIV:
8189 return getConstantFP(C1, DL, VT);
8190 case ISD::FREM:
8191 C1.mod(C2);
8192 return getConstantFP(C1, DL, VT);
8193 case ISD::FCOPYSIGN:
8194 C1.copySign(C2);
8195 return getConstantFP(C1, DL, VT);
8196 case ISD::FMINNUM:
8197 return getConstantFP(minnum(C1, C2), DL, VT);
8198 case ISD::FMAXNUM:
8199 return getConstantFP(maxnum(C1, C2), DL, VT);
8200 case ISD::FMINIMUM:
8201 return getConstantFP(minimum(C1, C2), DL, VT);
8202 case ISD::FMAXIMUM:
8203 return getConstantFP(maximum(C1, C2), DL, VT);
8204 case ISD::FMINIMUMNUM:
8205 return getConstantFP(minimumnum(C1, C2), DL, VT);
8206 case ISD::FMAXIMUMNUM:
8207 return getConstantFP(maximumnum(C1, C2), DL, VT);
8208 default: break;
8209 }
8210 }
8211 if (N1CFP && Opcode == ISD::FP_ROUND) {
8212 APFloat C1 = N1CFP->getValueAPF(); // make copy
8213 bool Unused;
8214 // This can return overflow, underflow, or inexact; we don't care.
8215 // FIXME need to be more flexible about rounding mode.
8217 &Unused);
8218 return getConstantFP(C1, DL, VT);
8219 }
8220
8221 switch (Opcode) {
8222 case ISD::FSUB:
8223 // -0.0 - undef --> undef (consistent with "fneg undef")
8224 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8225 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8226 return getUNDEF(VT);
8227 [[fallthrough]];
8228
8229 case ISD::FADD:
8230 case ISD::FMUL:
8231 case ISD::FDIV:
8232 case ISD::FREM:
8233 // If both operands are undef, the result is undef. If 1 operand is undef,
8234 // the result is NaN. This should match the behavior of the IR optimizer.
8235 if (N1.isUndef() && N2.isUndef())
8236 return getUNDEF(VT);
8237 if (N1.isUndef() || N2.isUndef())
8239 }
8240 return SDValue();
8241}
8242
8244 const SDLoc &DL, EVT DstEltVT) {
8245 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8246
8247 // If this is already the right type, we're done.
8248 if (SrcEltVT == DstEltVT)
8249 return SDValue(BV, 0);
8250
8251 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8252 unsigned DstBitSize = DstEltVT.getSizeInBits();
8253
8254 // If this is a conversion of N elements of one type to N elements of another
8255 // type, convert each element. This handles FP<->INT cases.
8256 if (SrcBitSize == DstBitSize) {
8258 for (SDValue Op : BV->op_values()) {
8259 // If the vector element type is not legal, the BUILD_VECTOR operands
8260 // are promoted and implicitly truncated. Make that explicit here.
8261 if (Op.getValueType() != SrcEltVT)
8262 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8263 Ops.push_back(getBitcast(DstEltVT, Op));
8264 }
8265 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8267 return getBuildVector(VT, DL, Ops);
8268 }
8269
8270 // Otherwise, we're growing or shrinking the elements. To avoid having to
8271 // handle annoying details of growing/shrinking FP values, we convert them to
8272 // int first.
8273 if (SrcEltVT.isFloatingPoint()) {
8274 // Convert the input float vector to a int vector where the elements are the
8275 // same sizes.
8276 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8277 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8279 DstEltVT);
8280 return SDValue();
8281 }
8282
8283 // Now we know the input is an integer vector. If the output is a FP type,
8284 // convert to integer first, then to FP of the right size.
8285 if (DstEltVT.isFloatingPoint()) {
8286 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8287 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8289 DstEltVT);
8290 return SDValue();
8291 }
8292
8293 // Okay, we know the src/dst types are both integers of differing types.
8294 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8295
8296 // Extract the constant raw bit data.
8297 BitVector UndefElements;
8298 SmallVector<APInt> RawBits;
8299 bool IsLE = getDataLayout().isLittleEndian();
8300 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8301 return SDValue();
8302
8304 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8305 if (UndefElements[I])
8306 Ops.push_back(getUNDEF(DstEltVT));
8307 else
8308 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8309 }
8310
8311 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8312 return getBuildVector(VT, DL, Ops);
8313}
8314
8316 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8317
8318 // There's no need to assert on a byte-aligned pointer. All pointers are at
8319 // least byte aligned.
8320 if (A == Align(1))
8321 return Val;
8322
8323 SDVTList VTs = getVTList(Val.getValueType());
8325 AddNodeIDNode(ID, ISD::AssertAlign, VTs, {Val});
8326 ID.AddInteger(A.value());
8327
8328 void *IP = nullptr;
8329 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8330 return SDValue(E, 0);
8331
8332 auto *N =
8333 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8334 createOperands(N, {Val});
8335
8336 CSEMap.InsertNode(N, IP);
8337 InsertNode(N);
8338
8339 SDValue V(N, 0);
8340 NewSDValueDbgMsg(V, "Creating new node: ", this);
8341 return V;
8342}
8343
8344SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8345 SDValue N1, SDValue N2) {
8346 SDNodeFlags Flags;
8347 if (Inserter)
8348 Flags = Inserter->getFlags();
8349 return getNode(Opcode, DL, VT, N1, N2, Flags);
8350}
8351
8353 SDValue &N2) const {
8354 if (!TLI->isCommutativeBinOp(Opcode))
8355 return;
8356
8357 // Canonicalize:
8358 // binop(const, nonconst) -> binop(nonconst, const)
8361 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8362 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8363 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8364 std::swap(N1, N2);
8365
8366 // Canonicalize:
8367 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8368 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8370 std::swap(N1, N2);
8371}
8372
8373SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8374 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8376 N2.getOpcode() != ISD::DELETED_NODE &&
8377 "Operand is DELETED_NODE!");
8378
8379 canonicalizeCommutativeBinop(Opcode, N1, N2);
8380
8381 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8382 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8383
8384 // Don't allow undefs in vector splats - we might be returning N2 when folding
8385 // to zero etc.
8386 ConstantSDNode *N2CV =
8387 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8388
8389 switch (Opcode) {
8390 default: break;
8391 case ISD::TokenFactor:
8392 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8393 N2.getValueType() == MVT::Other && "Invalid token factor!");
8394 // Fold trivial token factors.
8395 if (N1.getOpcode() == ISD::EntryToken) return N2;
8396 if (N2.getOpcode() == ISD::EntryToken) return N1;
8397 if (N1 == N2) return N1;
8398 break;
8399 case ISD::BUILD_VECTOR: {
8400 // Attempt to simplify BUILD_VECTOR.
8401 SDValue Ops[] = {N1, N2};
8402 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8403 return V;
8404 break;
8405 }
8406 case ISD::CONCAT_VECTORS: {
8407 SDValue Ops[] = {N1, N2};
8408 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8409 return V;
8410 break;
8411 }
8412 case ISD::AND:
8413 assert(VT.isInteger() && "This operator does not apply to FP types!");
8414 assert(N1.getValueType() == N2.getValueType() &&
8415 N1.getValueType() == VT && "Binary operator types must match!");
8416 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8417 // worth handling here.
8418 if (N2CV && N2CV->isZero())
8419 return N2;
8420 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8421 return N1;
8422 break;
8423 case ISD::OR:
8424 case ISD::XOR:
8425 case ISD::ADD:
8426 case ISD::PTRADD:
8427 case ISD::SUB:
8428 assert(VT.isInteger() && "This operator does not apply to FP types!");
8429 assert(N1.getValueType() == N2.getValueType() &&
8430 N1.getValueType() == VT && "Binary operator types must match!");
8431 // The equal operand types requirement is unnecessarily strong for PTRADD.
8432 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8433 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8434 // logic everywhere where PTRADDs may be folded or combined to properly
8435 // support them. If/when we introduce pointer types to the SDAG, we will
8436 // need to relax this constraint.
8437
8438 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8439 // it's worth handling here.
8440 if (N2CV && N2CV->isZero())
8441 return N1;
8442 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8443 VT.getScalarType() == MVT::i1)
8444 return getNode(ISD::XOR, DL, VT, N1, N2);
8445 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8446 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8447 N2.getOpcode() == ISD::VSCALE) {
8448 const APInt &C1 = N1->getConstantOperandAPInt(0);
8449 const APInt &C2 = N2->getConstantOperandAPInt(0);
8450 return getVScale(DL, VT, C1 + C2);
8451 }
8452 break;
8453 case ISD::MUL:
8454 assert(VT.isInteger() && "This operator does not apply to FP types!");
8455 assert(N1.getValueType() == N2.getValueType() &&
8456 N1.getValueType() == VT && "Binary operator types must match!");
8457 if (VT.getScalarType() == MVT::i1)
8458 return getNode(ISD::AND, DL, VT, N1, N2);
8459 if (N2CV && N2CV->isZero())
8460 return N2;
8461 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8462 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8463 const APInt &N2CImm = N2C->getAPIntValue();
8464 return getVScale(DL, VT, MulImm * N2CImm);
8465 }
8466 break;
8467 case ISD::UDIV:
8468 case ISD::UREM:
8469 case ISD::MULHU:
8470 case ISD::MULHS:
8471 case ISD::SDIV:
8472 case ISD::SREM:
8473 case ISD::SADDSAT:
8474 case ISD::SSUBSAT:
8475 case ISD::UADDSAT:
8476 case ISD::USUBSAT:
8477 assert(VT.isInteger() && "This operator does not apply to FP types!");
8478 assert(N1.getValueType() == N2.getValueType() &&
8479 N1.getValueType() == VT && "Binary operator types must match!");
8480 if (VT.getScalarType() == MVT::i1) {
8481 // fold (add_sat x, y) -> (or x, y) for bool types.
8482 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8483 return getNode(ISD::OR, DL, VT, N1, N2);
8484 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8485 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8486 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8487 }
8488 break;
8489 case ISD::SCMP:
8490 case ISD::UCMP:
8491 assert(N1.getValueType() == N2.getValueType() &&
8492 "Types of operands of UCMP/SCMP must match");
8493 assert(N1.getValueType().isVector() == VT.isVector() &&
8494 "Operands and return type of must both be scalars or vectors");
8495 if (VT.isVector())
8498 "Result and operands must have the same number of elements");
8499 break;
8500 case ISD::AVGFLOORS:
8501 case ISD::AVGFLOORU:
8502 case ISD::AVGCEILS:
8503 case ISD::AVGCEILU:
8504 assert(VT.isInteger() && "This operator does not apply to FP types!");
8505 assert(N1.getValueType() == N2.getValueType() &&
8506 N1.getValueType() == VT && "Binary operator types must match!");
8507 break;
8508 case ISD::ABDS:
8509 case ISD::ABDU:
8510 assert(VT.isInteger() && "This operator does not apply to FP types!");
8511 assert(N1.getValueType() == N2.getValueType() &&
8512 N1.getValueType() == VT && "Binary operator types must match!");
8513 if (VT.getScalarType() == MVT::i1)
8514 return getNode(ISD::XOR, DL, VT, N1, N2);
8515 break;
8516 case ISD::SMIN:
8517 case ISD::UMAX:
8518 assert(VT.isInteger() && "This operator does not apply to FP types!");
8519 assert(N1.getValueType() == N2.getValueType() &&
8520 N1.getValueType() == VT && "Binary operator types must match!");
8521 if (VT.getScalarType() == MVT::i1)
8522 return getNode(ISD::OR, DL, VT, N1, N2);
8523 break;
8524 case ISD::SMAX:
8525 case ISD::UMIN:
8526 assert(VT.isInteger() && "This operator does not apply to FP types!");
8527 assert(N1.getValueType() == N2.getValueType() &&
8528 N1.getValueType() == VT && "Binary operator types must match!");
8529 if (VT.getScalarType() == MVT::i1)
8530 return getNode(ISD::AND, DL, VT, N1, N2);
8531 break;
8532 case ISD::FADD:
8533 case ISD::FSUB:
8534 case ISD::FMUL:
8535 case ISD::FDIV:
8536 case ISD::FREM:
8537 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8538 assert(N1.getValueType() == N2.getValueType() &&
8539 N1.getValueType() == VT && "Binary operator types must match!");
8540 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8541 return V;
8542 break;
8543 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8544 assert(N1.getValueType() == VT &&
8547 "Invalid FCOPYSIGN!");
8548 break;
8549 case ISD::SHL:
8550 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8551 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8552 const APInt &ShiftImm = N2C->getAPIntValue();
8553 return getVScale(DL, VT, MulImm << ShiftImm);
8554 }
8555 [[fallthrough]];
8556 case ISD::SRA:
8557 case ISD::SRL:
8558 if (SDValue V = simplifyShift(N1, N2))
8559 return V;
8560 [[fallthrough]];
8561 case ISD::ROTL:
8562 case ISD::ROTR:
8563 case ISD::SSHLSAT:
8564 case ISD::USHLSAT:
8565 assert(VT == N1.getValueType() &&
8566 "Shift operators return type must be the same as their first arg");
8567 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8568 "Shifts only work on integers");
8569 assert((!VT.isVector() || VT == N2.getValueType()) &&
8570 "Vector shift amounts must be in the same as their first arg");
8571 // Verify that the shift amount VT is big enough to hold valid shift
8572 // amounts. This catches things like trying to shift an i1024 value by an
8573 // i8, which is easy to fall into in generic code that uses
8574 // TLI.getShiftAmount().
8577 "Invalid use of small shift amount with oversized value!");
8578
8579 // Always fold shifts of i1 values so the code generator doesn't need to
8580 // handle them. Since we know the size of the shift has to be less than the
8581 // size of the value, the shift/rotate count is guaranteed to be zero.
8582 if (VT == MVT::i1)
8583 return N1;
8584 if (N2CV && N2CV->isZero())
8585 return N1;
8586 break;
8587 case ISD::FP_ROUND:
8589 VT.bitsLE(N1.getValueType()) && N2C &&
8590 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8591 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8592 if (N1.getValueType() == VT) return N1; // noop conversion.
8593 break;
8594 case ISD::IS_FPCLASS: {
8596 "IS_FPCLASS is used for a non-floating type");
8597 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8598 // is.fpclass(poison, mask) -> poison
8599 if (N1.getOpcode() == ISD::POISON)
8600 return getPOISON(VT);
8601 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8602 // If all tests are made, it doesn't matter what the value is.
8603 if ((Mask & fcAllFlags) == fcAllFlags)
8604 return getBoolConstant(true, DL, VT, N1.getValueType());
8605 if ((Mask & fcAllFlags) == 0)
8606 return getBoolConstant(false, DL, VT, N1.getValueType());
8607 break;
8608 }
8609 case ISD::AssertNoFPClass: {
8611 "AssertNoFPClass is used for a non-floating type");
8612 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8613 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8614 assert(llvm::to_underlying(NoFPClass) <=
8616 "FPClassTest value too large");
8617 (void)NoFPClass;
8618 break;
8619 }
8620 case ISD::AssertSext:
8621 case ISD::AssertZext: {
8622 EVT EVT = cast<VTSDNode>(N2)->getVT();
8623 assert(VT == N1.getValueType() && "Not an inreg extend!");
8624 assert(VT.isInteger() && EVT.isInteger() &&
8625 "Cannot *_EXTEND_INREG FP types");
8626 assert(!EVT.isVector() &&
8627 "AssertSExt/AssertZExt type should be the vector element type "
8628 "rather than the vector type!");
8629 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8630 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8631 break;
8632 }
8634 EVT EVT = cast<VTSDNode>(N2)->getVT();
8635 assert(VT == N1.getValueType() && "Not an inreg extend!");
8636 assert(VT.isInteger() && EVT.isInteger() &&
8637 "Cannot *_EXTEND_INREG FP types");
8638 assert(EVT.isVector() == VT.isVector() &&
8639 "SIGN_EXTEND_INREG type should be vector iff the operand "
8640 "type is vector!");
8641 assert((!EVT.isVector() ||
8643 "Vector element counts must match in SIGN_EXTEND_INREG");
8644 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8645 if (EVT == VT) return N1; // Not actually extending
8646 break;
8647 }
8649 case ISD::FP_TO_UINT_SAT: {
8650 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8651 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8652 assert(N1.getValueType().isVector() == VT.isVector() &&
8653 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8654 "vector!");
8655 assert((!VT.isVector() || VT.getVectorElementCount() ==
8657 "Vector element counts must match in FP_TO_*INT_SAT");
8658 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8659 "Type to saturate to must be a scalar.");
8660 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8661 "Not extending!");
8662 break;
8663 }
8666 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8667 element type of the vector.");
8668
8669 // Extract from an undefined value or using an undefined index is undefined.
8670 if (N1.isUndef() || N2.isUndef())
8671 return getUNDEF(VT);
8672
8673 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8674 // vectors. For scalable vectors we will provide appropriate support for
8675 // dealing with arbitrary indices.
8676 if (N2C && N1.getValueType().isFixedLengthVector() &&
8677 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8678 return getPOISON(VT);
8679
8680 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8681 // expanding copies of large vectors from registers. This only works for
8682 // fixed length vectors, since we need to know the exact number of
8683 // elements.
8684 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8686 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8687 return getExtractVectorElt(DL, VT,
8688 N1.getOperand(N2C->getZExtValue() / Factor),
8689 N2C->getZExtValue() % Factor);
8690 }
8691
8692 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8693 // lowering is expanding large vector constants.
8694 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8695 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8698 "BUILD_VECTOR used for scalable vectors");
8699 unsigned Index =
8700 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8701 SDValue Elt = N1.getOperand(Index);
8702
8703 if (VT != Elt.getValueType())
8704 // If the vector element type is not legal, the BUILD_VECTOR operands
8705 // are promoted and implicitly truncated, and the result implicitly
8706 // extended. Make that explicit here.
8707 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8708
8709 return Elt;
8710 }
8711
8712 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8713 // operations are lowered to scalars.
8714 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8715 // If the indices are the same, return the inserted element else
8716 // if the indices are known different, extract the element from
8717 // the original vector.
8718 SDValue N1Op2 = N1.getOperand(2);
8720
8721 if (N1Op2C && N2C) {
8722 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8723 if (VT == N1.getOperand(1).getValueType())
8724 return N1.getOperand(1);
8725 if (VT.isFloatingPoint()) {
8727 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8728 }
8729 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8730 }
8731 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8732 }
8733 }
8734
8735 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8736 // when vector types are scalarized and v1iX is legal.
8737 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8738 // Here we are completely ignoring the extract element index (N2),
8739 // which is fine for fixed width vectors, since any index other than 0
8740 // is undefined anyway. However, this cannot be ignored for scalable
8741 // vectors - in theory we could support this, but we don't want to do this
8742 // without a profitability check.
8743 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8745 N1.getValueType().getVectorNumElements() == 1) {
8746 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8747 N1.getOperand(1));
8748 }
8749 break;
8751 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8752 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8753 (N1.getValueType().isInteger() == VT.isInteger()) &&
8754 N1.getValueType() != VT &&
8755 "Wrong types for EXTRACT_ELEMENT!");
8756
8757 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8758 // 64-bit integers into 32-bit parts. Instead of building the extract of
8759 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8760 if (N1.getOpcode() == ISD::BUILD_PAIR)
8761 return N1.getOperand(N2C->getZExtValue());
8762
8763 // EXTRACT_ELEMENT of a constant int is also very common.
8764 if (N1C) {
8765 unsigned ElementSize = VT.getSizeInBits();
8766 unsigned Shift = ElementSize * N2C->getZExtValue();
8767 const APInt &Val = N1C->getAPIntValue();
8768 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8769 }
8770 break;
8772 EVT N1VT = N1.getValueType();
8773 assert(VT.isVector() && N1VT.isVector() &&
8774 "Extract subvector VTs must be vectors!");
8776 "Extract subvector VTs must have the same element type!");
8777 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8778 "Cannot extract a scalable vector from a fixed length vector!");
8779 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8781 "Extract subvector must be from larger vector to smaller vector!");
8782 assert(N2C && "Extract subvector index must be a constant");
8783 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8784 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8785 N1VT.getVectorMinNumElements()) &&
8786 "Extract subvector overflow!");
8787 assert(N2C->getAPIntValue().getBitWidth() ==
8788 TLI->getVectorIdxWidth(getDataLayout()) &&
8789 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8790 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8791 "Extract index is not a multiple of the output vector length");
8792
8793 // Trivial extraction.
8794 if (VT == N1VT)
8795 return N1;
8796
8797 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8798 if (N1.isUndef())
8799 return getUNDEF(VT);
8800
8801 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8802 // the concat have the same type as the extract.
8803 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8804 VT == N1.getOperand(0).getValueType()) {
8805 unsigned Factor = VT.getVectorMinNumElements();
8806 return N1.getOperand(N2C->getZExtValue() / Factor);
8807 }
8808
8809 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8810 // during shuffle legalization.
8811 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8812 VT == N1.getOperand(1).getValueType())
8813 return N1.getOperand(1);
8814 break;
8815 }
8816 }
8817
8818 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8819 switch (Opcode) {
8820 case ISD::XOR:
8821 case ISD::ADD:
8822 case ISD::PTRADD:
8823 case ISD::SUB:
8825 case ISD::UDIV:
8826 case ISD::SDIV:
8827 case ISD::UREM:
8828 case ISD::SREM:
8829 case ISD::MUL:
8830 case ISD::AND:
8831 case ISD::SSUBSAT:
8832 case ISD::USUBSAT:
8833 case ISD::UMIN:
8834 case ISD::OR:
8835 case ISD::SADDSAT:
8836 case ISD::UADDSAT:
8837 case ISD::UMAX:
8838 case ISD::SMAX:
8839 case ISD::SMIN:
8840 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8841 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8842 }
8843 }
8844
8845 // Canonicalize an UNDEF to the RHS, even over a constant.
8846 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8847 if (TLI->isCommutativeBinOp(Opcode)) {
8848 std::swap(N1, N2);
8849 } else {
8850 switch (Opcode) {
8851 case ISD::PTRADD:
8852 case ISD::SUB:
8853 // fold op(undef, non_undef_arg2) -> undef.
8854 return N1;
8856 case ISD::UDIV:
8857 case ISD::SDIV:
8858 case ISD::UREM:
8859 case ISD::SREM:
8860 case ISD::SSUBSAT:
8861 case ISD::USUBSAT:
8862 // fold op(undef, non_undef_arg2) -> 0.
8863 return getConstant(0, DL, VT);
8864 }
8865 }
8866 }
8867
8868 // Fold a bunch of operators when the RHS is undef.
8869 if (N2.getOpcode() == ISD::UNDEF) {
8870 switch (Opcode) {
8871 case ISD::XOR:
8872 if (N1.getOpcode() == ISD::UNDEF)
8873 // Handle undef ^ undef -> 0 special case. This is a common
8874 // idiom (misuse).
8875 return getConstant(0, DL, VT);
8876 [[fallthrough]];
8877 case ISD::ADD:
8878 case ISD::PTRADD:
8879 case ISD::SUB:
8880 // fold op(arg1, undef) -> undef.
8881 return N2;
8882 case ISD::UDIV:
8883 case ISD::SDIV:
8884 case ISD::UREM:
8885 case ISD::SREM:
8886 // fold op(arg1, undef) -> poison.
8887 return getPOISON(VT);
8888 case ISD::MUL:
8889 case ISD::AND:
8890 case ISD::SSUBSAT:
8891 case ISD::USUBSAT:
8892 case ISD::UMIN:
8893 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8894 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8895 case ISD::OR:
8896 case ISD::SADDSAT:
8897 case ISD::UADDSAT:
8898 case ISD::UMAX:
8899 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8900 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8901 case ISD::SMAX:
8902 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8903 return N1.getOpcode() == ISD::UNDEF
8904 ? N2
8905 : getConstant(
8907 VT);
8908 case ISD::SMIN:
8909 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8910 return N1.getOpcode() == ISD::UNDEF
8911 ? N2
8912 : getConstant(
8914 VT);
8915 }
8916 }
8917
8918 // Perform trivial constant folding.
8919 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
8920 return SV;
8921
8922 // Memoize this node if possible.
8923 SDNode *N;
8924 SDVTList VTs = getVTList(VT);
8925 SDValue Ops[] = {N1, N2};
8926 if (VT != MVT::Glue) {
8928 AddNodeIDNode(ID, Opcode, VTs, Ops);
8929 void *IP = nullptr;
8930 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
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.InsertNode(N, IP);
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::VP_TRUNCATE:
9129 case ISD::VP_SIGN_EXTEND:
9130 case ISD::VP_ZERO_EXTEND:
9131 // Don't create noop casts.
9132 if (N1.getValueType() == VT)
9133 return N1;
9134 break;
9135 case ISD::VECTOR_COMPRESS: {
9136 [[maybe_unused]] EVT VecVT = N1.getValueType();
9137 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9138 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9139 assert(VT == VecVT && "Vector and result type don't match.");
9140 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9141 "All inputs must be vectors.");
9142 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9144 "Vector and mask must have same number of elements.");
9145
9146 if (N1.isUndef() || N2.isUndef())
9147 return N3;
9148
9149 break;
9150 }
9155 [[maybe_unused]] EVT AccVT = N1.getValueType();
9156 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9157 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9158 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9159 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9160 "node to have the same type!");
9161 assert(VT.isVector() && VT == AccVT &&
9162 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9163 "the same type as its result!");
9165 AccVT.getVectorElementCount()) &&
9166 "Expected the element count of the second and third operands of the "
9167 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9168 "element count of the first operand and the result!");
9170 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9171 "node to have an element type which is the same as or smaller than "
9172 "the element type of the first operand and result!");
9173 break;
9174 }
9175 }
9176
9177 // Perform trivial constant folding for arithmetic operators.
9178 switch (Opcode) {
9179 case ISD::FMA:
9180 case ISD::FMAD:
9181 case ISD::SETCC:
9182 case ISD::FSHL:
9183 case ISD::FSHR:
9184 if (SDValue SV =
9185 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9186 return SV;
9187 break;
9188 }
9189
9190 // Memoize node if it doesn't produce a glue result.
9191 SDNode *N;
9192 SDVTList VTs = getVTList(VT);
9193 SDValue Ops[] = {N1, N2, N3};
9194 if (VT != MVT::Glue) {
9196 AddNodeIDNode(ID, Opcode, VTs, Ops);
9197 void *IP = nullptr;
9198 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9199 E->intersectFlagsWith(Flags);
9200 return SDValue(E, 0);
9201 }
9202
9203 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9204 N->setFlags(Flags);
9205 createOperands(N, Ops);
9206 CSEMap.InsertNode(N, IP);
9207 } else {
9208 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9209 createOperands(N, Ops);
9210 }
9211
9212 InsertNode(N);
9213 SDValue V = SDValue(N, 0);
9214 NewSDValueDbgMsg(V, "Creating new node: ", this);
9215 return V;
9216}
9217
9218SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9219 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9220 const SDNodeFlags Flags) {
9221 SDValue Ops[] = { N1, N2, N3, N4 };
9222 return getNode(Opcode, DL, VT, Ops, Flags);
9223}
9224
9225SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9226 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9227 SDNodeFlags Flags;
9228 if (Inserter)
9229 Flags = Inserter->getFlags();
9230 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9231}
9232
9233SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9234 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9235 SDValue N5, const SDNodeFlags Flags) {
9236 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9237 return getNode(Opcode, DL, VT, Ops, Flags);
9238}
9239
9240SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9241 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9242 SDValue N5) {
9243 SDNodeFlags Flags;
9244 if (Inserter)
9245 Flags = Inserter->getFlags();
9246 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9247}
9248
9249/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9250/// the incoming stack arguments to be loaded from the stack.
9252 SmallVector<SDValue, 8> ArgChains;
9253
9254 // Include the original chain at the beginning of the list. When this is
9255 // used by target LowerCall hooks, this helps legalize find the
9256 // CALLSEQ_BEGIN node.
9257 ArgChains.push_back(Chain);
9258
9259 // Add a chain value for each stack argument.
9260 for (SDNode *U : getEntryNode().getNode()->users())
9261 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9262 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9263 if (FI->getIndex() < 0)
9264 ArgChains.push_back(SDValue(L, 1));
9265
9266 // Build a tokenfactor for all the chains.
9267 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9268}
9269
9270/// getMemsetValue - Vectorized representation of the memset value
9271/// operand.
9273 const SDLoc &dl) {
9274 assert(!Value.isUndef());
9275
9276 unsigned NumBits = VT.getScalarSizeInBits();
9278 assert(C->getAPIntValue().getBitWidth() == 8);
9279 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9280 if (VT.isInteger()) {
9281 bool IsOpaque = VT.getSizeInBits() > 64 ||
9282 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9283 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9284 }
9285 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9286 }
9287
9288 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9289 EVT IntVT = VT.getScalarType();
9290 if (!IntVT.isInteger())
9291 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9292
9293 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9294 if (NumBits > 8) {
9295 // Use a multiplication with 0x010101... to extend the input to the
9296 // required length.
9297 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9298 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9299 DAG.getConstant(Magic, dl, IntVT));
9300 }
9301
9302 if (VT != Value.getValueType() && !VT.isInteger())
9303 Value = DAG.getBitcast(VT.getScalarType(), Value);
9304 if (VT != Value.getValueType())
9305 Value = DAG.getSplatBuildVector(VT, dl, Value);
9306
9307 return Value;
9308}
9309
9310/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9311/// used when a memcpy is turned into a memset when the source is a constant
9312/// string ptr.
9314 const TargetLowering &TLI,
9315 const ConstantDataArraySlice &Slice) {
9316 // Handle vector with all elements zero.
9317 if (Slice.Array == nullptr) {
9318 if (VT.isInteger())
9319 return DAG.getConstant(0, dl, VT);
9320 return DAG.getNode(ISD::BITCAST, dl, VT,
9321 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9322 }
9323
9324 assert(!VT.isVector() && "Can't handle vector type here!");
9325 unsigned NumVTBits = VT.getSizeInBits();
9326 unsigned NumVTBytes = NumVTBits / 8;
9327 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9328
9329 APInt Val(NumVTBits, 0);
9330 if (DAG.getDataLayout().isLittleEndian()) {
9331 for (unsigned i = 0; i != NumBytes; ++i)
9332 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9333 } else {
9334 for (unsigned i = 0; i != NumBytes; ++i)
9335 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9336 }
9337
9338 // If the "cost" of materializing the integer immediate is less than the cost
9339 // of a load, then it is cost effective to turn the load into the immediate.
9340 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9341 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9342 return DAG.getConstant(Val, dl, VT);
9343 return SDValue();
9344}
9345
9347 const SDLoc &DL,
9348 const SDNodeFlags Flags) {
9349 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9350 return getMemBasePlusOffset(Base, Index, DL, Flags);
9351}
9352
9354 const SDLoc &DL,
9355 const SDNodeFlags Flags) {
9356 assert(Offset.getValueType().isInteger());
9357 EVT BasePtrVT = Ptr.getValueType();
9358 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9359 BasePtrVT))
9360 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9361 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9362 SDNodeFlags AddFlags = Flags;
9363 AddFlags.setInBounds(false);
9364 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9365}
9366
9367/// Returns true if memcpy source is constant data.
9369 uint64_t SrcDelta = 0;
9370 GlobalAddressSDNode *G = nullptr;
9371 if (Src.getOpcode() == ISD::GlobalAddress)
9373 else if (Src->isAnyAdd() &&
9374 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9375 Src.getOperand(1).getOpcode() == ISD::Constant) {
9376 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9377 SrcDelta = Src.getConstantOperandVal(1);
9378 }
9379 if (!G)
9380 return false;
9381
9382 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9383 SrcDelta + G->getOffset());
9384}
9385
9387 SelectionDAG &DAG) {
9388 // On Darwin, -Os means optimize for size without hurting performance, so
9389 // only really optimize for size when -Oz (MinSize) is used.
9391 return MF.getFunction().hasMinSize();
9392 return DAG.shouldOptForSize();
9393}
9394
9396 SmallVector<SDValue, 32> &OutChains, unsigned From,
9397 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9398 SmallVector<SDValue, 16> &OutStoreChains) {
9399 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9400 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9401 SmallVector<SDValue, 16> GluedLoadChains;
9402 for (unsigned i = From; i < To; ++i) {
9403 OutChains.push_back(OutLoadChains[i]);
9404 GluedLoadChains.push_back(OutLoadChains[i]);
9405 }
9406
9407 // Chain for all loads.
9408 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9409 GluedLoadChains);
9410
9411 for (unsigned i = From; i < To; ++i) {
9412 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9413 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9414 ST->getBasePtr(), ST->getMemoryVT(),
9415 ST->getMemOperand());
9416 OutChains.push_back(NewStore);
9417 }
9418}
9419
9420static SDValue
9422 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9423 Align SrcAlign, bool isVol, bool AlwaysInline,
9424 MachinePointerInfo DstPtrInfo,
9425 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9426 BatchAAResults *BatchAA) {
9427 // Turn a memcpy of undef to nop.
9428 // FIXME: We need to honor volatile even is Src is undef.
9429 if (Src.isUndef())
9430 return Chain;
9431
9432 // Expand memcpy to a series of load and store ops if the size operand falls
9433 // below a certain threshold.
9434 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9435 // rather than maybe a humongous number of loads and stores.
9436 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9437 const DataLayout &DL = DAG.getDataLayout();
9438 LLVMContext &C = *DAG.getContext();
9439 std::vector<EVT> MemOps;
9440 bool DstAlignCanChange = false;
9442 MachineFrameInfo &MFI = MF.getFrameInfo();
9443 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9445 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9446 DstAlignCanChange = true;
9447 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9449 // If marked as volatile, perform a copy even when marked as constant.
9450 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9451 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9452 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9453 const MemOp Op = isZeroConstant
9454 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9455 /*IsZeroMemset*/ true, isVol)
9456 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9457 SrcAlign, isVol, CopyFromConstant);
9458 if (!TLI.findOptimalMemOpLowering(
9459 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9460 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9461 return SDValue();
9462
9463 if (DstAlignCanChange) {
9464 Type *Ty = MemOps[0].getTypeForEVT(C);
9465 Align NewDstAlign = DL.getABITypeAlign(Ty);
9466
9467 // Don't promote to an alignment that would require dynamic stack
9468 // realignment which may conflict with optimizations such as tail call
9469 // optimization.
9471 if (!TRI->hasStackRealignment(MF))
9472 if (MaybeAlign StackAlign = DL.getStackAlignment())
9473 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9474
9475 if (NewDstAlign > DstAlign) {
9476 // Give the stack frame object a larger alignment if needed.
9477 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9478 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9479 DstAlign = NewDstAlign;
9480 }
9481 }
9482
9483 // Prepare AAInfo for loads/stores after lowering this memcpy.
9484 AAMDNodes NewAAInfo = AAInfo;
9485 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9486
9487 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9488 bool isConstant =
9489 BatchAA && SrcVal &&
9490 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9491
9492 MachineMemOperand::Flags MMOFlags =
9494 SmallVector<SDValue, 16> OutLoadChains;
9495 SmallVector<SDValue, 16> OutStoreChains;
9496 SmallVector<SDValue, 32> OutChains;
9497 unsigned NumMemOps = MemOps.size();
9498 uint64_t SrcOff = 0, DstOff = 0;
9499 for (unsigned i = 0; i != NumMemOps; ++i) {
9500 EVT VT = MemOps[i];
9501 unsigned VTSize = VT.getSizeInBits() / 8;
9503
9504 if (VTSize > Size) {
9505 // Issuing an unaligned load / store pair that overlaps with the previous
9506 // pair. Adjust the offset accordingly.
9507 assert(i == NumMemOps-1 && i != 0);
9508 SrcOff -= VTSize - Size;
9509 DstOff -= VTSize - Size;
9510 }
9511
9512 if (CopyFromConstant &&
9513 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9514 // It's unlikely a store of a vector immediate can be done in a single
9515 // instruction. It would require a load from a constantpool first.
9516 // We only handle zero vectors here.
9517 // FIXME: Handle other cases where store of vector immediate is done in
9518 // a single instruction.
9519 ConstantDataArraySlice SubSlice;
9520 if (SrcOff < Slice.Length) {
9521 SubSlice = Slice;
9522 SubSlice.move(SrcOff);
9523 } else {
9524 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9525 SubSlice.Array = nullptr;
9526 SubSlice.Offset = 0;
9527 SubSlice.Length = VTSize;
9528 }
9529 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9530 if (Value.getNode()) {
9531 Store = DAG.getStore(
9532 Chain, dl, Value,
9533 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9534 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags, NewAAInfo);
9535 OutChains.push_back(Store);
9536 }
9537 }
9538
9539 if (!Store.getNode()) {
9540 // The type might not be legal for the target. This should only happen
9541 // if the type is smaller than a legal type, as on PPC, so the right
9542 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9543 // to Load/Store if NVT==VT.
9544 // FIXME does the case above also need this?
9545 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9546 assert(NVT.bitsGE(VT));
9547
9548 bool isDereferenceable =
9549 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9550 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9551 if (isDereferenceable)
9553 if (isConstant)
9554 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9555
9556 Value = DAG.getExtLoad(
9557 ISD::EXTLOAD, dl, NVT, Chain,
9558 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9559 SrcPtrInfo.getWithOffset(SrcOff), VT,
9560 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
9561 OutLoadChains.push_back(Value.getValue(1));
9562
9563 Store = DAG.getTruncStore(
9564 Chain, dl, Value,
9565 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9566 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags, NewAAInfo);
9567 OutStoreChains.push_back(Store);
9568 }
9569 SrcOff += VTSize;
9570 DstOff += VTSize;
9571 Size -= VTSize;
9572 }
9573
9574 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9576 unsigned NumLdStInMemcpy = OutStoreChains.size();
9577
9578 if (NumLdStInMemcpy) {
9579 // It may be that memcpy might be converted to memset if it's memcpy
9580 // of constants. In such a case, we won't have loads and stores, but
9581 // just stores. In the absence of loads, there is nothing to gang up.
9582 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9583 // If target does not care, just leave as it.
9584 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9585 OutChains.push_back(OutLoadChains[i]);
9586 OutChains.push_back(OutStoreChains[i]);
9587 }
9588 } else {
9589 // Ld/St less than/equal limit set by target.
9590 if (NumLdStInMemcpy <= GluedLdStLimit) {
9591 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9592 NumLdStInMemcpy, OutLoadChains,
9593 OutStoreChains);
9594 } else {
9595 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9596 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9597 unsigned GlueIter = 0;
9598
9599 // Residual ld/st.
9600 if (RemainingLdStInMemcpy) {
9602 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9603 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9604 }
9605
9606 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9607 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9608 GlueIter - GluedLdStLimit;
9609 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9610 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9611 OutLoadChains, OutStoreChains);
9612 GlueIter += GluedLdStLimit;
9613 }
9614 }
9615 }
9616 }
9617 return DAG.getTokenFactor(dl, OutChains);
9618}
9619
9621 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9622 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9623 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9624 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9625 // Turn a memmove of undef to nop.
9626 // FIXME: We need to honor volatile even is Src is undef.
9627 if (Src.isUndef())
9628 return Chain;
9629
9630 // Expand memmove to a series of load and store ops if the size operand falls
9631 // below a certain threshold.
9632 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9633 const DataLayout &DL = DAG.getDataLayout();
9634 LLVMContext &C = *DAG.getContext();
9635 std::vector<EVT> MemOps;
9636 bool DstAlignCanChange = false;
9638 MachineFrameInfo &MFI = MF.getFrameInfo();
9639 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9641 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9642 DstAlignCanChange = true;
9643 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9644 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9645 if (!TLI.findOptimalMemOpLowering(
9646 C, MemOps, Limit,
9647 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9648 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9649 MF.getFunction().getAttributes(), nullptr))
9650 return SDValue();
9651
9652 if (DstAlignCanChange) {
9653 Type *Ty = MemOps[0].getTypeForEVT(C);
9654 Align NewDstAlign = DL.getABITypeAlign(Ty);
9655
9656 // Don't promote to an alignment that would require dynamic stack
9657 // realignment which may conflict with optimizations such as tail call
9658 // optimization.
9660 if (!TRI->hasStackRealignment(MF))
9661 if (MaybeAlign StackAlign = DL.getStackAlignment())
9662 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9663
9664 if (NewDstAlign > DstAlign) {
9665 // Give the stack frame object a larger alignment if needed.
9666 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9667 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9668 DstAlign = NewDstAlign;
9669 }
9670 }
9671
9672 // Prepare AAInfo for loads/stores after lowering this memmove.
9673 AAMDNodes NewAAInfo = AAInfo;
9674 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9675
9676 MachineMemOperand::Flags MMOFlags =
9678 uint64_t SrcOff = 0;
9679 SmallVector<SDValue, 8> LoadValues;
9680 SmallVector<SDValue, 8> LoadChains;
9681 SmallVector<SDValue, 8> OutChains;
9682 unsigned NumMemOps = MemOps.size();
9683 for (unsigned i = 0; i < NumMemOps; i++) {
9684 EVT VT = MemOps[i];
9685 unsigned VTSize = VT.getSizeInBits() / 8;
9686 SDValue Value;
9687 bool IsOverlapping = false;
9688
9689 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9690 // Issuing an unaligned load / store pair that overlaps with the previous
9691 // pair. Adjust the offset accordingly.
9692 SrcOff = Size - VTSize;
9693 IsOverlapping = true;
9694 }
9695
9696 // Calculate the actual alignment at the current offset. The alignment at
9697 // SrcOff may be lower than the base alignment, especially when using
9698 // overlapping loads.
9699 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9700 if (IsOverlapping) {
9701 // Verify that the target allows misaligned memory accesses at the
9702 // adjusted offset when using overlapping loads.
9703 unsigned Fast;
9704 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9705 SrcAlignAtOffset, MMOFlags,
9706 &Fast) ||
9707 !Fast) {
9708 // This should have been caught by findOptimalMemOpLowering, but verify
9709 // here for safety.
9710 return SDValue();
9711 }
9712 }
9713
9714 bool isDereferenceable =
9715 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9716 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9717 if (isDereferenceable)
9719 Value =
9720 DAG.getLoad(VT, dl, Chain,
9721 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9722 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9723 SrcMMOFlags, NewAAInfo);
9724 LoadValues.push_back(Value);
9725 LoadChains.push_back(Value.getValue(1));
9726 SrcOff += VTSize;
9727 }
9728 Chain = DAG.getTokenFactor(dl, LoadChains);
9729 OutChains.clear();
9730 uint64_t DstOff = 0;
9731 for (unsigned i = 0; i < NumMemOps; i++) {
9732 EVT VT = MemOps[i];
9733 unsigned VTSize = VT.getSizeInBits() / 8;
9734 SDValue Store;
9735 bool IsOverlapping = false;
9736
9737 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9738 // Issuing an unaligned load / store pair that overlaps with the previous
9739 // pair. Adjust the offset accordingly.
9740 DstOff = Size - VTSize;
9741 IsOverlapping = true;
9742 }
9743
9744 // Calculate the actual alignment at the current offset. The alignment at
9745 // DstOff may be lower than the base alignment, especially when using
9746 // overlapping stores.
9747 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9748 if (IsOverlapping) {
9749 // Verify that the target allows misaligned memory accesses at the
9750 // adjusted offset when using overlapping stores.
9751 unsigned Fast;
9752 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9753 DstAlignAtOffset, MMOFlags,
9754 &Fast) ||
9755 !Fast) {
9756 // This should have been caught by findOptimalMemOpLowering, but verify
9757 // here for safety.
9758 return SDValue();
9759 }
9760 }
9761 Store = DAG.getStore(
9762 Chain, dl, LoadValues[i],
9763 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9764 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9765 NewAAInfo);
9766 OutChains.push_back(Store);
9767 DstOff += VTSize;
9768 }
9769
9770 return DAG.getTokenFactor(dl, OutChains);
9771}
9772
9773/// Lower the call to 'memset' intrinsic function into a series of store
9774/// operations.
9775///
9776/// \param DAG Selection DAG where lowered code is placed.
9777/// \param dl Link to corresponding IR location.
9778/// \param Chain Control flow dependency.
9779/// \param Dst Pointer to destination memory location.
9780/// \param Src Value of byte to write into the memory.
9781/// \param Size Number of bytes to write.
9782/// \param Alignment Alignment of the destination in bytes.
9783/// \param isVol True if destination is volatile.
9784/// \param AlwaysInline Makes sure no function call is generated.
9785/// \param DstPtrInfo IR information on the memory pointer.
9786/// \returns New head in the control flow, if lowering was successful, empty
9787/// SDValue otherwise.
9788///
9789/// The function tries to replace 'llvm.memset' intrinsic with several store
9790/// operations and value calculation code. This is usually profitable for small
9791/// memory size or when the semantic requires inlining.
9793 SDValue Chain, SDValue Dst, SDValue Src,
9794 uint64_t Size, Align Alignment, bool isVol,
9795 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9796 const AAMDNodes &AAInfo) {
9797 // Turn a memset of undef to nop.
9798 // FIXME: We need to honor volatile even is Src is undef.
9799 if (Src.isUndef())
9800 return Chain;
9801
9802 // Expand memset to a series of load/store ops if the size operand
9803 // falls below a certain threshold.
9804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9805 std::vector<EVT> MemOps;
9806 bool DstAlignCanChange = false;
9807 LLVMContext &C = *DAG.getContext();
9809 MachineFrameInfo &MFI = MF.getFrameInfo();
9810 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9812 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9813 DstAlignCanChange = true;
9814 bool IsZeroVal = isNullConstant(Src);
9815 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9816
9817 EVT LargestVT;
9818 if (!TLI.findOptimalMemOpLowering(
9819 C, MemOps, Limit,
9820 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9821 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
9822 &LargestVT))
9823 return SDValue();
9824
9825 if (DstAlignCanChange) {
9826 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9827 const DataLayout &DL = DAG.getDataLayout();
9828 Align NewAlign = DL.getABITypeAlign(Ty);
9829
9830 // Don't promote to an alignment that would require dynamic stack
9831 // realignment which may conflict with optimizations such as tail call
9832 // optimization.
9834 if (!TRI->hasStackRealignment(MF))
9835 if (MaybeAlign StackAlign = DL.getStackAlignment())
9836 NewAlign = std::min(NewAlign, *StackAlign);
9837
9838 if (NewAlign > Alignment) {
9839 // Give the stack frame object a larger alignment if needed.
9840 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9841 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9842 Alignment = NewAlign;
9843 }
9844 }
9845
9846 SmallVector<SDValue, 8> OutChains;
9847 uint64_t DstOff = 0;
9848 unsigned NumMemOps = MemOps.size();
9849
9850 // Find the largest store and generate the bit pattern for it.
9851 // If target didn't set LargestVT, compute it from MemOps.
9852 if (!LargestVT.isSimple()) {
9853 LargestVT = MemOps[0];
9854 for (unsigned i = 1; i < NumMemOps; i++)
9855 if (MemOps[i].bitsGT(LargestVT))
9856 LargestVT = MemOps[i];
9857 }
9858 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9859
9860 // Prepare AAInfo for loads/stores after lowering this memset.
9861 AAMDNodes NewAAInfo = AAInfo;
9862 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9863
9864 for (unsigned i = 0; i < NumMemOps; i++) {
9865 EVT VT = MemOps[i];
9866 unsigned VTSize = VT.getSizeInBits() / 8;
9867 // The target should specify store types that exactly cover the memset size
9868 // (with the last store potentially being oversized for overlapping stores).
9869 assert(Size > 0 && "Target specified more stores than needed in "
9870 "findOptimalMemOpLowering");
9871 if (VTSize > Size) {
9872 // Issuing an unaligned load / store pair that overlaps with the previous
9873 // pair. Adjust the offset accordingly.
9874 assert(i == NumMemOps-1 && i != 0);
9875 DstOff -= VTSize - Size;
9876 }
9877
9878 // If this store is smaller than the largest store see whether we can get
9879 // the smaller value for free with a truncate or extract vector element and
9880 // then store.
9881 SDValue Value = MemSetValue;
9882 if (VT.bitsLT(LargestVT)) {
9883 unsigned Index;
9884 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9885 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9886 if (!LargestVT.isVector() && !VT.isVector() &&
9887 TLI.isTruncateFree(LargestVT, VT))
9888 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9889 else if (LargestVT.isVector() && !VT.isVector() &&
9891 LargestVT.getTypeForEVT(*DAG.getContext()),
9892 VT.getSizeInBits(), Index) &&
9893 TLI.isTypeLegal(SVT) &&
9894 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9895 // Target which can combine store(extractelement VectorTy, Idx) can get
9896 // the smaller value for free.
9897 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9898 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9899 } else
9900 Value = getMemsetValue(Src, VT, DAG, dl);
9901 }
9902 assert(Value.getValueType() == VT && "Value with wrong type.");
9903 SDValue Store = DAG.getStore(
9904 Chain, dl, Value,
9905 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9906 DstPtrInfo.getWithOffset(DstOff), Alignment,
9908 NewAAInfo);
9909 OutChains.push_back(Store);
9910 DstOff += VT.getSizeInBits() / 8;
9911 // For oversized overlapping stores, only subtract the remaining bytes.
9912 // For normal stores, subtract the full store size.
9913 if (VTSize > Size) {
9914 Size = 0;
9915 } else {
9916 Size -= VTSize;
9917 }
9918 }
9919
9920 // After processing all stores, Size should be exactly 0. Any remaining bytes
9921 // indicate a bug in the target's findOptimalMemOpLowering implementation.
9922 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
9923 "stores that exactly cover the memset size");
9924
9925 return DAG.getTokenFactor(dl, OutChains);
9926}
9927
9929 unsigned AS) {
9930 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
9931 // pointer operands can be losslessly bitcasted to pointers of address space 0
9932 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
9933 report_fatal_error("cannot lower memory intrinsic in address space " +
9934 Twine(AS));
9935 }
9936}
9937
9939 const SelectionDAG *SelDAG,
9940 bool AllowReturnsFirstArg) {
9941 if (!CI || !CI->isTailCall())
9942 return false;
9943 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
9944 // helper symbol we lower to.
9945 return isInTailCallPosition(*CI, SelDAG->getTarget(),
9946 AllowReturnsFirstArg &&
9948}
9949
9950static std::pair<SDValue, SDValue>
9953 const CallInst *CI, RTLIB::Libcall Call,
9954 SelectionDAG *DAG, const TargetLowering *TLI) {
9955 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
9956
9957 if (LCImpl == RTLIB::Unsupported)
9958 return {};
9959
9961 bool IsTailCall =
9962 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true);
9963 SDValue Callee =
9964 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
9965
9966 CLI.setDebugLoc(dl)
9967 .setChain(Chain)
9969 CI->getType(), Callee, std::move(Args))
9970 .setTailCall(IsTailCall);
9971
9972 return TLI->LowerCallTo(CLI);
9973}
9974
9975std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
9976 const SDLoc &dl, SDValue S1,
9977 SDValue S2,
9978 const CallInst *CI) {
9980 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
9981 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
9982 RTLIB::STRCMP, this, TLI);
9983}
9984
9985std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
9986 const SDLoc &dl, SDValue S1,
9987 SDValue S2,
9988 const CallInst *CI) {
9990 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
9991 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
9992 RTLIB::STRSTR, this, TLI);
9993}
9994
9995std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
9996 const SDLoc &dl,
9997 SDValue Dst, SDValue Src,
9999 const CallInst *CI) {
10001
10003 {Dst, PT},
10004 {Src, PT},
10007 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10008 RTLIB::MEMCCPY, this, TLI);
10009}
10010
10011std::pair<SDValue, SDValue>
10013 SDValue Mem1, SDValue Size, const CallInst *CI) {
10016 {Mem0, PT},
10017 {Mem1, PT},
10019 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10020 RTLIB::MEMCMP, this, TLI);
10021}
10022
10023std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10024 const SDLoc &dl,
10025 SDValue Dst, SDValue Src,
10026 const CallInst *CI) {
10028 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10029 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10030 RTLIB::STRCPY, this, TLI);
10031}
10032
10033std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10034 const SDLoc &dl,
10035 SDValue Src,
10036 const CallInst *CI) {
10037 // Emit a library call.
10040 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10041 RTLIB::STRLEN, this, TLI);
10042}
10043
10045 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10046 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10047 const CallInst *CI, std::optional<bool> OverrideTailCall,
10048 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10049 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10050 // Check to see if we should lower the memcpy to loads and stores first.
10051 // For cases within the target-specified limits, this is the best choice.
10053 if (ConstantSize) {
10054 // Memcpy with size zero? Just return the original chain.
10055 if (ConstantSize->isZero())
10056 return Chain;
10057
10059 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10060 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA);
10061 if (Result.getNode())
10062 return Result;
10063 }
10064
10065 // Then check to see if we should lower the memcpy with target-specific
10066 // code. If the target chooses to do this, this is the next best.
10067 if (TSI) {
10068 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10069 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10070 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10071 if (Result.getNode())
10072 return Result;
10073 }
10074
10075 // If we really need inline code and the target declined to provide it,
10076 // use a (potentially long) sequence of loads and stores.
10077 if (AlwaysInline) {
10078 assert(ConstantSize && "AlwaysInline requires a constant size!");
10080 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10081 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA);
10082 }
10083
10086
10087 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10088 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10089 // respect volatile, so they may do things like read or write memory
10090 // beyond the given memory regions. But fixing this isn't easy, and most
10091 // people don't care.
10092
10093 // Emit a library call.
10096 Args.emplace_back(Dst, PtrTy);
10097 Args.emplace_back(Src, PtrTy);
10098 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10099 // FIXME: pass in SDLoc
10101 bool IsTailCall = false;
10102 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10103
10104 if (OverrideTailCall.has_value()) {
10105 IsTailCall = *OverrideTailCall;
10106 } else {
10107 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10108 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10109 }
10110
10111 CLI.setDebugLoc(dl)
10112 .setChain(Chain)
10113 .setLibCallee(
10114 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10115 Dst.getValueType().getTypeForEVT(*getContext()),
10116 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10117 std::move(Args))
10119 .setTailCall(IsTailCall);
10120
10121 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10122 return CallResult.second;
10123}
10124
10126 SDValue Dst, SDValue Src, SDValue Size,
10127 Type *SizeTy, unsigned ElemSz,
10128 bool isTailCall,
10129 MachinePointerInfo DstPtrInfo,
10130 MachinePointerInfo SrcPtrInfo) {
10131 // Emit a library call.
10134 Args.emplace_back(Dst, ArgTy);
10135 Args.emplace_back(Src, ArgTy);
10136 Args.emplace_back(Size, SizeTy);
10137
10138 RTLIB::Libcall LibraryCall =
10140 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10141 if (LibcallImpl == RTLIB::Unsupported)
10142 report_fatal_error("Unsupported element size");
10143
10145 CLI.setDebugLoc(dl)
10146 .setChain(Chain)
10147 .setLibCallee(
10148 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10150 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10151 std::move(Args))
10153 .setTailCall(isTailCall);
10154
10155 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10156 return CallResult.second;
10157}
10158
10160 SDValue Src, SDValue Size, Align DstAlign,
10161 Align SrcAlign, bool isVol, const CallInst *CI,
10162 std::optional<bool> OverrideTailCall,
10163 MachinePointerInfo DstPtrInfo,
10164 MachinePointerInfo SrcPtrInfo,
10165 const AAMDNodes &AAInfo,
10166 BatchAAResults *BatchAA) {
10167 // Check to see if we should lower the memmove to loads and stores first.
10168 // For cases within the target-specified limits, this is the best choice.
10170 if (ConstantSize) {
10171 // Memmove with size zero? Just return the original chain.
10172 if (ConstantSize->isZero())
10173 return Chain;
10174
10176 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10177 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10178 if (Result.getNode())
10179 return Result;
10180 }
10181
10182 // Then check to see if we should lower the memmove with target-specific
10183 // code. If the target chooses to do this, this is the next best.
10184 if (TSI) {
10185 SDValue Result = TSI->EmitTargetCodeForMemmove(
10186 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10187 SrcPtrInfo);
10188 if (Result.getNode())
10189 return Result;
10190 }
10191
10194
10195 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10196 // not be safe. See memcpy above for more details.
10197
10198 // Emit a library call.
10201 Args.emplace_back(Dst, PtrTy);
10202 Args.emplace_back(Src, PtrTy);
10203 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10204 // FIXME: pass in SDLoc
10206
10207 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10208
10209 bool IsTailCall = false;
10210 if (OverrideTailCall.has_value()) {
10211 IsTailCall = *OverrideTailCall;
10212 } else {
10213 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10214 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10215 }
10216
10217 CLI.setDebugLoc(dl)
10218 .setChain(Chain)
10219 .setLibCallee(
10220 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10221 Dst.getValueType().getTypeForEVT(*getContext()),
10222 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10223 std::move(Args))
10225 .setTailCall(IsTailCall);
10226
10227 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10228 return CallResult.second;
10229}
10230
10232 SDValue Dst, SDValue Src, SDValue Size,
10233 Type *SizeTy, unsigned ElemSz,
10234 bool isTailCall,
10235 MachinePointerInfo DstPtrInfo,
10236 MachinePointerInfo SrcPtrInfo) {
10237 // Emit a library call.
10240 Args.emplace_back(Dst, IntPtrTy);
10241 Args.emplace_back(Src, IntPtrTy);
10242 Args.emplace_back(Size, SizeTy);
10243
10244 RTLIB::Libcall LibraryCall =
10246 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10247 if (LibcallImpl == RTLIB::Unsupported)
10248 report_fatal_error("Unsupported element size");
10249
10251 CLI.setDebugLoc(dl)
10252 .setChain(Chain)
10253 .setLibCallee(
10254 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10256 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10257 std::move(Args))
10259 .setTailCall(isTailCall);
10260
10261 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10262 return CallResult.second;
10263}
10264
10266 SDValue Src, SDValue Size, Align Alignment,
10267 bool isVol, bool AlwaysInline,
10268 const CallInst *CI,
10269 MachinePointerInfo DstPtrInfo,
10270 const AAMDNodes &AAInfo) {
10271 // Check to see if we should lower the memset to stores first.
10272 // For cases within the target-specified limits, this is the best choice.
10274 if (ConstantSize) {
10275 // Memset with size zero? Just return the original chain.
10276 if (ConstantSize->isZero())
10277 return Chain;
10278
10279 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10280 ConstantSize->getZExtValue(), Alignment,
10281 isVol, false, DstPtrInfo, AAInfo);
10282
10283 if (Result.getNode())
10284 return Result;
10285 }
10286
10287 // Then check to see if we should lower the memset with target-specific
10288 // code. If the target chooses to do this, this is the next best.
10289 if (TSI) {
10290 SDValue Result = TSI->EmitTargetCodeForMemset(
10291 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10292 if (Result.getNode())
10293 return Result;
10294 }
10295
10296 // If we really need inline code and the target declined to provide it,
10297 // use a (potentially long) sequence of loads and stores.
10298 if (AlwaysInline) {
10299 assert(ConstantSize && "AlwaysInline requires a constant size!");
10300 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10301 ConstantSize->getZExtValue(), Alignment,
10302 isVol, true, DstPtrInfo, AAInfo);
10303 assert(Result &&
10304 "getMemsetStores must return a valid sequence when AlwaysInline");
10305 return Result;
10306 }
10307
10309
10310 // Emit a library call.
10311 auto &Ctx = *getContext();
10312 const auto& DL = getDataLayout();
10313
10315 // FIXME: pass in SDLoc
10316 CLI.setDebugLoc(dl).setChain(Chain);
10317
10318 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10319 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10320
10321 // If zeroing out and bzero is present, use it.
10322 if (UseBZero) {
10324 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10325 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10326 CLI.setLibCallee(
10327 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10328 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10329 } else {
10330 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10331
10333 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10334 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
10335 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10336 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10337 Dst.getValueType().getTypeForEVT(Ctx),
10338 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10339 std::move(Args));
10340 }
10341
10342 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10343 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10344
10345 // If we're going to use bzero, make sure not to tail call unless the
10346 // subsequent return doesn't need a value, as bzero doesn't return the first
10347 // arg unlike memset.
10348 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10349 bool IsTailCall =
10350 CI && CI->isTailCall() &&
10351 isInTailCallPosition(*CI, getTarget(), ReturnsFirstArg && LowersToMemset);
10352 CLI.setDiscardResult().setTailCall(IsTailCall);
10353
10354 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10355 return CallResult.second;
10356}
10357
10360 Type *SizeTy, unsigned ElemSz,
10361 bool isTailCall,
10362 MachinePointerInfo DstPtrInfo) {
10363 // Emit a library call.
10365 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10366 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
10367 Args.emplace_back(Size, SizeTy);
10368
10369 RTLIB::Libcall LibraryCall =
10371 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10372 if (LibcallImpl == RTLIB::Unsupported)
10373 report_fatal_error("Unsupported element size");
10374
10376 CLI.setDebugLoc(dl)
10377 .setChain(Chain)
10378 .setLibCallee(
10379 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10381 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10382 std::move(Args))
10384 .setTailCall(isTailCall);
10385
10386 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10387 return CallResult.second;
10388}
10389
10390SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10392 MachineMemOperand *MMO,
10393 ISD::LoadExtType ExtType) {
10395 AddNodeIDNode(ID, Opcode, VTList, Ops);
10396 ID.AddInteger(MemVT.getRawBits());
10397 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10398 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10399 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10400 ID.AddInteger(MMO->getFlags());
10401 void* IP = nullptr;
10402 if (auto *E = cast_or_null<AtomicSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10403 E->refineAlignment(MMO);
10404 E->refineRanges(MMO);
10405 return SDValue(E, 0);
10406 }
10407
10408 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10409 VTList, MemVT, MMO, ExtType);
10410 createOperands(N, Ops);
10411
10412 CSEMap.InsertNode(N, IP);
10413 InsertNode(N);
10414 SDValue V(N, 0);
10415 NewSDValueDbgMsg(V, "Creating new node: ", this);
10416 return V;
10417}
10418
10420 EVT MemVT, SDVTList VTs, SDValue Chain,
10421 SDValue Ptr, SDValue Cmp, SDValue Swp,
10422 MachineMemOperand *MMO) {
10423 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10425 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10426
10427 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10428 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10429}
10430
10431SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10432 SDValue Chain, SDValue Ptr, SDValue Val,
10433 MachineMemOperand *MMO) {
10434 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10435 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10436 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10437 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10438 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10439 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10440 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10441 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10442 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10443 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10444 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10445 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10446 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10447 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10448 Opcode == ISD::ATOMIC_STORE) &&
10449 "Invalid Atomic Op");
10450
10451 EVT VT = Val.getValueType();
10452
10453 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10454 getVTList(VT, MVT::Other);
10455 SDValue Ops[] = {Chain, Ptr, Val};
10456 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10457}
10458
10460 EVT MemVT, EVT VT, SDValue Chain,
10461 SDValue Ptr, MachineMemOperand *MMO) {
10462 SDVTList VTs = getVTList(VT, MVT::Other);
10463 SDValue Ops[] = {Chain, Ptr};
10464 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10465}
10466
10467/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10469 if (Ops.size() == 1)
10470 return Ops[0];
10471
10473 VTs.reserve(Ops.size());
10474 for (const SDValue &Op : Ops)
10475 VTs.push_back(Op.getValueType());
10476 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10477}
10478
10480 SDValue Chain, const SDLoc &dl) {
10481 SmallVector<SDValue, 4> RetValues;
10482 RetValues.reserve(ResultTypes.size());
10483 for (EVT VT : ResultTypes)
10484 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10485 return getMergeValues(RetValues, dl);
10486}
10487
10489 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10490 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10492 const AAMDNodes &AAInfo) {
10493 if (Size.hasValue() && !Size.getValue())
10495
10497 MachineMemOperand *MMO =
10498 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10499
10500 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10501}
10502
10504 SDVTList VTList,
10505 ArrayRef<SDValue> Ops, EVT MemVT,
10506 MachineMemOperand *MMO) {
10507 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10508}
10509
10511 SDVTList VTList,
10512 ArrayRef<SDValue> Ops, EVT MemVT,
10514 assert(!MMOs.empty() && "Must have at least one MMO");
10515 assert(
10516 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10517 Opcode == ISD::PREFETCH ||
10518 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10519 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10520 "Opcode is not a memory-accessing opcode!");
10521
10523 if (MMOs.size() == 1) {
10524 MemRefs = MMOs[0];
10525 } else {
10526 // Allocate: [size_t count][MMO*][MMO*]...
10527 size_t AllocSize =
10528 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10529 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10530 size_t *CountPtr = static_cast<size_t *>(Buffer);
10531 *CountPtr = MMOs.size();
10532 MachineMemOperand **Array =
10533 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10534 llvm::copy(MMOs, Array);
10535 MemRefs = Array;
10536 }
10537
10538 // Memoize the node unless it returns a glue result.
10540 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10542 AddNodeIDNode(ID, Opcode, VTList, Ops);
10543 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10544 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10545 ID.AddInteger(MemVT.getRawBits());
10546 for (const MachineMemOperand *MMO : MMOs) {
10547 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10548 ID.AddInteger(MMO->getFlags());
10549 }
10550 void *IP = nullptr;
10551 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10552 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10553 return SDValue(E, 0);
10554 }
10555
10556 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10557 VTList, MemVT, MemRefs);
10558 createOperands(N, Ops);
10559 CSEMap.InsertNode(N, IP);
10560 } else {
10561 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10562 VTList, MemVT, MemRefs);
10563 createOperands(N, Ops);
10564 }
10565 InsertNode(N);
10566 SDValue V(N, 0);
10567 NewSDValueDbgMsg(V, "Creating new node: ", this);
10568 return V;
10569}
10570
10572 SDValue Chain, int FrameIndex) {
10573 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10574 const auto VTs = getVTList(MVT::Other);
10575 SDValue Ops[2] = {
10576 Chain,
10577 getFrameIndex(FrameIndex,
10578 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10579 true)};
10580
10582 AddNodeIDNode(ID, Opcode, VTs, Ops);
10583 ID.AddInteger(FrameIndex);
10584 void *IP = nullptr;
10585 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10586 return SDValue(E, 0);
10587
10588 LifetimeSDNode *N =
10589 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10590 createOperands(N, Ops);
10591 CSEMap.InsertNode(N, IP);
10592 InsertNode(N);
10593 SDValue V(N, 0);
10594 NewSDValueDbgMsg(V, "Creating new node: ", this);
10595 return V;
10596}
10597
10599 uint64_t Guid, uint64_t Index,
10600 uint32_t Attr) {
10601 const unsigned Opcode = ISD::PSEUDO_PROBE;
10602 const auto VTs = getVTList(MVT::Other);
10603 SDValue Ops[] = {Chain};
10605 AddNodeIDNode(ID, Opcode, VTs, Ops);
10606 ID.AddInteger(Guid);
10607 ID.AddInteger(Index);
10608 void *IP = nullptr;
10609 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
10610 return SDValue(E, 0);
10611
10612 auto *N = newSDNode<PseudoProbeSDNode>(
10613 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10614 createOperands(N, Ops);
10615 CSEMap.InsertNode(N, IP);
10616 InsertNode(N);
10617 SDValue V(N, 0);
10618 NewSDValueDbgMsg(V, "Creating new node: ", this);
10619 return V;
10620}
10621
10622/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10623/// MachinePointerInfo record from it. This is particularly useful because the
10624/// code generator has many cases where it doesn't bother passing in a
10625/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10627 SelectionDAG &DAG, SDValue Ptr,
10628 int64_t Offset = 0) {
10629 // If this is FI+Offset, we can model it.
10630 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10632 FI->getIndex(), Offset);
10633
10634 // If this is (FI+Offset1)+Offset2, we can model it.
10635 if (Ptr.getOpcode() != ISD::ADD ||
10638 return Info;
10639
10640 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10642 DAG.getMachineFunction(), FI,
10643 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10644}
10645
10646/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10647/// MachinePointerInfo record from it. This is particularly useful because the
10648/// code generator has many cases where it doesn't bother passing in a
10649/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10651 SelectionDAG &DAG, SDValue Ptr,
10652 SDValue OffsetOp) {
10653 // If the 'Offset' value isn't a constant, we can't handle this.
10655 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10656 if (OffsetOp.isUndef())
10657 return InferPointerInfo(Info, DAG, Ptr);
10658 return Info;
10659}
10660
10662 EVT VT, const SDLoc &dl, SDValue Chain,
10663 SDValue Ptr, SDValue Offset,
10664 MachinePointerInfo PtrInfo, EVT MemVT,
10665 Align Alignment,
10666 MachineMemOperand::Flags MMOFlags,
10667 const AAMDNodes &AAInfo, const MDNode *Ranges) {
10668 assert(Chain.getValueType() == MVT::Other &&
10669 "Invalid chain type");
10670
10671 MMOFlags |= MachineMemOperand::MOLoad;
10672 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10673 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10674 // clients.
10675 if (PtrInfo.V.isNull())
10676 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10677
10678 TypeSize Size = MemVT.getStoreSize();
10680 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
10681 Alignment, AAInfo, Ranges);
10682 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10683}
10684
10686 EVT VT, const SDLoc &dl, SDValue Chain,
10687 SDValue Ptr, SDValue Offset, EVT MemVT,
10688 MachineMemOperand *MMO) {
10689 if (VT == MemVT) {
10690 ExtType = ISD::NON_EXTLOAD;
10691 } else if (ExtType == ISD::NON_EXTLOAD) {
10692 assert(VT == MemVT && "Non-extending load from different memory type!");
10693 } else {
10694 // Extending load.
10695 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10696 "Should only be an extending load, not truncating!");
10697 assert(VT.isInteger() == MemVT.isInteger() &&
10698 "Cannot convert from FP to Int or Int -> FP!");
10699 assert(VT.isVector() == MemVT.isVector() &&
10700 "Cannot use an ext load to convert to or from a vector!");
10701 assert((!VT.isVector() ||
10703 "Cannot use an ext load to change the number of vector elements!");
10704 }
10705
10706 assert((!MMO->getRanges() ||
10708 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10709 MemVT.isInteger())) &&
10710 "Range metadata and load type must match!");
10711
10712 bool Indexed = AM != ISD::UNINDEXED;
10713 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10714 "Unindexed load with an offset!");
10715
10716 SDVTList VTs = Indexed ?
10717 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10718 SDValue Ops[] = { Chain, Ptr, Offset };
10720 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
10721 ID.AddInteger(MemVT.getRawBits());
10722 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
10723 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
10724 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10725 ID.AddInteger(MMO->getFlags());
10726 void *IP = nullptr;
10727 if (auto *E = cast_or_null<LoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10728 E->refineAlignment(MMO);
10729 E->refineRanges(MMO);
10730 return SDValue(E, 0);
10731 }
10732 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10733 ExtType, MemVT, MMO);
10734 createOperands(N, Ops);
10735
10736 CSEMap.InsertNode(N, IP);
10737 InsertNode(N);
10738 SDValue V(N, 0);
10739 NewSDValueDbgMsg(V, "Creating new node: ", this);
10740 return V;
10741}
10742
10744 SDValue Ptr, MachinePointerInfo PtrInfo,
10745 MaybeAlign Alignment,
10746 MachineMemOperand::Flags MMOFlags,
10747 const AAMDNodes &AAInfo, const MDNode *Ranges) {
10749 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10750 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
10751}
10752
10754 SDValue Ptr, MachineMemOperand *MMO) {
10756 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10757 VT, MMO);
10758}
10759
10761 EVT VT, SDValue Chain, SDValue Ptr,
10762 MachinePointerInfo PtrInfo, EVT MemVT,
10763 MaybeAlign Alignment,
10764 MachineMemOperand::Flags MMOFlags,
10765 const AAMDNodes &AAInfo) {
10767 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
10768 MemVT, Alignment, MMOFlags, AAInfo);
10769}
10770
10772 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
10773 MachineMemOperand *MMO) {
10775 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
10776 MemVT, MMO);
10777}
10778
10782 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
10783 assert(LD->getOffset().getOpcode() == ISD::POISON &&
10784 "Load is already a indexed load!");
10785 // Don't propagate the invariant or dereferenceable flags.
10786 auto MMOFlags =
10787 LD->getMemOperand()->getFlags() &
10789 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
10790 LD->getChain(), Base, Offset, LD->getPointerInfo(),
10791 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
10792}
10793
10795 SDValue Ptr, MachinePointerInfo PtrInfo,
10796 Align Alignment,
10797 MachineMemOperand::Flags MMOFlags,
10798 const AAMDNodes &AAInfo) {
10799 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10800
10801 MMOFlags |= MachineMemOperand::MOStore;
10802 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10803
10804 if (PtrInfo.V.isNull())
10805 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10806
10809 MachineMemOperand *MMO =
10810 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
10811 return getStore(Chain, dl, Val, Ptr, MMO);
10812}
10813
10815 SDValue Ptr, MachineMemOperand *MMO) {
10817 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
10819}
10820
10822 SDValue Ptr, SDValue Offset, EVT SVT,
10824 bool IsTruncating) {
10825 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10826 EVT VT = Val.getValueType();
10827 if (VT == SVT) {
10828 IsTruncating = false;
10829 } else if (!IsTruncating) {
10830 assert(VT == SVT && "No-truncating store from different memory type!");
10831 } else {
10833 "Should only be a truncating store, not extending!");
10834 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10835 assert(VT.isVector() == SVT.isVector() &&
10836 "Cannot use trunc store to convert to or from a vector!");
10837 assert((!VT.isVector() ||
10839 "Cannot use trunc store to change the number of vector elements!");
10840 }
10841
10842 bool Indexed = AM != ISD::UNINDEXED;
10843 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10844 "Unindexed store with an offset!");
10845 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10846 : getVTList(MVT::Other);
10847 SDValue Ops[] = {Chain, Val, Ptr, Offset};
10849 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
10850 ID.AddInteger(SVT.getRawBits());
10851 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
10852 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
10853 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10854 ID.AddInteger(MMO->getFlags());
10855 void *IP = nullptr;
10856 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10857 cast<StoreSDNode>(E)->refineAlignment(MMO);
10858 return SDValue(E, 0);
10859 }
10860 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10861 IsTruncating, SVT, MMO);
10862 createOperands(N, Ops);
10863
10864 CSEMap.InsertNode(N, IP);
10865 InsertNode(N);
10866 SDValue V(N, 0);
10867 NewSDValueDbgMsg(V, "Creating new node: ", this);
10868 return V;
10869}
10870
10872 SDValue Ptr, SDValue Offset,
10873 MachinePointerInfo PtrInfo, EVT SVT,
10874 Align Alignment,
10875 MachineMemOperand::Flags MMOFlags,
10876 const AAMDNodes &AAInfo) {
10877 assert(Chain.getValueType() == MVT::Other &&
10878 "Invalid chain type");
10879
10880 MMOFlags |= MachineMemOperand::MOStore;
10881 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10882
10883 if (PtrInfo.V.isNull())
10884 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10885
10887 MachineMemOperand *MMO = MF.getMachineMemOperand(
10888 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
10889 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
10890}
10891
10893 SDValue Ptr, MachinePointerInfo PtrInfo,
10894 EVT SVT, Align Alignment,
10895 MachineMemOperand::Flags MMOFlags,
10896 const AAMDNodes &AAInfo) {
10897 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
10898 PtrInfo, SVT, Alignment, MMOFlags, AAInfo);
10899}
10900
10902 SDValue Ptr, SDValue Offset, EVT SVT,
10903 MachineMemOperand *MMO) {
10904 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
10905}
10906
10908 SDValue Ptr, EVT SVT,
10909 MachineMemOperand *MMO) {
10910 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
10911 ISD::UNINDEXED, true);
10912}
10913
10917 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
10918 assert(ST->getOffset().getOpcode() == ISD::POISON &&
10919 "Store is already a indexed store!");
10920 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10921 ST->getMemoryVT(), ST->getMemOperand(), AM,
10922 ST->isTruncatingStore());
10923}
10924
10926 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
10927 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
10928 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
10929 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
10930 const MDNode *Ranges, bool IsExpanding) {
10931 MMOFlags |= MachineMemOperand::MOLoad;
10932 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10933 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10934 // clients.
10935 if (PtrInfo.V.isNull())
10936 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10937
10938 TypeSize Size = MemVT.getStoreSize();
10940 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
10941 Alignment, AAInfo, Ranges);
10942 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
10943 MMO, IsExpanding);
10944}
10945
10947 ISD::LoadExtType ExtType, EVT VT,
10948 const SDLoc &dl, SDValue Chain, SDValue Ptr,
10949 SDValue Offset, SDValue Mask, SDValue EVL,
10950 EVT MemVT, MachineMemOperand *MMO,
10951 bool IsExpanding) {
10952 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10953 assert(Mask.getValueType().getVectorElementCount() ==
10954 VT.getVectorElementCount() &&
10955 "Vector width mismatch between mask and data");
10956
10957 bool Indexed = AM != ISD::UNINDEXED;
10958 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10959 "Unindexed load with an offset!");
10960
10961 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
10962 : getVTList(VT, MVT::Other);
10963 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
10965 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
10966 ID.AddInteger(MemVT.getRawBits());
10967 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
10968 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
10969 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10970 ID.AddInteger(MMO->getFlags());
10971 void *IP = nullptr;
10972 if (auto *E = cast_or_null<VPLoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10973 E->refineAlignment(MMO);
10974 E->refineRanges(MMO);
10975 return SDValue(E, 0);
10976 }
10977 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10978 ExtType, IsExpanding, MemVT, MMO);
10979 createOperands(N, Ops);
10980
10981 CSEMap.InsertNode(N, IP);
10982 InsertNode(N);
10983 SDValue V(N, 0);
10984 NewSDValueDbgMsg(V, "Creating new node: ", this);
10985 return V;
10986}
10987
10989 SDValue Ptr, SDValue Mask, SDValue EVL,
10990 MachinePointerInfo PtrInfo,
10991 MaybeAlign Alignment,
10992 MachineMemOperand::Flags MMOFlags,
10993 const AAMDNodes &AAInfo, const MDNode *Ranges,
10994 bool IsExpanding) {
10996 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10997 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
10998 IsExpanding);
10999}
11000
11002 SDValue Ptr, SDValue Mask, SDValue EVL,
11003 MachineMemOperand *MMO, bool IsExpanding) {
11005 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11006 Mask, EVL, VT, MMO, IsExpanding);
11007}
11008
11010 EVT VT, SDValue Chain, SDValue Ptr,
11011 SDValue Mask, SDValue EVL,
11012 MachinePointerInfo PtrInfo, EVT MemVT,
11013 MaybeAlign Alignment,
11014 MachineMemOperand::Flags MMOFlags,
11015 const AAMDNodes &AAInfo, bool IsExpanding) {
11017 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11018 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11019 IsExpanding);
11020}
11021
11023 EVT VT, SDValue Chain, SDValue Ptr,
11024 SDValue Mask, SDValue EVL, EVT MemVT,
11025 MachineMemOperand *MMO, bool IsExpanding) {
11027 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11028 EVL, MemVT, MMO, IsExpanding);
11029}
11030
11034 auto *LD = cast<VPLoadSDNode>(OrigLoad);
11035 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11036 "Load is already a indexed load!");
11037 // Don't propagate the invariant or dereferenceable flags.
11038 auto MMOFlags =
11039 LD->getMemOperand()->getFlags() &
11041 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
11042 LD->getChain(), Base, Offset, LD->getMask(),
11043 LD->getVectorLength(), LD->getPointerInfo(),
11044 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
11045 nullptr, LD->isExpandingLoad());
11046}
11047
11049 SDValue Ptr, SDValue Offset, SDValue Mask,
11050 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11051 ISD::MemIndexedMode AM, bool IsTruncating,
11052 bool IsCompressing) {
11053 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11054 assert(Mask.getValueType().getVectorElementCount() ==
11056 "Vector width mismatch between mask and data");
11057
11058 bool Indexed = AM != ISD::UNINDEXED;
11059 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11060 "Unindexed vp_store with an offset!");
11061 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11062 : getVTList(MVT::Other);
11063 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11065 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11066 ID.AddInteger(MemVT.getRawBits());
11067 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11068 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11069 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11070 ID.AddInteger(MMO->getFlags());
11071 void *IP = nullptr;
11072 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11073 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11074 return SDValue(E, 0);
11075 }
11076 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11077 IsTruncating, IsCompressing, MemVT, MMO);
11078 createOperands(N, Ops);
11079
11080 CSEMap.InsertNode(N, IP);
11081 InsertNode(N);
11082 SDValue V(N, 0);
11083 NewSDValueDbgMsg(V, "Creating new node: ", this);
11084 return V;
11085}
11086
11088 SDValue Val, SDValue Ptr, SDValue Mask,
11089 SDValue EVL, MachinePointerInfo PtrInfo,
11090 EVT SVT, Align Alignment,
11091 MachineMemOperand::Flags MMOFlags,
11092 const AAMDNodes &AAInfo,
11093 bool IsCompressing) {
11094 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11095
11096 MMOFlags |= MachineMemOperand::MOStore;
11097 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11098
11099 if (PtrInfo.V.isNull())
11100 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11101
11103 MachineMemOperand *MMO = MF.getMachineMemOperand(
11104 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11105 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11106 IsCompressing);
11107}
11108
11110 SDValue Val, SDValue Ptr, SDValue Mask,
11111 SDValue EVL, EVT SVT,
11112 MachineMemOperand *MMO,
11113 bool IsCompressing) {
11114 EVT VT = Val.getValueType();
11115
11116 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11117 if (VT == SVT)
11118 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11119 EVL, VT, MMO, ISD::UNINDEXED,
11120 /*IsTruncating*/ false, IsCompressing);
11121
11123 "Should only be a truncating store, not extending!");
11124 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11125 assert(VT.isVector() == SVT.isVector() &&
11126 "Cannot use trunc store to convert to or from a vector!");
11127 assert((!VT.isVector() ||
11129 "Cannot use trunc store to change the number of vector elements!");
11130
11131 SDVTList VTs = getVTList(MVT::Other);
11133 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11135 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11136 ID.AddInteger(SVT.getRawBits());
11137 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11138 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11139 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11140 ID.AddInteger(MMO->getFlags());
11141 void *IP = nullptr;
11142 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11143 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11144 return SDValue(E, 0);
11145 }
11146 auto *N =
11147 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11148 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11149 createOperands(N, Ops);
11150
11151 CSEMap.InsertNode(N, IP);
11152 InsertNode(N);
11153 SDValue V(N, 0);
11154 NewSDValueDbgMsg(V, "Creating new node: ", this);
11155 return V;
11156}
11157
11161 auto *ST = cast<VPStoreSDNode>(OrigStore);
11162 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11163 "Store is already an indexed store!");
11164 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
11165 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
11166 Offset, ST->getMask(), ST->getVectorLength()};
11168 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11169 ID.AddInteger(ST->getMemoryVT().getRawBits());
11170 ID.AddInteger(ST->getRawSubclassData());
11171 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
11172 ID.AddInteger(ST->getMemOperand()->getFlags());
11173 void *IP = nullptr;
11174 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11175 return SDValue(E, 0);
11176
11177 auto *N = newSDNode<VPStoreSDNode>(
11178 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
11179 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
11180 createOperands(N, Ops);
11181
11182 CSEMap.InsertNode(N, IP);
11183 InsertNode(N);
11184 SDValue V(N, 0);
11185 NewSDValueDbgMsg(V, "Creating new node: ", this);
11186 return V;
11187}
11188
11190 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11191 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11192 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11193 bool Indexed = AM != ISD::UNINDEXED;
11194 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11195 "Unindexed load with an offset!");
11196
11197 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11198 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11199 : getVTList(VT, MVT::Other);
11201 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11202 ID.AddInteger(VT.getRawBits());
11203 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11204 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11205 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11206
11207 void *IP = nullptr;
11208 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11209 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11210 return SDValue(E, 0);
11211 }
11212
11213 auto *N =
11214 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11215 ExtType, IsExpanding, MemVT, MMO);
11216 createOperands(N, Ops);
11217 CSEMap.InsertNode(N, IP);
11218 InsertNode(N);
11219 SDValue V(N, 0);
11220 NewSDValueDbgMsg(V, "Creating new node: ", this);
11221 return V;
11222}
11223
11225 SDValue Ptr, SDValue Stride,
11226 SDValue Mask, SDValue EVL,
11227 MachineMemOperand *MMO,
11228 bool IsExpanding) {
11230 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11231 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11232}
11233
11235 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11236 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11237 MachineMemOperand *MMO, bool IsExpanding) {
11239 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11240 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11241}
11242
11244 SDValue Val, SDValue Ptr,
11245 SDValue Offset, SDValue Stride,
11246 SDValue Mask, SDValue EVL, EVT MemVT,
11247 MachineMemOperand *MMO,
11249 bool IsTruncating, bool IsCompressing) {
11250 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11251 bool Indexed = AM != ISD::UNINDEXED;
11252 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11253 "Unindexed vp_store with an offset!");
11254 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11255 : getVTList(MVT::Other);
11256 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11258 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11259 ID.AddInteger(MemVT.getRawBits());
11260 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11261 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11262 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11263 void *IP = nullptr;
11264 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11265 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11266 return SDValue(E, 0);
11267 }
11268 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11269 VTs, AM, IsTruncating,
11270 IsCompressing, MemVT, MMO);
11271 createOperands(N, Ops);
11272
11273 CSEMap.InsertNode(N, IP);
11274 InsertNode(N);
11275 SDValue V(N, 0);
11276 NewSDValueDbgMsg(V, "Creating new node: ", this);
11277 return V;
11278}
11279
11281 SDValue Val, SDValue Ptr,
11282 SDValue Stride, SDValue Mask,
11283 SDValue EVL, EVT SVT,
11284 MachineMemOperand *MMO,
11285 bool IsCompressing) {
11286 EVT VT = Val.getValueType();
11287
11288 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11289 if (VT == SVT)
11290 return getStridedStoreVP(Chain, DL, Val, Ptr, getPOISON(Ptr.getValueType()),
11291 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
11292 /*IsTruncating*/ false, IsCompressing);
11293
11295 "Should only be a truncating store, not extending!");
11296 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11297 assert(VT.isVector() == SVT.isVector() &&
11298 "Cannot use trunc store to convert to or from a vector!");
11299 assert((!VT.isVector() ||
11301 "Cannot use trunc store to change the number of vector elements!");
11302
11303 SDVTList VTs = getVTList(MVT::Other);
11305 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
11307 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11308 ID.AddInteger(SVT.getRawBits());
11309 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11310 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11311 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11312 void *IP = nullptr;
11313 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11314 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11315 return SDValue(E, 0);
11316 }
11317 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11318 VTs, ISD::UNINDEXED, true,
11319 IsCompressing, SVT, MMO);
11320 createOperands(N, Ops);
11321
11322 CSEMap.InsertNode(N, IP);
11323 InsertNode(N);
11324 SDValue V(N, 0);
11325 NewSDValueDbgMsg(V, "Creating new node: ", this);
11326 return V;
11327}
11328
11331 ISD::MemIndexType IndexType) {
11332 assert(Ops.size() == 6 && "Incompatible number of operands");
11333
11335 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
11336 ID.AddInteger(VT.getRawBits());
11337 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11338 dl.getIROrder(), VTs, VT, MMO, IndexType));
11339 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11340 ID.AddInteger(MMO->getFlags());
11341 void *IP = nullptr;
11342 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11343 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11344 return SDValue(E, 0);
11345 }
11346
11347 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11348 VT, MMO, IndexType);
11349 createOperands(N, Ops);
11350
11351 assert(N->getMask().getValueType().getVectorElementCount() ==
11352 N->getValueType(0).getVectorElementCount() &&
11353 "Vector width mismatch between mask and data");
11354 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11355 N->getValueType(0).getVectorElementCount().isScalable() &&
11356 "Scalable flags of index and data do not match");
11358 N->getIndex().getValueType().getVectorElementCount(),
11359 N->getValueType(0).getVectorElementCount()) &&
11360 "Vector width mismatch between index and data");
11361 assert(isa<ConstantSDNode>(N->getScale()) &&
11362 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11363 "Scale should be a constant power of 2");
11364
11365 CSEMap.InsertNode(N, IP);
11366 InsertNode(N);
11367 SDValue V(N, 0);
11368 NewSDValueDbgMsg(V, "Creating new node: ", this);
11369 return V;
11370}
11371
11374 MachineMemOperand *MMO,
11375 ISD::MemIndexType IndexType) {
11376 assert(Ops.size() == 7 && "Incompatible number of operands");
11377
11379 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
11380 ID.AddInteger(VT.getRawBits());
11381 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11382 dl.getIROrder(), VTs, VT, MMO, IndexType));
11383 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11384 ID.AddInteger(MMO->getFlags());
11385 void *IP = nullptr;
11386 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11387 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11388 return SDValue(E, 0);
11389 }
11390 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11391 VT, MMO, IndexType);
11392 createOperands(N, Ops);
11393
11394 assert(N->getMask().getValueType().getVectorElementCount() ==
11395 N->getValue().getValueType().getVectorElementCount() &&
11396 "Vector width mismatch between mask and data");
11397 assert(
11398 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11399 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11400 "Scalable flags of index and data do not match");
11402 N->getIndex().getValueType().getVectorElementCount(),
11403 N->getValue().getValueType().getVectorElementCount()) &&
11404 "Vector width mismatch between index and data");
11405 assert(isa<ConstantSDNode>(N->getScale()) &&
11406 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11407 "Scale should be a constant power of 2");
11408
11409 CSEMap.InsertNode(N, IP);
11410 InsertNode(N);
11411 SDValue V(N, 0);
11412 NewSDValueDbgMsg(V, "Creating new node: ", this);
11413 return V;
11414}
11415
11418 SDValue PassThru, EVT MemVT,
11419 MachineMemOperand *MMO,
11421 ISD::LoadExtType ExtTy, bool isExpanding) {
11422 bool Indexed = AM != ISD::UNINDEXED;
11423 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11424 "Unindexed masked load with an offset!");
11425 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11426 : getVTList(VT, MVT::Other);
11427 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11429 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
11430 ID.AddInteger(MemVT.getRawBits());
11431 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11432 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11433 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11434 ID.AddInteger(MMO->getFlags());
11435 void *IP = nullptr;
11436 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11437 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11438 return SDValue(E, 0);
11439 }
11440 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11441 AM, ExtTy, isExpanding, MemVT, MMO);
11442 createOperands(N, Ops);
11443
11444 CSEMap.InsertNode(N, IP);
11445 InsertNode(N);
11446 SDValue V(N, 0);
11447 NewSDValueDbgMsg(V, "Creating new node: ", this);
11448 return V;
11449}
11450
11455 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11456 "Masked load is already a indexed load!");
11457 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11458 Offset, LD->getMask(), LD->getPassThru(),
11459 LD->getMemoryVT(), LD->getMemOperand(), AM,
11460 LD->getExtensionType(), LD->isExpandingLoad());
11461}
11462
11465 SDValue Mask, EVT MemVT,
11466 MachineMemOperand *MMO,
11467 ISD::MemIndexedMode AM, bool IsTruncating,
11468 bool IsCompressing) {
11469 assert(Chain.getValueType() == MVT::Other &&
11470 "Invalid chain type");
11471 bool Indexed = AM != ISD::UNINDEXED;
11472 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11473 "Unindexed masked store with an offset!");
11474 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11475 : getVTList(MVT::Other);
11476 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11478 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
11479 ID.AddInteger(MemVT.getRawBits());
11480 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11481 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11482 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11483 ID.AddInteger(MMO->getFlags());
11484 void *IP = nullptr;
11485 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11486 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11487 return SDValue(E, 0);
11488 }
11489 auto *N =
11490 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11491 IsTruncating, IsCompressing, MemVT, MMO);
11492 createOperands(N, Ops);
11493
11494 CSEMap.InsertNode(N, IP);
11495 InsertNode(N);
11496 SDValue V(N, 0);
11497 NewSDValueDbgMsg(V, "Creating new node: ", this);
11498 return V;
11499}
11500
11505 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11506 "Masked store is already a indexed store!");
11507 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11508 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11509 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11510}
11511
11514 MachineMemOperand *MMO,
11515 ISD::MemIndexType IndexType,
11516 ISD::LoadExtType ExtTy) {
11517 assert(Ops.size() == 6 && "Incompatible number of operands");
11518
11520 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
11521 ID.AddInteger(MemVT.getRawBits());
11522 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11523 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11524 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11525 ID.AddInteger(MMO->getFlags());
11526 void *IP = nullptr;
11527 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11528 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11529 return SDValue(E, 0);
11530 }
11531
11532 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11533 VTs, MemVT, MMO, IndexType, ExtTy);
11534 createOperands(N, Ops);
11535
11536 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11537 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11538 assert(N->getMask().getValueType().getVectorElementCount() ==
11539 N->getValueType(0).getVectorElementCount() &&
11540 "Vector width mismatch between mask and data");
11541 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11542 N->getValueType(0).getVectorElementCount().isScalable() &&
11543 "Scalable flags of index and data do not match");
11545 N->getIndex().getValueType().getVectorElementCount(),
11546 N->getValueType(0).getVectorElementCount()) &&
11547 "Vector width mismatch between index and data");
11548 assert(isa<ConstantSDNode>(N->getScale()) &&
11549 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11550 "Scale should be a constant power of 2");
11551
11552 CSEMap.InsertNode(N, IP);
11553 InsertNode(N);
11554 SDValue V(N, 0);
11555 NewSDValueDbgMsg(V, "Creating new node: ", this);
11556 return V;
11557}
11558
11561 MachineMemOperand *MMO,
11562 ISD::MemIndexType IndexType,
11563 bool IsTrunc) {
11564 assert(Ops.size() == 6 && "Incompatible number of operands");
11565
11567 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
11568 ID.AddInteger(MemVT.getRawBits());
11569 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11570 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11571 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11572 ID.AddInteger(MMO->getFlags());
11573 void *IP = nullptr;
11574 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11575 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11576 return SDValue(E, 0);
11577 }
11578
11579 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11580 VTs, MemVT, MMO, IndexType, IsTrunc);
11581 createOperands(N, Ops);
11582
11583 assert(N->getMask().getValueType().getVectorElementCount() ==
11584 N->getValue().getValueType().getVectorElementCount() &&
11585 "Vector width mismatch between mask and data");
11586 assert(
11587 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11588 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11589 "Scalable flags of index and data do not match");
11591 N->getIndex().getValueType().getVectorElementCount(),
11592 N->getValue().getValueType().getVectorElementCount()) &&
11593 "Vector width mismatch between index and data");
11594 assert(isa<ConstantSDNode>(N->getScale()) &&
11595 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11596 "Scale should be a constant power of 2");
11597
11598 CSEMap.InsertNode(N, IP);
11599 InsertNode(N);
11600 SDValue V(N, 0);
11601 NewSDValueDbgMsg(V, "Creating new node: ", this);
11602 return V;
11603}
11604
11606 const SDLoc &dl, ArrayRef<SDValue> Ops,
11607 MachineMemOperand *MMO,
11608 ISD::MemIndexType IndexType) {
11609 assert(Ops.size() == 7 && "Incompatible number of operands");
11610
11613 ID.AddInteger(MemVT.getRawBits());
11614 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11615 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11616 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11617 ID.AddInteger(MMO->getFlags());
11618 void *IP = nullptr;
11619 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11620 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11621 return SDValue(E, 0);
11622 }
11623
11624 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11625 VTs, MemVT, MMO, IndexType);
11626 createOperands(N, Ops);
11627
11628 assert(N->getMask().getValueType().getVectorElementCount() ==
11629 N->getIndex().getValueType().getVectorElementCount() &&
11630 "Vector width mismatch between mask and data");
11631 assert(isa<ConstantSDNode>(N->getScale()) &&
11632 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11633 "Scale should be a constant power of 2");
11634 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11635
11636 CSEMap.InsertNode(N, IP);
11637 InsertNode(N);
11638 SDValue V(N, 0);
11639 NewSDValueDbgMsg(V, "Creating new node: ", this);
11640 return V;
11641}
11642
11644 SDValue Ptr, SDValue Mask, SDValue EVL,
11645 MachineMemOperand *MMO) {
11646 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11647 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11649 AddNodeIDNode(ID, ISD::VP_LOAD_FF, VTs, Ops);
11650 ID.AddInteger(VT.getRawBits());
11651 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11652 VTs, VT, MMO));
11653 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11654 ID.AddInteger(MMO->getFlags());
11655 void *IP = nullptr;
11656 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11657 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11658 return SDValue(E, 0);
11659 }
11660 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11661 VT, MMO);
11662 createOperands(N, Ops);
11663
11664 CSEMap.InsertNode(N, IP);
11665 InsertNode(N);
11666 SDValue V(N, 0);
11667 NewSDValueDbgMsg(V, "Creating new node: ", this);
11668 return V;
11669}
11670
11672 EVT MemVT, MachineMemOperand *MMO) {
11673 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11674 SDVTList VTs = getVTList(MVT::Other);
11675 SDValue Ops[] = {Chain, Ptr};
11678 ID.AddInteger(MemVT.getRawBits());
11679 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11680 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11681 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11682 ID.AddInteger(MMO->getFlags());
11683 void *IP = nullptr;
11684 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11685 return SDValue(E, 0);
11686
11687 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11688 dl.getDebugLoc(), VTs, MemVT, MMO);
11689 createOperands(N, Ops);
11690
11691 CSEMap.InsertNode(N, IP);
11692 InsertNode(N);
11693 SDValue V(N, 0);
11694 NewSDValueDbgMsg(V, "Creating new node: ", this);
11695 return V;
11696}
11697
11699 EVT MemVT, MachineMemOperand *MMO) {
11700 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11701 SDVTList VTs = getVTList(MVT::Other);
11702 SDValue Ops[] = {Chain, Ptr};
11705 ID.AddInteger(MemVT.getRawBits());
11706 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11707 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11708 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11709 ID.AddInteger(MMO->getFlags());
11710 void *IP = nullptr;
11711 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11712 return SDValue(E, 0);
11713
11714 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11715 dl.getDebugLoc(), VTs, MemVT, MMO);
11716 createOperands(N, Ops);
11717
11718 CSEMap.InsertNode(N, IP);
11719 InsertNode(N);
11720 SDValue V(N, 0);
11721 NewSDValueDbgMsg(V, "Creating new node: ", this);
11722 return V;
11723}
11724
11726 // select undef, T, F --> T (if T is a constant), otherwise F
11727 // select, ?, undef, F --> F
11728 // select, ?, T, undef --> T
11729 if (Cond.isUndef())
11730 return isConstantValueOfAnyType(T) ? T : F;
11731 if (T.isUndef())
11733 if (F.isUndef())
11735
11736 // select true, T, F --> T
11737 // select false, T, F --> F
11738 if (auto C = isBoolConstant(Cond))
11739 return *C ? T : F;
11740
11741 // select ?, T, T --> T
11742 if (T == F)
11743 return T;
11744
11745 return SDValue();
11746}
11747
11749 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11750 if (X.isUndef())
11751 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11752 // shift X, undef --> undef (because it may shift by the bitwidth)
11753 if (Y.isUndef())
11754 return getUNDEF(X.getValueType());
11755
11756 // shift 0, Y --> 0
11757 // shift X, 0 --> X
11759 return X;
11760
11761 // shift X, C >= bitwidth(X) --> undef
11762 // All vector elements must be too big (or undef) to avoid partial undefs.
11763 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11764 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11765 };
11766 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11767 return getUNDEF(X.getValueType());
11768
11769 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11770 if (X.getValueType().getScalarType() == MVT::i1)
11771 return X;
11772
11773 return SDValue();
11774}
11775
11777 SDNodeFlags Flags) {
11778 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11779 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11780 // operation is poison. That result can be relaxed to undef.
11781 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11782 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11783 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11784 (YC && YC->getValueAPF().isNaN());
11785 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11786 (YC && YC->getValueAPF().isInfinity());
11787
11788 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11789 return getUNDEF(X.getValueType());
11790
11791 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11792 return getUNDEF(X.getValueType());
11793
11794 if (!YC)
11795 return SDValue();
11796
11797 // X + -0.0 --> X
11798 if (Opcode == ISD::FADD)
11799 if (YC->getValueAPF().isNegZero())
11800 return X;
11801
11802 // X - +0.0 --> X
11803 if (Opcode == ISD::FSUB)
11804 if (YC->getValueAPF().isPosZero())
11805 return X;
11806
11807 // X * 1.0 --> X
11808 // X / 1.0 --> X
11809 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11810 if (YC->getValueAPF().isOne())
11811 return X;
11812
11813 // X * 0.0 --> 0.0
11814 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11815 if (YC->getValueAPF().isZero())
11816 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11817
11818 return SDValue();
11819}
11820
11822 SDValue Ptr, SDValue SV, unsigned Align) {
11823 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11824 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11825}
11826
11827SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11829 switch (Ops.size()) {
11830 case 0: return getNode(Opcode, DL, VT);
11831 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
11832 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
11833 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
11834 default: break;
11835 }
11836
11837 // Copy from an SDUse array into an SDValue array for use with
11838 // the regular getNode logic.
11840 return getNode(Opcode, DL, VT, NewOps);
11841}
11842
11843SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11845 SDNodeFlags Flags;
11846 if (Inserter)
11847 Flags = Inserter->getFlags();
11848 return getNode(Opcode, DL, VT, Ops, Flags);
11849}
11850
11851SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11852 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11853 unsigned NumOps = Ops.size();
11854 switch (NumOps) {
11855 case 0: return getNode(Opcode, DL, VT);
11856 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
11857 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
11858 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
11859 default: break;
11860 }
11861
11862#ifndef NDEBUG
11863 for (const auto &Op : Ops)
11864 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11865 "Operand is DELETED_NODE!");
11866#endif
11867
11868 switch (Opcode) {
11869 default: break;
11870 case ISD::BUILD_VECTOR:
11871 // Attempt to simplify BUILD_VECTOR.
11872 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
11873 return V;
11874 break;
11876 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
11877 return V;
11878 break;
11879 case ISD::SELECT_CC:
11880 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
11881 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
11882 "LHS and RHS of condition must have same type!");
11883 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11884 "True and False arms of SelectCC must have same type!");
11885 assert(Ops[2].getValueType() == VT &&
11886 "select_cc node must be of same type as true and false value!");
11887 assert((!Ops[0].getValueType().isVector() ||
11888 Ops[0].getValueType().getVectorElementCount() ==
11889 VT.getVectorElementCount()) &&
11890 "Expected select_cc with vector result to have the same sized "
11891 "comparison type!");
11892 break;
11893 case ISD::BR_CC:
11894 assert(NumOps == 5 && "BR_CC takes 5 operands!");
11895 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11896 "LHS/RHS of comparison should match types!");
11897 break;
11898 case ISD::VP_ADD:
11899 case ISD::VP_SUB:
11900 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
11901 if (VT.getScalarType() == MVT::i1)
11902 Opcode = ISD::VP_XOR;
11903 break;
11904 case ISD::VP_MUL:
11905 // If it is VP_MUL mask operation then turn it to VP_AND
11906 if (VT.getScalarType() == MVT::i1)
11907 Opcode = ISD::VP_AND;
11908 break;
11909 case ISD::VP_REDUCE_MUL:
11910 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
11911 if (VT == MVT::i1)
11912 Opcode = ISD::VP_REDUCE_AND;
11913 break;
11914 case ISD::VP_REDUCE_ADD:
11915 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
11916 if (VT == MVT::i1)
11917 Opcode = ISD::VP_REDUCE_XOR;
11918 break;
11919 case ISD::VP_REDUCE_SMAX:
11920 case ISD::VP_REDUCE_UMIN:
11921 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
11922 // VP_REDUCE_AND.
11923 if (VT == MVT::i1)
11924 Opcode = ISD::VP_REDUCE_AND;
11925 break;
11926 case ISD::VP_REDUCE_SMIN:
11927 case ISD::VP_REDUCE_UMAX:
11928 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
11929 // VP_REDUCE_OR.
11930 if (VT == MVT::i1)
11931 Opcode = ISD::VP_REDUCE_OR;
11932 break;
11933 }
11934
11935 // Memoize nodes.
11936 SDNode *N;
11937 SDVTList VTs = getVTList(VT);
11938
11939 if (VT != MVT::Glue) {
11941 AddNodeIDNode(ID, Opcode, VTs, Ops);
11942 void *IP = nullptr;
11943
11944 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11945 E->intersectFlagsWith(Flags);
11946 return SDValue(E, 0);
11947 }
11948
11949 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11950 createOperands(N, Ops);
11951
11952 CSEMap.InsertNode(N, IP);
11953 } else {
11954 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11955 createOperands(N, Ops);
11956 }
11957
11958 N->setFlags(Flags);
11959 InsertNode(N);
11960 SDValue V(N, 0);
11961 NewSDValueDbgMsg(V, "Creating new node: ", this);
11962 return V;
11963}
11964
11965SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11966 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
11967 SDNodeFlags Flags;
11968 if (Inserter)
11969 Flags = Inserter->getFlags();
11970 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11971}
11972
11973SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11975 const SDNodeFlags Flags) {
11976 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11977}
11978
11979SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11981 SDNodeFlags Flags;
11982 if (Inserter)
11983 Flags = Inserter->getFlags();
11984 return getNode(Opcode, DL, VTList, Ops, Flags);
11985}
11986
11987SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11988 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11989 if (VTList.NumVTs == 1)
11990 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
11991
11992#ifndef NDEBUG
11993 for (const auto &Op : Ops)
11994 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11995 "Operand is DELETED_NODE!");
11996#endif
11997
11998 switch (Opcode) {
11999 case ISD::SADDO:
12000 case ISD::UADDO:
12001 case ISD::SSUBO:
12002 case ISD::USUBO: {
12003 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12004 "Invalid add/sub overflow op!");
12005 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12006 Ops[0].getValueType() == Ops[1].getValueType() &&
12007 Ops[0].getValueType() == VTList.VTs[0] &&
12008 "Binary operator types must match!");
12009 SDValue N1 = Ops[0], N2 = Ops[1];
12010 canonicalizeCommutativeBinop(Opcode, N1, N2);
12011
12012 // (X +- 0) -> X with zero-overflow.
12013 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12014 /*AllowTruncation*/ true);
12015 if (N2CV && N2CV->isZero()) {
12016 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12017 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12018 }
12019
12020 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12021 VTList.VTs[1].getScalarType() == MVT::i1) {
12022 SDValue F1 = getFreeze(N1);
12023 SDValue F2 = getFreeze(N2);
12024 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12025 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12026 return getNode(ISD::MERGE_VALUES, DL, VTList,
12027 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12028 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12029 Flags);
12030 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12031 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12032 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12033 return getNode(ISD::MERGE_VALUES, DL, VTList,
12034 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12035 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12036 Flags);
12037 }
12038 }
12039 break;
12040 }
12041 case ISD::SADDO_CARRY:
12042 case ISD::UADDO_CARRY:
12043 case ISD::SSUBO_CARRY:
12044 case ISD::USUBO_CARRY:
12045 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12046 "Invalid add/sub overflow op!");
12047 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12048 Ops[0].getValueType() == Ops[1].getValueType() &&
12049 Ops[0].getValueType() == VTList.VTs[0] &&
12050 Ops[2].getValueType() == VTList.VTs[1] &&
12051 "Binary operator types must match!");
12052 break;
12053 case ISD::SMUL_LOHI:
12054 case ISD::UMUL_LOHI: {
12055 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12056 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12057 VTList.VTs[0] == Ops[0].getValueType() &&
12058 VTList.VTs[0] == Ops[1].getValueType() &&
12059 "Binary operator types must match!");
12060 // Constant fold.
12063 if (LHS && RHS) {
12064 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12065 unsigned OutWidth = Width * 2;
12066 APInt Val = LHS->getAPIntValue();
12067 APInt Mul = RHS->getAPIntValue();
12068 if (Opcode == ISD::SMUL_LOHI) {
12069 Val = Val.sext(OutWidth);
12070 Mul = Mul.sext(OutWidth);
12071 } else {
12072 Val = Val.zext(OutWidth);
12073 Mul = Mul.zext(OutWidth);
12074 }
12075 Val *= Mul;
12076
12077 SDValue Hi =
12078 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12079 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12080 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12081 }
12082 break;
12083 }
12084 case ISD::FFREXP: {
12085 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12086 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12087 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12088
12090 int FrexpExp;
12091 APFloat FrexpMant =
12092 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12093 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12094 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12095 DL, VTList.VTs[1]);
12096 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12097 }
12098
12099 break;
12100 }
12102 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12103 "Invalid STRICT_FP_EXTEND!");
12104 assert(VTList.VTs[0].isFloatingPoint() &&
12105 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12106 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12107 "STRICT_FP_EXTEND result type should be vector iff the operand "
12108 "type is vector!");
12109 assert((!VTList.VTs[0].isVector() ||
12110 VTList.VTs[0].getVectorElementCount() ==
12111 Ops[1].getValueType().getVectorElementCount()) &&
12112 "Vector element count mismatch!");
12113 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12114 "Invalid fpext node, dst <= src!");
12115 break;
12117 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12118 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12119 "STRICT_FP_ROUND result type should be vector iff the operand "
12120 "type is vector!");
12121 assert((!VTList.VTs[0].isVector() ||
12122 VTList.VTs[0].getVectorElementCount() ==
12123 Ops[1].getValueType().getVectorElementCount()) &&
12124 "Vector element count mismatch!");
12125 assert(VTList.VTs[0].isFloatingPoint() &&
12126 Ops[1].getValueType().isFloatingPoint() &&
12127 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12128 Ops[2].getOpcode() == ISD::TargetConstant &&
12129 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12130 "Invalid STRICT_FP_ROUND!");
12131 break;
12132 }
12133
12134 // Memoize the node unless it returns a glue result.
12135 SDNode *N;
12136 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12138 AddNodeIDNode(ID, Opcode, VTList, Ops);
12139 void *IP = nullptr;
12140 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12141 E->intersectFlagsWith(Flags);
12142 return SDValue(E, 0);
12143 }
12144
12145 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12146 createOperands(N, Ops);
12147 CSEMap.InsertNode(N, IP);
12148 } else {
12149 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12150 createOperands(N, Ops);
12151 }
12152
12153 N->setFlags(Flags);
12154 InsertNode(N);
12155 SDValue V(N, 0);
12156 NewSDValueDbgMsg(V, "Creating new node: ", this);
12157 return V;
12158}
12159
12160SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12161 SDVTList VTList) {
12162 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12163}
12164
12165SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12166 SDValue N1) {
12167 SDValue Ops[] = { N1 };
12168 return getNode(Opcode, DL, VTList, Ops);
12169}
12170
12171SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12172 SDValue N1, SDValue N2) {
12173 SDValue Ops[] = { N1, N2 };
12174 return getNode(Opcode, DL, VTList, Ops);
12175}
12176
12177SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12178 SDValue N1, SDValue N2, SDValue N3) {
12179 SDValue Ops[] = { N1, N2, N3 };
12180 return getNode(Opcode, DL, VTList, Ops);
12181}
12182
12183SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12184 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12185 SDValue Ops[] = { N1, N2, N3, N4 };
12186 return getNode(Opcode, DL, VTList, Ops);
12187}
12188
12189SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12190 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12191 SDValue N5) {
12192 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12193 return getNode(Opcode, DL, VTList, Ops);
12194}
12195
12197 if (!VT.isExtended())
12198 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12199
12200 return makeVTList(&(*EVTs.insert(VT).first), 1);
12201}
12202
12205 ID.AddInteger(2U);
12206 ID.AddInteger(VT1.getRawBits());
12207 ID.AddInteger(VT2.getRawBits());
12208
12209 void *IP = nullptr;
12210 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12211 if (!Result) {
12212 EVT *Array = Allocator.Allocate<EVT>(2);
12213 Array[0] = VT1;
12214 Array[1] = VT2;
12215 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
12216 VTListMap.InsertNode(Result, IP);
12217 }
12218 return Result->getSDVTList();
12219}
12220
12223 ID.AddInteger(3U);
12224 ID.AddInteger(VT1.getRawBits());
12225 ID.AddInteger(VT2.getRawBits());
12226 ID.AddInteger(VT3.getRawBits());
12227
12228 void *IP = nullptr;
12229 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12230 if (!Result) {
12231 EVT *Array = Allocator.Allocate<EVT>(3);
12232 Array[0] = VT1;
12233 Array[1] = VT2;
12234 Array[2] = VT3;
12235 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
12236 VTListMap.InsertNode(Result, IP);
12237 }
12238 return Result->getSDVTList();
12239}
12240
12243 ID.AddInteger(4U);
12244 ID.AddInteger(VT1.getRawBits());
12245 ID.AddInteger(VT2.getRawBits());
12246 ID.AddInteger(VT3.getRawBits());
12247 ID.AddInteger(VT4.getRawBits());
12248
12249 void *IP = nullptr;
12250 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12251 if (!Result) {
12252 EVT *Array = Allocator.Allocate<EVT>(4);
12253 Array[0] = VT1;
12254 Array[1] = VT2;
12255 Array[2] = VT3;
12256 Array[3] = VT4;
12257 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
12258 VTListMap.InsertNode(Result, IP);
12259 }
12260 return Result->getSDVTList();
12261}
12262
12264 unsigned NumVTs = VTs.size();
12266 ID.AddInteger(NumVTs);
12267 for (unsigned index = 0; index < NumVTs; index++) {
12268 ID.AddInteger(VTs[index].getRawBits());
12269 }
12270
12271 void *IP = nullptr;
12272 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12273 if (!Result) {
12274 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
12275 llvm::copy(VTs, Array);
12276 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
12277 VTListMap.InsertNode(Result, IP);
12278 }
12279 return Result->getSDVTList();
12280}
12281
12282
12283/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12284/// specified operands. If the resultant node already exists in the DAG,
12285/// this does not modify the specified node, instead it returns the node that
12286/// already exists. If the resultant node does not exist in the DAG, the
12287/// input node is returned. As a degenerate case, if you specify the same
12288/// input operands as the node already has, the input node is returned.
12290 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12291
12292 // Check to see if there is no change.
12293 if (Op == N->getOperand(0)) return N;
12294
12295 // See if the modified node already exists.
12296 void *InsertPos = nullptr;
12297 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
12298 return Existing;
12299
12300 // Nope it doesn't. Remove the node from its current place in the maps.
12301 if (InsertPos)
12302 if (!RemoveNodeFromCSEMaps(N))
12303 InsertPos = nullptr;
12304
12305 // Now we update the operands.
12306 N->OperandList[0].set(Op);
12307
12309 // If this gets put into a CSE map, add it.
12310 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12311 return N;
12312}
12313
12315 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12316
12317 // Check to see if there is no change.
12318 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12319 return N; // No operands changed, just return the input node.
12320
12321 // See if the modified node already exists.
12322 void *InsertPos = nullptr;
12323 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
12324 return Existing;
12325
12326 // Nope it doesn't. Remove the node from its current place in the maps.
12327 if (InsertPos)
12328 if (!RemoveNodeFromCSEMaps(N))
12329 InsertPos = nullptr;
12330
12331 // Now we update the operands.
12332 if (N->OperandList[0] != Op1)
12333 N->OperandList[0].set(Op1);
12334 if (N->OperandList[1] != Op2)
12335 N->OperandList[1].set(Op2);
12336
12338 // If this gets put into a CSE map, add it.
12339 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12340 return N;
12341}
12342
12345 SDValue Ops[] = { Op1, Op2, Op3 };
12346 return UpdateNodeOperands(N, Ops);
12347}
12348
12351 SDValue Op3, SDValue Op4) {
12352 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12353 return UpdateNodeOperands(N, Ops);
12354}
12355
12358 SDValue Op3, SDValue Op4, SDValue Op5) {
12359 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12360 return UpdateNodeOperands(N, Ops);
12361}
12362
12365 unsigned NumOps = Ops.size();
12366 assert(N->getNumOperands() == NumOps &&
12367 "Update with wrong number of operands");
12368
12369 // If no operands changed just return the input node.
12370 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12371 return N;
12372
12373 // See if the modified node already exists.
12374 void *InsertPos = nullptr;
12375 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
12376 return Existing;
12377
12378 // Nope it doesn't. Remove the node from its current place in the maps.
12379 if (InsertPos)
12380 if (!RemoveNodeFromCSEMaps(N))
12381 InsertPos = nullptr;
12382
12383 // Now we update the operands.
12384 for (unsigned i = 0; i != NumOps; ++i)
12385 if (N->OperandList[i] != Ops[i])
12386 N->OperandList[i].set(Ops[i]);
12387
12389 // If this gets put into a CSE map, add it.
12390 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12391 return N;
12392}
12393
12394/// DropOperands - Release the operands and set this node to have
12395/// zero operands.
12397 // Unlike the code in MorphNodeTo that does this, we don't need to
12398 // watch for dead nodes here.
12399 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12400 SDUse &Use = *I++;
12401 Use.set(SDValue());
12402 }
12403}
12404
12406 ArrayRef<MachineMemOperand *> NewMemRefs) {
12407 if (NewMemRefs.empty()) {
12408 N->clearMemRefs();
12409 return;
12410 }
12411
12412 // Check if we can avoid allocating by storing a single reference directly.
12413 if (NewMemRefs.size() == 1) {
12414 N->MemRefs = NewMemRefs[0];
12415 N->NumMemRefs = 1;
12416 return;
12417 }
12418
12419 MachineMemOperand **MemRefsBuffer =
12420 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12421 llvm::copy(NewMemRefs, MemRefsBuffer);
12422 N->MemRefs = MemRefsBuffer;
12423 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12424}
12425
12426/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12427/// machine opcode.
12428///
12430 EVT VT) {
12431 SDVTList VTs = getVTList(VT);
12432 return SelectNodeTo(N, MachineOpc, VTs, {});
12433}
12434
12436 EVT VT, SDValue Op1) {
12437 SDVTList VTs = getVTList(VT);
12438 SDValue Ops[] = { Op1 };
12439 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12440}
12441
12443 EVT VT, SDValue Op1,
12444 SDValue Op2) {
12445 SDVTList VTs = getVTList(VT);
12446 SDValue Ops[] = { Op1, Op2 };
12447 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12448}
12449
12451 EVT VT, SDValue Op1,
12452 SDValue Op2, SDValue Op3) {
12453 SDVTList VTs = getVTList(VT);
12454 SDValue Ops[] = { Op1, Op2, Op3 };
12455 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12456}
12457
12460 SDVTList VTs = getVTList(VT);
12461 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12462}
12463
12465 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12466 SDVTList VTs = getVTList(VT1, VT2);
12467 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12468}
12469
12471 EVT VT1, EVT VT2) {
12472 SDVTList VTs = getVTList(VT1, VT2);
12473 return SelectNodeTo(N, MachineOpc, VTs, {});
12474}
12475
12477 EVT VT1, EVT VT2, EVT VT3,
12479 SDVTList VTs = getVTList(VT1, VT2, VT3);
12480 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12481}
12482
12484 EVT VT1, EVT VT2,
12485 SDValue Op1, SDValue Op2) {
12486 SDVTList VTs = getVTList(VT1, VT2);
12487 SDValue Ops[] = { Op1, Op2 };
12488 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12489}
12490
12493 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12494 // Reset the NodeID to -1.
12495 New->setNodeId(-1);
12496 if (New != N) {
12497 ReplaceAllUsesWith(N, New);
12499 }
12500 return New;
12501}
12502
12503/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12504/// the line number information on the merged node since it is not possible to
12505/// preserve the information that operation is associated with multiple lines.
12506/// This will make the debugger working better at -O0, were there is a higher
12507/// probability having other instructions associated with that line.
12508///
12509/// For IROrder, we keep the smaller of the two
12510SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12511 DebugLoc NLoc = N->getDebugLoc();
12512 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12513 N->setDebugLoc(DebugLoc());
12514 }
12515 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12516 N->setIROrder(Order);
12517 return N;
12518}
12519
12520/// MorphNodeTo - This *mutates* the specified node to have the specified
12521/// return type, opcode, and operands.
12522///
12523/// Note that MorphNodeTo returns the resultant node. If there is already a
12524/// node of the specified opcode and operands, it returns that node instead of
12525/// the current one. Note that the SDLoc need not be the same.
12526///
12527/// Using MorphNodeTo is faster than creating a new node and swapping it in
12528/// with ReplaceAllUsesWith both because it often avoids allocating a new
12529/// node, and because it doesn't require CSE recalculation for any of
12530/// the node's users.
12531///
12532/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12533/// As a consequence it isn't appropriate to use from within the DAG combiner or
12534/// the legalizer which maintain worklists that would need to be updated when
12535/// deleting things.
12538 // If an identical node already exists, use it.
12539 void *IP = nullptr;
12540 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12542 AddNodeIDNode(ID, Opc, VTs, Ops);
12543 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
12544 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12545 }
12546
12547 if (!RemoveNodeFromCSEMaps(N))
12548 IP = nullptr;
12549
12550 // Start the morphing.
12551 N->NodeType = Opc;
12552 N->ValueList = VTs.VTs;
12553 N->NumValues = VTs.NumVTs;
12554
12555 // Clear the operands list, updating used nodes to remove this from their
12556 // use list. Keep track of any operands that become dead as a result.
12557 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12558 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12559 SDUse &Use = *I++;
12560 SDNode *Used = Use.getNode();
12561 Use.set(SDValue());
12562 if (Used->use_empty())
12563 DeadNodeSet.insert(Used);
12564 }
12565
12566 // For MachineNode, initialize the memory references information.
12568 MN->clearMemRefs();
12569
12570 // Swap for an appropriately sized array from the recycler.
12571 removeOperands(N);
12572 createOperands(N, Ops);
12573
12574 // Delete any nodes that are still dead after adding the uses for the
12575 // new operands.
12576 if (!DeadNodeSet.empty()) {
12577 SmallVector<SDNode *, 16> DeadNodes;
12578 for (SDNode *N : DeadNodeSet)
12579 if (N->use_empty())
12580 DeadNodes.push_back(N);
12581 RemoveDeadNodes(DeadNodes);
12582 }
12583
12584 if (IP)
12585 CSEMap.InsertNode(N, IP); // Memoize the new node.
12586 return N;
12587}
12588
12590 unsigned OrigOpc = Node->getOpcode();
12591 unsigned NewOpc;
12592 switch (OrigOpc) {
12593 default:
12594 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12595#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12596 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12597#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12598 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12599#include "llvm/IR/ConstrainedOps.def"
12600 }
12601
12602 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12603
12604 // We're taking this node out of the chain, so we need to re-link things.
12605 SDValue InputChain = Node->getOperand(0);
12606 SDValue OutputChain = SDValue(Node, 1);
12607 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12608
12610 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12611 Ops.push_back(Node->getOperand(i));
12612
12613 SDVTList VTs = getVTList(Node->getValueType(0));
12614 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12615
12616 // MorphNodeTo can operate in two ways: if an existing node with the
12617 // specified operands exists, it can just return it. Otherwise, it
12618 // updates the node in place to have the requested operands.
12619 if (Res == Node) {
12620 // If we updated the node in place, reset the node ID. To the isel,
12621 // this should be just like a newly allocated machine node.
12622 Res->setNodeId(-1);
12623 } else {
12626 }
12627
12628 return Res;
12629}
12630
12631/// getMachineNode - These are used for target selectors to create a new node
12632/// with specified return type(s), MachineInstr opcode, and operands.
12633///
12634/// Note that getMachineNode returns the resultant node. If there is already a
12635/// node of the specified opcode and operands, it returns that node instead of
12636/// the current one.
12638 EVT VT) {
12639 SDVTList VTs = getVTList(VT);
12640 return getMachineNode(Opcode, dl, VTs, {});
12641}
12642
12644 EVT VT, SDValue Op1) {
12645 SDVTList VTs = getVTList(VT);
12646 SDValue Ops[] = { Op1 };
12647 return getMachineNode(Opcode, dl, VTs, Ops);
12648}
12649
12651 EVT VT, SDValue Op1, SDValue Op2) {
12652 SDVTList VTs = getVTList(VT);
12653 SDValue Ops[] = { Op1, Op2 };
12654 return getMachineNode(Opcode, dl, VTs, Ops);
12655}
12656
12658 EVT VT, SDValue Op1, SDValue Op2,
12659 SDValue Op3) {
12660 SDVTList VTs = getVTList(VT);
12661 SDValue Ops[] = { Op1, Op2, Op3 };
12662 return getMachineNode(Opcode, dl, VTs, Ops);
12663}
12664
12667 SDVTList VTs = getVTList(VT);
12668 return getMachineNode(Opcode, dl, VTs, Ops);
12669}
12670
12672 EVT VT1, EVT VT2, SDValue Op1,
12673 SDValue Op2) {
12674 SDVTList VTs = getVTList(VT1, VT2);
12675 SDValue Ops[] = { Op1, Op2 };
12676 return getMachineNode(Opcode, dl, VTs, Ops);
12677}
12678
12680 EVT VT1, EVT VT2, SDValue Op1,
12681 SDValue Op2, SDValue Op3) {
12682 SDVTList VTs = getVTList(VT1, VT2);
12683 SDValue Ops[] = { Op1, Op2, Op3 };
12684 return getMachineNode(Opcode, dl, VTs, Ops);
12685}
12686
12688 EVT VT1, EVT VT2,
12690 SDVTList VTs = getVTList(VT1, VT2);
12691 return getMachineNode(Opcode, dl, VTs, Ops);
12692}
12693
12695 EVT VT1, EVT VT2, EVT VT3,
12696 SDValue Op1, SDValue Op2) {
12697 SDVTList VTs = getVTList(VT1, VT2, VT3);
12698 SDValue Ops[] = { Op1, Op2 };
12699 return getMachineNode(Opcode, dl, VTs, Ops);
12700}
12701
12703 EVT VT1, EVT VT2, EVT VT3,
12704 SDValue Op1, SDValue Op2,
12705 SDValue Op3) {
12706 SDVTList VTs = getVTList(VT1, VT2, VT3);
12707 SDValue Ops[] = { Op1, Op2, Op3 };
12708 return getMachineNode(Opcode, dl, VTs, Ops);
12709}
12710
12712 EVT VT1, EVT VT2, EVT VT3,
12714 SDVTList VTs = getVTList(VT1, VT2, VT3);
12715 return getMachineNode(Opcode, dl, VTs, Ops);
12716}
12717
12719 ArrayRef<EVT> ResultTys,
12721 SDVTList VTs = getVTList(ResultTys);
12722 return getMachineNode(Opcode, dl, VTs, Ops);
12723}
12724
12726 SDVTList VTs,
12728 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12730 void *IP = nullptr;
12731
12732 if (DoCSE) {
12734 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
12735 IP = nullptr;
12736 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12737 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12738 }
12739 }
12740
12741 // Allocate a new MachineSDNode.
12742 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12743 createOperands(N, Ops);
12744
12745 if (DoCSE)
12746 CSEMap.InsertNode(N, IP);
12747
12748 InsertNode(N);
12749 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12750 return N;
12751}
12752
12753/// getTargetExtractSubreg - A convenience function for creating
12754/// TargetOpcode::EXTRACT_SUBREG nodes.
12756 SDValue Operand) {
12757 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12758 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12759 VT, Operand, SRIdxVal);
12760 return SDValue(Subreg, 0);
12761}
12762
12763/// getTargetInsertSubreg - A convenience function for creating
12764/// TargetOpcode::INSERT_SUBREG nodes.
12766 SDValue Operand, SDValue Subreg) {
12767 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12768 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12769 VT, Operand, Subreg, SRIdxVal);
12770 return SDValue(Result, 0);
12771}
12772
12773/// getNodeIfExists - Get the specified node if it's already available, or
12774/// else return NULL.
12777 bool AllowCommute) {
12778 SDNodeFlags Flags;
12779 if (Inserter)
12780 Flags = Inserter->getFlags();
12781 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12782}
12783
12786 const SDNodeFlags Flags,
12787 bool AllowCommute) {
12788 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12789 return nullptr;
12790
12791 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12793 AddNodeIDNode(ID, Opcode, VTList, LookupOps);
12794 void *IP = nullptr;
12795 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) {
12796 E->intersectFlagsWith(Flags);
12797 return E;
12798 }
12799 return nullptr;
12800 };
12801
12802 if (SDNode *Existing = Lookup(Ops))
12803 return Existing;
12804
12805 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12806 return Lookup({Ops[1], Ops[0]});
12807
12808 return nullptr;
12809}
12810
12811/// doesNodeExist - Check if a node exists without modifying its flags.
12812bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12814 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12816 AddNodeIDNode(ID, Opcode, VTList, Ops);
12817 void *IP = nullptr;
12818 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
12819 return true;
12820 }
12821 return false;
12822}
12823
12824/// getDbgValue - Creates a SDDbgValue node.
12825///
12826/// SDNode
12828 SDNode *N, unsigned R, bool IsIndirect,
12829 const DebugLoc &DL, unsigned O) {
12830 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12831 "Expected inlined-at fields to agree");
12832 return new (DbgInfo->getAlloc())
12833 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12834 {}, IsIndirect, DL, O,
12835 /*IsVariadic=*/false);
12836}
12837
12838/// Constant
12840 DIExpression *Expr,
12841 const Value *C,
12842 const DebugLoc &DL, unsigned O) {
12843 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12844 "Expected inlined-at fields to agree");
12845 return new (DbgInfo->getAlloc())
12846 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12847 /*IsIndirect=*/false, DL, O,
12848 /*IsVariadic=*/false);
12849}
12850
12851/// FrameIndex
12853 DIExpression *Expr, unsigned FI,
12854 bool IsIndirect,
12855 const DebugLoc &DL,
12856 unsigned O) {
12857 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12858 "Expected inlined-at fields to agree");
12859 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12860}
12861
12862/// FrameIndex with dependencies
12864 DIExpression *Expr, unsigned FI,
12865 ArrayRef<SDNode *> Dependencies,
12866 bool IsIndirect,
12867 const DebugLoc &DL,
12868 unsigned O) {
12869 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12870 "Expected inlined-at fields to agree");
12871 return new (DbgInfo->getAlloc())
12872 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
12873 Dependencies, IsIndirect, DL, O,
12874 /*IsVariadic=*/false);
12875}
12876
12877/// VReg
12879 Register VReg, bool IsIndirect,
12880 const DebugLoc &DL, unsigned O) {
12881 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12882 "Expected inlined-at fields to agree");
12883 return new (DbgInfo->getAlloc())
12884 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
12885 {}, IsIndirect, DL, O,
12886 /*IsVariadic=*/false);
12887}
12888
12891 ArrayRef<SDNode *> Dependencies,
12892 bool IsIndirect, const DebugLoc &DL,
12893 unsigned O, bool IsVariadic) {
12894 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12895 "Expected inlined-at fields to agree");
12896 return new (DbgInfo->getAlloc())
12897 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
12898 DL, O, IsVariadic);
12899}
12900
12902 unsigned OffsetInBits, unsigned SizeInBits,
12903 bool InvalidateDbg) {
12904 SDNode *FromNode = From.getNode();
12905 SDNode *ToNode = To.getNode();
12906 assert(FromNode && ToNode && "Can't modify dbg values");
12907
12908 // PR35338
12909 // TODO: assert(From != To && "Redundant dbg value transfer");
12910 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
12911 if (From == To || FromNode == ToNode)
12912 return;
12913
12914 if (!FromNode->getHasDebugValue())
12915 return;
12916
12917 SDDbgOperand FromLocOp =
12918 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
12920
12922 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
12923 if (Dbg->isInvalidated())
12924 continue;
12925
12926 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
12927
12928 // Create a new location ops vector that is equal to the old vector, but
12929 // with each instance of FromLocOp replaced with ToLocOp.
12930 bool Changed = false;
12931 auto NewLocOps = Dbg->copyLocationOps();
12932 std::replace_if(
12933 NewLocOps.begin(), NewLocOps.end(),
12934 [&Changed, FromLocOp](const SDDbgOperand &Op) {
12935 bool Match = Op == FromLocOp;
12936 Changed |= Match;
12937 return Match;
12938 },
12939 ToLocOp);
12940 // Ignore this SDDbgValue if we didn't find a matching location.
12941 if (!Changed)
12942 continue;
12943
12944 DIVariable *Var = Dbg->getVariable();
12945 auto *Expr = Dbg->getExpression();
12946 // If a fragment is requested, update the expression.
12947 if (SizeInBits) {
12948 // When splitting a larger (e.g., sign-extended) value whose
12949 // lower bits are described with an SDDbgValue, do not attempt
12950 // to transfer the SDDbgValue to the upper bits.
12951 if (auto FI = Expr->getFragmentInfo())
12952 if (OffsetInBits + SizeInBits > FI->SizeInBits)
12953 continue;
12954 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
12955 SizeInBits);
12956 if (!Fragment)
12957 continue;
12958 Expr = *Fragment;
12959 }
12960
12961 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
12962 // Clone the SDDbgValue and move it to To.
12963 SDDbgValue *Clone = getDbgValueList(
12964 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
12965 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
12966 Dbg->isVariadic());
12967 ClonedDVs.push_back(Clone);
12968
12969 if (InvalidateDbg) {
12970 // Invalidate value and indicate the SDDbgValue should not be emitted.
12971 Dbg->setIsInvalidated();
12972 Dbg->setIsEmitted();
12973 }
12974 }
12975
12976 for (SDDbgValue *Dbg : ClonedDVs) {
12977 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
12978 "Transferred DbgValues should depend on the new SDNode");
12979 AddDbgValue(Dbg, false);
12980 }
12981}
12982
12984 if (!N.getHasDebugValue())
12985 return;
12986
12987 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
12988 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
12989 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
12990 return SDDbgOperand::fromNode(Node, ResNo);
12991 };
12992
12994 for (auto *DV : GetDbgValues(&N)) {
12995 if (DV->isInvalidated())
12996 continue;
12997 switch (N.getOpcode()) {
12998 default:
12999 break;
13000 case ISD::ADD: {
13001 SDValue N0 = N.getOperand(0);
13002 SDValue N1 = N.getOperand(1);
13003 if (!isa<ConstantSDNode>(N0)) {
13004 bool RHSConstant = isa<ConstantSDNode>(N1);
13006 if (RHSConstant)
13007 Offset = N.getConstantOperandVal(1);
13008 // We are not allowed to turn indirect debug values variadic, so
13009 // don't salvage those.
13010 if (!RHSConstant && DV->isIndirect())
13011 continue;
13012
13013 // Rewrite an ADD constant node into a DIExpression. Since we are
13014 // performing arithmetic to compute the variable's *value* in the
13015 // DIExpression, we need to mark the expression with a
13016 // DW_OP_stack_value.
13017 auto *DIExpr = DV->getExpression();
13018 auto NewLocOps = DV->copyLocationOps();
13019 bool Changed = false;
13020 size_t OrigLocOpsSize = NewLocOps.size();
13021 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13022 // We're not given a ResNo to compare against because the whole
13023 // node is going away. We know that any ISD::ADD only has one
13024 // result, so we can assume any node match is using the result.
13025 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13026 NewLocOps[i].getSDNode() != &N)
13027 continue;
13028 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13029 if (RHSConstant) {
13032 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13033 } else {
13034 // Convert to a variadic expression (if not already).
13035 // convertToVariadicExpression() returns a const pointer, so we use
13036 // a temporary const variable here.
13037 const auto *TmpDIExpr =
13041 ExprOps.push_back(NewLocOps.size());
13042 ExprOps.push_back(dwarf::DW_OP_plus);
13043 SDDbgOperand RHS =
13045 NewLocOps.push_back(RHS);
13046 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13047 }
13048 Changed = true;
13049 }
13050 (void)Changed;
13051 assert(Changed && "Salvage target doesn't use N");
13052
13053 bool IsVariadic =
13054 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13055
13056 auto AdditionalDependencies = DV->getAdditionalDependencies();
13057 SDDbgValue *Clone = getDbgValueList(
13058 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13059 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13060 ClonedDVs.push_back(Clone);
13061 DV->setIsInvalidated();
13062 DV->setIsEmitted();
13063 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13064 N0.getNode()->dumprFull(this);
13065 dbgs() << " into " << *DIExpr << '\n');
13066 }
13067 break;
13068 }
13069 case ISD::TRUNCATE: {
13070 SDValue N0 = N.getOperand(0);
13071 TypeSize FromSize = N0.getValueSizeInBits();
13072 TypeSize ToSize = N.getValueSizeInBits(0);
13073
13074 DIExpression *DbgExpression = DV->getExpression();
13075 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13076 auto NewLocOps = DV->copyLocationOps();
13077 bool Changed = false;
13078 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13079 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13080 NewLocOps[i].getSDNode() != &N)
13081 continue;
13082
13083 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13084 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13085 Changed = true;
13086 }
13087 assert(Changed && "Salvage target doesn't use N");
13088 (void)Changed;
13089
13090 SDDbgValue *Clone =
13091 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13092 DV->getAdditionalDependencies(), DV->isIndirect(),
13093 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13094
13095 ClonedDVs.push_back(Clone);
13096 DV->setIsInvalidated();
13097 DV->setIsEmitted();
13098 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13099 dbgs() << " into " << *DbgExpression << '\n');
13100 break;
13101 }
13102 }
13103 }
13104
13105 for (SDDbgValue *Dbg : ClonedDVs) {
13106 assert((!Dbg->getSDNodes().empty() ||
13107 llvm::any_of(Dbg->getLocationOps(),
13108 [&](const SDDbgOperand &Op) {
13109 return Op.getKind() == SDDbgOperand::FRAMEIX;
13110 })) &&
13111 "Salvaged DbgValue should depend on a new SDNode");
13112 AddDbgValue(Dbg, false);
13113 }
13114}
13115
13116/// Creates a SDDbgLabel node.
13118 const DebugLoc &DL, unsigned O) {
13119 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13120 "Expected inlined-at fields to agree");
13121 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13122}
13123
13124namespace {
13125
13126/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13127/// pointed to by a use iterator is deleted, increment the use iterator
13128/// so that it doesn't dangle.
13129///
13130class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13133
13134 void NodeDeleted(SDNode *N, SDNode *E) override {
13135 // Increment the iterator as needed.
13136 while (UI != UE && N == UI->getUser())
13137 ++UI;
13138 }
13139
13140public:
13141 RAUWUpdateListener(SelectionDAG &d,
13144 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13145};
13146
13147} // end anonymous namespace
13148
13149/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13150/// This can cause recursive merging of nodes in the DAG.
13151///
13152/// This version assumes From has a single result value.
13153///
13155 SDNode *From = FromN.getNode();
13156 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13157 "Cannot replace with this method!");
13158 assert(From != To.getNode() && "Cannot replace uses of with self");
13159
13160 // Preserve Debug Values
13161 transferDbgValues(FromN, To);
13162 // Preserve extra info.
13163 copyExtraInfo(From, To.getNode());
13164
13165 // Iterate over all the existing uses of From. New uses will be added
13166 // to the beginning of the use list, which we avoid visiting.
13167 // This specifically avoids visiting uses of From that arise while the
13168 // replacement is happening, because any such uses would be the result
13169 // of CSE: If an existing node looks like From after one of its operands
13170 // is replaced by To, we don't want to replace of all its users with To
13171 // too. See PR3018 for more info.
13172 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13173 RAUWUpdateListener Listener(*this, UI, UE);
13174 while (UI != UE) {
13175 SDNode *User = UI->getUser();
13176
13177 // This node is about to morph, remove its old self from the CSE maps.
13178 RemoveNodeFromCSEMaps(User);
13179
13180 // A user can appear in a use list multiple times, and when this
13181 // happens the uses are usually next to each other in the list.
13182 // To help reduce the number of CSE recomputations, process all
13183 // the uses of this user that we can find this way.
13184 do {
13185 SDUse &Use = *UI;
13186 ++UI;
13187 Use.set(To);
13188 if (To->isDivergent() != From->isDivergent())
13190 } while (UI != UE && UI->getUser() == User);
13191 // Now that we have modified User, add it back to the CSE maps. If it
13192 // already exists there, recursively merge the results together.
13193 AddModifiedNodeToCSEMaps(User);
13194 }
13195
13196 // If we just RAUW'd the root, take note.
13197 if (FromN == getRoot())
13198 setRoot(To);
13199}
13200
13201/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13202/// This can cause recursive merging of nodes in the DAG.
13203///
13204/// This version assumes that for each value of From, there is a
13205/// corresponding value in To in the same position with the same type.
13206///
13208#ifndef NDEBUG
13209 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13210 assert((!From->hasAnyUseOfValue(i) ||
13211 From->getValueType(i) == To->getValueType(i)) &&
13212 "Cannot use this version of ReplaceAllUsesWith!");
13213#endif
13214
13215 // Handle the trivial case.
13216 if (From == To)
13217 return;
13218
13219 // Preserve Debug Info. Only do this if there's a use.
13220 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13221 if (From->hasAnyUseOfValue(i)) {
13222 assert((i < To->getNumValues()) && "Invalid To location");
13223 transferDbgValues(SDValue(From, i), SDValue(To, i));
13224 }
13225 // Preserve extra info.
13226 copyExtraInfo(From, To);
13227
13228 // Iterate over just the existing users of From. See the comments in
13229 // the ReplaceAllUsesWith above.
13230 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13231 RAUWUpdateListener Listener(*this, UI, UE);
13232 while (UI != UE) {
13233 SDNode *User = UI->getUser();
13234
13235 // This node is about to morph, remove its old self from the CSE maps.
13236 RemoveNodeFromCSEMaps(User);
13237
13238 // A user can appear in a use list multiple times, and when this
13239 // happens the uses are usually next to each other in the list.
13240 // To help reduce the number of CSE recomputations, process all
13241 // the uses of this user that we can find this way.
13242 do {
13243 SDUse &Use = *UI;
13244 ++UI;
13245 Use.setNode(To);
13246 if (To->isDivergent() != From->isDivergent())
13248 } while (UI != UE && UI->getUser() == User);
13249
13250 // Now that we have modified User, add it back to the CSE maps. If it
13251 // already exists there, recursively merge the results together.
13252 AddModifiedNodeToCSEMaps(User);
13253 }
13254
13255 // If we just RAUW'd the root, take note.
13256 if (From == getRoot().getNode())
13257 setRoot(SDValue(To, getRoot().getResNo()));
13258}
13259
13260/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13261/// This can cause recursive merging of nodes in the DAG.
13262///
13263/// This version can replace From with any result values. To must match the
13264/// number and types of values returned by From.
13266 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13267 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13268
13269 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13270 // Preserve Debug Info.
13271 transferDbgValues(SDValue(From, i), To[i]);
13272 // Preserve extra info.
13273 copyExtraInfo(From, To[i].getNode());
13274 }
13275
13276 // Iterate over just the existing users of From. See the comments in
13277 // the ReplaceAllUsesWith above.
13278 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13279 RAUWUpdateListener Listener(*this, UI, UE);
13280 while (UI != UE) {
13281 SDNode *User = UI->getUser();
13282
13283 // This node is about to morph, remove its old self from the CSE maps.
13284 RemoveNodeFromCSEMaps(User);
13285
13286 // A user can appear in a use list multiple times, and when this happens the
13287 // uses are usually next to each other in the list. To help reduce the
13288 // number of CSE and divergence recomputations, process all the uses of this
13289 // user that we can find this way.
13290 bool To_IsDivergent = false;
13291 do {
13292 SDUse &Use = *UI;
13293 const SDValue &ToOp = To[Use.getResNo()];
13294 ++UI;
13295 Use.set(ToOp);
13296 if (ToOp.getValueType() != MVT::Other)
13297 To_IsDivergent |= ToOp->isDivergent();
13298 } while (UI != UE && UI->getUser() == User);
13299
13300 if (To_IsDivergent != From->isDivergent())
13302
13303 // Now that we have modified User, add it back to the CSE maps. If it
13304 // already exists there, recursively merge the results together.
13305 AddModifiedNodeToCSEMaps(User);
13306 }
13307
13308 // If we just RAUW'd the root, take note.
13309 if (From == getRoot().getNode())
13310 setRoot(SDValue(To[getRoot().getResNo()]));
13311}
13312
13313/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13314/// uses of other values produced by From.getNode() alone. The Deleted
13315/// vector is handled the same way as for ReplaceAllUsesWith.
13317 // Handle the really simple, really trivial case efficiently.
13318 if (From == To) return;
13319
13320 // Handle the simple, trivial, case efficiently.
13321 if (From.getNode()->getNumValues() == 1) {
13322 ReplaceAllUsesWith(From, To);
13323 return;
13324 }
13325
13326 // Preserve Debug Info.
13327 transferDbgValues(From, To);
13328 copyExtraInfo(From.getNode(), To.getNode());
13329
13330 // Iterate over just the existing users of From. See the comments in
13331 // the ReplaceAllUsesWith above.
13332 SDNode::use_iterator UI = From.getNode()->use_begin(),
13333 UE = From.getNode()->use_end();
13334 RAUWUpdateListener Listener(*this, UI, UE);
13335 while (UI != UE) {
13336 SDNode *User = UI->getUser();
13337 bool UserRemovedFromCSEMaps = false;
13338
13339 // A user can appear in a use list multiple times, and when this
13340 // happens the uses are usually next to each other in the list.
13341 // To help reduce the number of CSE recomputations, process all
13342 // the uses of this user that we can find this way.
13343 do {
13344 SDUse &Use = *UI;
13345
13346 // Skip uses of different values from the same node.
13347 if (Use.getResNo() != From.getResNo()) {
13348 ++UI;
13349 continue;
13350 }
13351
13352 // If this node hasn't been modified yet, it's still in the CSE maps,
13353 // so remove its old self from the CSE maps.
13354 if (!UserRemovedFromCSEMaps) {
13355 RemoveNodeFromCSEMaps(User);
13356 UserRemovedFromCSEMaps = true;
13357 }
13358
13359 ++UI;
13360 Use.set(To);
13361 if (To->isDivergent() != From->isDivergent())
13363 } while (UI != UE && UI->getUser() == User);
13364 // We are iterating over all uses of the From node, so if a use
13365 // doesn't use the specific value, no changes are made.
13366 if (!UserRemovedFromCSEMaps)
13367 continue;
13368
13369 // Now that we have modified User, add it back to the CSE maps. If it
13370 // already exists there, recursively merge the results together.
13371 AddModifiedNodeToCSEMaps(User);
13372 }
13373
13374 // If we just RAUW'd the root, take note.
13375 if (From == getRoot())
13376 setRoot(To);
13377}
13378
13379namespace {
13380
13381/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13382/// to record information about a use.
13383struct UseMemo {
13384 SDNode *User;
13385 unsigned Index;
13386 SDUse *Use;
13387};
13388
13389/// operator< - Sort Memos by User.
13390bool operator<(const UseMemo &L, const UseMemo &R) {
13391 return (intptr_t)L.User < (intptr_t)R.User;
13392}
13393
13394/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13395/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13396/// the node already has been taken care of recursively.
13397class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13398 SmallVectorImpl<UseMemo> &Uses;
13399
13400 void NodeDeleted(SDNode *N, SDNode *E) override {
13401 for (UseMemo &Memo : Uses)
13402 if (Memo.User == N)
13403 Memo.User = nullptr;
13404 }
13405
13406public:
13407 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13408 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13409};
13410
13411} // end anonymous namespace
13412
13413/// Return true if a glue output should propagate divergence information.
13415 switch (Node->getOpcode()) {
13416 case ISD::CopyFromReg:
13417 case ISD::CopyToReg:
13418 return false;
13419 default:
13420 return true;
13421 }
13422
13423 llvm_unreachable("covered opcode switch");
13424}
13425
13427 if (TLI->isSDNodeAlwaysUniform(N)) {
13428 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13429 "Conflicting divergence information!");
13430 return false;
13431 }
13432 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13433 return true;
13434 for (const auto &Op : N->ops()) {
13435 EVT VT = Op.getValueType();
13436
13437 // Skip Chain. It does not carry divergence.
13438 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13439 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13440 return true;
13441 }
13442 return false;
13443}
13444
13446 SmallVector<SDNode *, 16> Worklist(1, N);
13447 do {
13448 N = Worklist.pop_back_val();
13449 bool IsDivergent = calculateDivergence(N);
13450 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13451 N->SDNodeBits.IsDivergent = IsDivergent;
13452 llvm::append_range(Worklist, N->users());
13453 }
13454 } while (!Worklist.empty());
13455}
13456
13457void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13459 Order.reserve(AllNodes.size());
13460 for (auto &N : allnodes()) {
13461 unsigned NOps = N.getNumOperands();
13462 Degree[&N] = NOps;
13463 if (0 == NOps)
13464 Order.push_back(&N);
13465 }
13466 for (size_t I = 0; I != Order.size(); ++I) {
13467 SDNode *N = Order[I];
13468 for (auto *U : N->users()) {
13469 unsigned &UnsortedOps = Degree[U];
13470 if (0 == --UnsortedOps)
13471 Order.push_back(U);
13472 }
13473 }
13474}
13475
13476#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13477void SelectionDAG::VerifyDAGDivergence() {
13478 std::vector<SDNode *> TopoOrder;
13479 CreateTopologicalOrder(TopoOrder);
13480 for (auto *N : TopoOrder) {
13481 assert(calculateDivergence(N) == N->isDivergent() &&
13482 "Divergence bit inconsistency detected");
13483 }
13484}
13485#endif
13486
13487/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13488/// uses of other values produced by From.getNode() alone. The same value
13489/// may appear in both the From and To list. The Deleted vector is
13490/// handled the same way as for ReplaceAllUsesWith.
13492 const SDValue *To,
13493 unsigned Num){
13494 // Handle the simple, trivial case efficiently.
13495 if (Num == 1)
13496 return ReplaceAllUsesOfValueWith(*From, *To);
13497
13498 transferDbgValues(*From, *To);
13499 copyExtraInfo(From->getNode(), To->getNode());
13500
13501 // Read up all the uses and make records of them. This helps
13502 // processing new uses that are introduced during the
13503 // replacement process.
13505 for (unsigned i = 0; i != Num; ++i) {
13506 unsigned FromResNo = From[i].getResNo();
13507 SDNode *FromNode = From[i].getNode();
13508 for (SDUse &Use : FromNode->uses()) {
13509 if (Use.getResNo() == FromResNo) {
13510 UseMemo Memo = {Use.getUser(), i, &Use};
13511 Uses.push_back(Memo);
13512 }
13513 }
13514 }
13515
13516 // Sort the uses, so that all the uses from a given User are together.
13518 RAUOVWUpdateListener Listener(*this, Uses);
13519
13520 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13521 UseIndex != UseIndexEnd; ) {
13522 // We know that this user uses some value of From. If it is the right
13523 // value, update it.
13524 SDNode *User = Uses[UseIndex].User;
13525 // If the node has been deleted by recursive CSE updates when updating
13526 // another node, then just skip this entry.
13527 if (User == nullptr) {
13528 ++UseIndex;
13529 continue;
13530 }
13531
13532 // This node is about to morph, remove its old self from the CSE maps.
13533 RemoveNodeFromCSEMaps(User);
13534
13535 // The Uses array is sorted, so all the uses for a given User
13536 // are next to each other in the list.
13537 // To help reduce the number of CSE recomputations, process all
13538 // the uses of this user that we can find this way.
13539 do {
13540 unsigned i = Uses[UseIndex].Index;
13541 SDUse &Use = *Uses[UseIndex].Use;
13542 ++UseIndex;
13543
13544 Use.set(To[i]);
13545 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13546
13547 // Now that we have modified User, add it back to the CSE maps. If it
13548 // already exists there, recursively merge the results together.
13549 AddModifiedNodeToCSEMaps(User);
13550 }
13551}
13552
13553/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13554/// based on their topological order. It returns the maximum id and a vector
13555/// of the SDNodes* in assigned order by reference.
13557 unsigned DAGSize = 0;
13558
13559 // SortedPos tracks the progress of the algorithm. Nodes before it are
13560 // sorted, nodes after it are unsorted. When the algorithm completes
13561 // it is at the end of the list.
13562 allnodes_iterator SortedPos = allnodes_begin();
13563
13564 // Visit all the nodes. Move nodes with no operands to the front of
13565 // the list immediately. Annotate nodes that do have operands with their
13566 // operand count. Before we do this, the Node Id fields of the nodes
13567 // may contain arbitrary values. After, the Node Id fields for nodes
13568 // before SortedPos will contain the topological sort index, and the
13569 // Node Id fields for nodes At SortedPos and after will contain the
13570 // count of outstanding operands.
13572 checkForCycles(&N, this);
13573 unsigned Degree = N.getNumOperands();
13574 if (Degree == 0) {
13575 // A node with no uses, add it to the result array immediately.
13576 N.setNodeId(DAGSize++);
13577 allnodes_iterator Q(&N);
13578 if (Q != SortedPos)
13579 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13580 assert(SortedPos != AllNodes.end() && "Overran node list");
13581 ++SortedPos;
13582 } else {
13583 // Temporarily use the Node Id as scratch space for the degree count.
13584 N.setNodeId(Degree);
13585 }
13586 }
13587
13588 // Visit all the nodes. As we iterate, move nodes into sorted order,
13589 // such that by the time the end is reached all nodes will be sorted.
13590 for (SDNode &Node : allnodes()) {
13591 SDNode *N = &Node;
13592 checkForCycles(N, this);
13593 // N is in sorted position, so all its uses have one less operand
13594 // that needs to be sorted.
13595 for (SDNode *P : N->users()) {
13596 unsigned Degree = P->getNodeId();
13597 assert(Degree != 0 && "Invalid node degree");
13598 --Degree;
13599 if (Degree == 0) {
13600 // All of P's operands are sorted, so P may sorted now.
13601 P->setNodeId(DAGSize++);
13602 if (P->getIterator() != SortedPos)
13603 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13604 assert(SortedPos != AllNodes.end() && "Overran node list");
13605 ++SortedPos;
13606 } else {
13607 // Update P's outstanding operand count.
13608 P->setNodeId(Degree);
13609 }
13610 }
13611 if (Node.getIterator() == SortedPos) {
13612#ifndef NDEBUG
13614 SDNode *S = &*++I;
13615 dbgs() << "Overran sorted position:\n";
13616 S->dumprFull(this); dbgs() << "\n";
13617 dbgs() << "Checking if this is due to cycles\n";
13618 checkForCycles(this, true);
13619#endif
13620 llvm_unreachable(nullptr);
13621 }
13622 }
13623
13624 assert(SortedPos == AllNodes.end() &&
13625 "Topological sort incomplete!");
13626 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13627 "First node in topological sort is not the entry token!");
13628 assert(AllNodes.front().getNodeId() == 0 &&
13629 "First node in topological sort has non-zero id!");
13630 assert(AllNodes.front().getNumOperands() == 0 &&
13631 "First node in topological sort has operands!");
13632 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13633 "Last node in topologic sort has unexpected id!");
13634 assert(AllNodes.back().use_empty() &&
13635 "Last node in topologic sort has users!");
13636 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13637 return DAGSize;
13638}
13639
13641 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13642 SortedNodes.clear();
13643 // Node -> remaining number of outstanding operands.
13644 DenseMap<const SDNode *, unsigned> RemainingOperands;
13645
13646 // Put nodes without any operands into SortedNodes first.
13647 for (const SDNode &N : allnodes()) {
13648 checkForCycles(&N, this);
13649 unsigned NumOperands = N.getNumOperands();
13650 if (NumOperands == 0)
13651 SortedNodes.push_back(&N);
13652 else
13653 // Record their total number of outstanding operands.
13654 RemainingOperands[&N] = NumOperands;
13655 }
13656
13657 // A node is pushed into SortedNodes when all of its operands (predecessors in
13658 // the graph) are also in SortedNodes.
13659 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13660 const SDNode *N = SortedNodes[i];
13661 for (const SDNode *U : N->users()) {
13662 // HandleSDNode is never part of a DAG and therefore has no entry in
13663 // RemainingOperands.
13664 if (U->getOpcode() == ISD::HANDLENODE)
13665 continue;
13666 unsigned &NumRemOperands = RemainingOperands[U];
13667 assert(NumRemOperands && "Invalid number of remaining operands");
13668 --NumRemOperands;
13669 if (!NumRemOperands)
13670 SortedNodes.push_back(U);
13671 }
13672 }
13673
13674 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13675 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13676 "First node in topological sort is not the entry token");
13677 assert(SortedNodes.front()->getNumOperands() == 0 &&
13678 "First node in topological sort has operands");
13679}
13680
13681/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13682/// value is produced by SD.
13683void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13684 for (SDNode *SD : DB->getSDNodes()) {
13685 if (!SD)
13686 continue;
13687 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13688 SD->setHasDebugValue(true);
13689 }
13690 DbgInfo->add(DB, isParameter);
13691}
13692
13693void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13694
13696 SDValue NewMemOpChain) {
13697 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13698 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13699 // The new memory operation must have the same position as the old load in
13700 // terms of memory dependency. Create a TokenFactor for the old load and new
13701 // memory operation and update uses of the old load's output chain to use that
13702 // TokenFactor.
13703 if (OldChain == NewMemOpChain || OldChain.use_empty())
13704 return NewMemOpChain;
13705
13706 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13707 OldChain, NewMemOpChain);
13708 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13709 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13710 return TokenFactor;
13711}
13712
13714 SDValue NewMemOp) {
13715 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13716 SDValue OldChain = SDValue(OldLoad, 1);
13717 SDValue NewMemOpChain = NewMemOp.getValue(1);
13718 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13719}
13720
13722 Function **OutFunction) {
13723 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13724
13725 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13726 auto *Module = MF->getFunction().getParent();
13727 auto *Function = Module->getFunction(Symbol);
13728
13729 if (OutFunction != nullptr)
13730 *OutFunction = Function;
13731
13732 if (Function != nullptr) {
13733 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13734 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13735 }
13736
13737 std::string ErrorStr;
13738 raw_string_ostream ErrorFormatter(ErrorStr);
13739 ErrorFormatter << "Undefined external symbol ";
13740 ErrorFormatter << '"' << Symbol << '"';
13741 report_fatal_error(Twine(ErrorStr));
13742}
13743
13744//===----------------------------------------------------------------------===//
13745// SDNode Class
13746//===----------------------------------------------------------------------===//
13747
13750 return Const != nullptr && Const->isZero();
13751}
13752
13754 return V.isUndef() || isNullConstant(V);
13755}
13756
13759 return Const != nullptr && Const->isZero() && !Const->isNegative();
13760}
13761
13764 return Const != nullptr && Const->isAllOnes();
13765}
13766
13769 return Const != nullptr && Const->isOne();
13770}
13771
13774 return Const != nullptr && Const->isMinSignedValue();
13775}
13776
13778 SDValue V, unsigned OperandNo,
13779 unsigned Depth) const {
13780 APInt DemandedElts = getDemandAllEltsMask(V);
13781 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13782}
13783
13785 SDValue V, const APInt &DemandedElts,
13786 unsigned OperandNo, unsigned Depth) const {
13787 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13788 // TODO: Target-specific opcodes could be added.
13789 if (V.getValueType().isInteger()) {
13790 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13791 if (Known.isConstant()) {
13792 const APInt &Const = Known.getConstant();
13793 switch (Opcode) {
13794 case ISD::ADD:
13795 case ISD::OR:
13796 case ISD::XOR:
13797 case ISD::UMAX:
13798 return Const.isZero();
13799 case ISD::MUL:
13800 return Const.isOne();
13801 case ISD::AND:
13802 case ISD::UMIN:
13803 return Const.isAllOnes();
13804 case ISD::SMAX:
13805 return Const.isMinSignedValue();
13806 case ISD::SMIN:
13807 return Const.isMaxSignedValue();
13808 case ISD::SUB:
13809 case ISD::SHL:
13810 case ISD::SRA:
13811 case ISD::SRL:
13812 return OperandNo == 1 && Const.isZero();
13813 case ISD::UDIV:
13814 case ISD::SDIV:
13815 return OperandNo == 1 && Const.isOne();
13816 }
13817 }
13818 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13819 switch (Opcode) {
13820 case ISD::FADD:
13821 return ConstFP->isZero() &&
13822 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13823 case ISD::FSUB:
13824 return OperandNo == 1 && ConstFP->isZero() &&
13825 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13826 case ISD::FMUL:
13827 return ConstFP->isOne();
13828 case ISD::FDIV:
13829 return OperandNo == 1 && ConstFP->isOne();
13830 case ISD::FMINNUM:
13831 case ISD::FMAXNUM: {
13832 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
13833 EVT VT = V.getValueType();
13834 const fltSemantics &Semantics = VT.getFltSemantics();
13835 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13836 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13837 : APFloat::getLargest(Semantics);
13838 if (Opcode == ISD::FMAXNUM)
13839 NeutralAF.changeSign();
13840
13841 return ConstFP->isExactlyValue(NeutralAF);
13842 }
13843 }
13844 }
13845 return false;
13846}
13847
13849 while (V.getOpcode() == ISD::BITCAST)
13850 V = V.getOperand(0);
13851 return V;
13852}
13853
13855 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
13856 V = V.getOperand(0);
13857 return V;
13858}
13859
13861 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13862 V = V.getOperand(0);
13863 return V;
13864}
13865
13867 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13868 SDValue InVec = V.getOperand(0);
13869 SDValue EltNo = V.getOperand(2);
13870 EVT VT = InVec.getValueType();
13871 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
13872 if (IndexC && VT.isFixedLengthVector() &&
13873 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
13874 !DemandedElts[IndexC->getZExtValue()]) {
13875 V = InVec;
13876 continue;
13877 }
13878 break;
13879 }
13880 return V;
13881}
13882
13884 while (V.getOpcode() == ISD::TRUNCATE)
13885 V = V.getOperand(0);
13886 return V;
13887}
13888
13889bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
13890 if (V.getOpcode() != ISD::XOR)
13891 return false;
13892 V = peekThroughBitcasts(V.getOperand(1));
13893 unsigned NumBits = V.getScalarValueSizeInBits();
13894 ConstantSDNode *C =
13895 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
13896 return C && (C->getAPIntValue().countr_one() >= NumBits);
13897}
13898
13900 bool AllowTruncation) {
13901 APInt DemandedElts = getDemandAllEltsMask(N);
13902 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
13903}
13904
13906 bool AllowUndefs,
13907 bool AllowTruncation) {
13909 return CN;
13910
13911 // SplatVectors can truncate their operands. Ignore that case here unless
13912 // AllowTruncation is set.
13913 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
13914 EVT VecEltVT = N->getValueType(0).getVectorElementType();
13915 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13916 EVT CVT = CN->getValueType(0);
13917 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
13918 if (AllowTruncation || CVT == VecEltVT)
13919 return CN;
13920 }
13921 }
13922
13924 BitVector UndefElements;
13925 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
13926
13927 // BuildVectors can truncate their operands. Ignore that case here unless
13928 // AllowTruncation is set.
13929 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13930 if (CN && (UndefElements.none() || AllowUndefs)) {
13931 EVT CVT = CN->getValueType(0);
13932 EVT NSVT = N.getValueType().getScalarType();
13933 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
13934 if (AllowTruncation || (CVT == NSVT))
13935 return CN;
13936 }
13937 }
13938
13939 return nullptr;
13940}
13941
13943 APInt DemandedElts = getDemandAllEltsMask(N);
13944 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
13945}
13946
13948 const APInt &DemandedElts,
13949 bool AllowUndefs) {
13951 return CN;
13952
13954 BitVector UndefElements;
13955 ConstantFPSDNode *CN =
13956 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
13957 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13958 if (CN && (UndefElements.none() || AllowUndefs))
13959 return CN;
13960 }
13961
13962 if (N.getOpcode() == ISD::SPLAT_VECTOR)
13963 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
13964 return CN;
13965
13966 return nullptr;
13967}
13968
13969bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
13970 // TODO: may want to use peekThroughBitcast() here.
13971 ConstantSDNode *C =
13972 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13973 return C && C->isZero();
13974}
13975
13976bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
13977 ConstantSDNode *C =
13978 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
13979 return C && C->isOne();
13980}
13981
13982bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
13983 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13984 return C && C->isOne();
13985}
13986
13987bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
13989 unsigned BitWidth = N.getScalarValueSizeInBits();
13990 ConstantSDNode *C =
13991 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13992 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
13993}
13994
13995bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
13996 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
13997 return C && APInt::isSameValue(C->getAPIntValue(),
13998 APInt(C->getAPIntValue().getBitWidth(), 1));
13999}
14000
14001bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14003 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14004 return C && C->isZero();
14005}
14006
14007bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14008 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14009 return C && C->isZero();
14010}
14011
14015
14017 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14019 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14020 bool IsVolatile = false;
14021 bool IsNonTemporal = false;
14022 bool IsDereferenceable = true;
14023 bool IsInvariant = true;
14024 for (const MachineMemOperand *MMO : memoperands()) {
14025 IsVolatile |= MMO->isVolatile();
14026 IsNonTemporal |= MMO->isNonTemporal();
14027 IsDereferenceable &= MMO->isDereferenceable();
14028 IsInvariant &= MMO->isInvariant();
14029 }
14030 MemSDNodeBits.IsVolatile = IsVolatile;
14031 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14032 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14033 MemSDNodeBits.IsInvariant = IsInvariant;
14034
14035 // For the single-MMO case, we check here that the size of the memory operand
14036 // fits within the size of the MMO. This is because the MMO might indicate
14037 // only a possible address range instead of specifying the affected memory
14038 // addresses precisely.
14041 getMemOperand()->getSize().getValue())) &&
14042 "Size mismatch!");
14043}
14044
14045/// Profile - Gather unique data for the node.
14046///
14048 AddNodeIDNode(ID, this);
14049}
14050
14051namespace {
14052
14053 struct EVTArray {
14054 std::vector<EVT> VTs;
14055
14056 EVTArray() {
14057 VTs.reserve(MVT::VALUETYPE_SIZE);
14058 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14059 VTs.push_back(MVT((MVT::SimpleValueType)i));
14060 }
14061 };
14062
14063} // end anonymous namespace
14064
14065/// getValueTypeList - Return a pointer to the specified value type.
14066///
14067const EVT *SDNode::getValueTypeList(MVT VT) {
14068 static EVTArray SimpleVTArray;
14069
14070 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14071 return &SimpleVTArray.VTs[VT.SimpleTy];
14072}
14073
14074/// hasAnyUseOfValue - Return true if there are any use of the indicated
14075/// value. This method ignores uses of other values defined by this operation.
14076bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14077 assert(Value < getNumValues() && "Bad value!");
14078
14079 for (SDUse &U : uses())
14080 if (U.getResNo() == Value)
14081 return true;
14082
14083 return false;
14084}
14085
14086/// isOnlyUserOf - Return true if this node is the only use of N.
14087bool SDNode::isOnlyUserOf(const SDNode *N) const {
14088 bool Seen = false;
14089 for (const SDNode *User : N->users()) {
14090 if (User == this)
14091 Seen = true;
14092 else
14093 return false;
14094 }
14095
14096 return Seen;
14097}
14098
14099/// Return true if the only users of N are contained in Nodes.
14101 bool Seen = false;
14102 for (const SDNode *User : N->users()) {
14103 if (llvm::is_contained(Nodes, User))
14104 Seen = true;
14105 else
14106 return false;
14107 }
14108
14109 return Seen;
14110}
14111
14112/// Return true if the referenced return value is an operand of N.
14113bool SDValue::isOperandOf(const SDNode *N) const {
14114 return is_contained(N->op_values(), *this);
14115}
14116
14117bool SDNode::isOperandOf(const SDNode *N) const {
14118 return any_of(N->op_values(),
14119 [this](SDValue Op) { return this == Op.getNode(); });
14120}
14121
14122/// reachesChainWithoutSideEffects - Return true if this operand (which must
14123/// be a chain) reaches the specified operand without crossing any
14124/// side-effecting instructions on any chain path. In practice, this looks
14125/// through token factors and non-volatile loads. In order to remain efficient,
14126/// this only looks a couple of nodes in, it does not do an exhaustive search.
14127///
14128/// Note that we only need to examine chains when we're searching for
14129/// side-effects; SelectionDAG requires that all side-effects are represented
14130/// by chains, even if another operand would force a specific ordering. This
14131/// constraint is necessary to allow transformations like splitting loads.
14133 unsigned Depth) const {
14134 if (*this == Dest) return true;
14135
14136 // Don't search too deeply, we just want to be able to see through
14137 // TokenFactor's etc.
14138 if (Depth == 0) return false;
14139
14140 // If this is a token factor, all inputs to the TF happen in parallel.
14141 if (getOpcode() == ISD::TokenFactor) {
14142 // First, try a shallow search.
14143 if (is_contained((*this)->ops(), Dest)) {
14144 // We found the chain we want as an operand of this TokenFactor.
14145 // Essentially, we reach the chain without side-effects if we could
14146 // serialize the TokenFactor into a simple chain of operations with
14147 // Dest as the last operation. This is automatically true if the
14148 // chain has one use: there are no other ordering constraints.
14149 // If the chain has more than one use, we give up: some other
14150 // use of Dest might force a side-effect between Dest and the current
14151 // node.
14152 if (Dest.hasOneUse())
14153 return true;
14154 }
14155 // Next, try a deep search: check whether every operand of the TokenFactor
14156 // reaches Dest.
14157 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14158 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14159 });
14160 }
14161
14162 // Loads don't have side effects, look through them.
14163 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14164 if (Ld->isUnordered())
14165 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14166 }
14167 return false;
14168}
14169
14170bool SDNode::hasPredecessor(const SDNode *N) const {
14173 Worklist.push_back(this);
14174 return hasPredecessorHelper(N, Visited, Worklist);
14175}
14176
14178 this->Flags &= Flags;
14179}
14180
14181SDValue
14183 ArrayRef<ISD::NodeType> CandidateBinOps,
14184 bool AllowPartials) {
14185 // The pattern must end in an extract from index 0.
14186 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14187 !isNullConstant(Extract->getOperand(1)))
14188 return SDValue();
14189
14190 // Match against one of the candidate binary ops.
14191 SDValue Op = Extract->getOperand(0);
14192 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14193 return Op.getOpcode() == unsigned(BinOp);
14194 }))
14195 return SDValue();
14196
14197 // Floating-point reductions may require relaxed constraints on the final step
14198 // of the reduction because they may reorder intermediate operations.
14199 unsigned CandidateBinOp = Op.getOpcode();
14200 if (Op.getValueType().isFloatingPoint()) {
14201 SDNodeFlags Flags = Op->getFlags();
14202 switch (CandidateBinOp) {
14203 case ISD::FADD:
14204 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14205 return SDValue();
14206 break;
14207 default:
14208 llvm_unreachable("Unhandled FP opcode for binop reduction");
14209 }
14210 }
14211
14212 // Matching failed - attempt to see if we did enough stages that a partial
14213 // reduction from a subvector is possible.
14214 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14215 if (!AllowPartials || !Op)
14216 return SDValue();
14217 EVT OpVT = Op.getValueType();
14218 EVT OpSVT = OpVT.getScalarType();
14219 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14220 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
14221 return SDValue();
14222 BinOp = (ISD::NodeType)CandidateBinOp;
14223 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14224 };
14225
14226 // At each stage, we're looking for something that looks like:
14227 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14228 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14229 // i32 undef, i32 undef, i32 undef, i32 undef>
14230 // %a = binop <8 x i32> %op, %s
14231 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14232 // we expect something like:
14233 // <4,5,6,7,u,u,u,u>
14234 // <2,3,u,u,u,u,u,u>
14235 // <1,u,u,u,u,u,u,u>
14236 // While a partial reduction match would be:
14237 // <2,3,u,u,u,u,u,u>
14238 // <1,u,u,u,u,u,u,u>
14239 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14240 SDValue PrevOp;
14241 for (unsigned i = 0; i < Stages; ++i) {
14242 unsigned MaskEnd = (1 << i);
14243
14244 if (Op.getOpcode() != CandidateBinOp)
14245 return PartialReduction(PrevOp, MaskEnd);
14246
14247 SDValue Op0 = Op.getOperand(0);
14248 SDValue Op1 = Op.getOperand(1);
14249
14251 if (Shuffle) {
14252 Op = Op1;
14253 } else {
14254 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14255 Op = Op0;
14256 }
14257
14258 // The first operand of the shuffle should be the same as the other operand
14259 // of the binop.
14260 if (!Shuffle || Shuffle->getOperand(0) != Op)
14261 return PartialReduction(PrevOp, MaskEnd);
14262
14263 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14264 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14265 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14266 return PartialReduction(PrevOp, MaskEnd);
14267
14268 PrevOp = Op;
14269 }
14270
14271 // Handle subvector reductions, which tend to appear after the shuffle
14272 // reduction stages.
14273 while (Op.getOpcode() == CandidateBinOp) {
14274 unsigned NumElts = Op.getValueType().getVectorNumElements();
14275 SDValue Op0 = Op.getOperand(0);
14276 SDValue Op1 = Op.getOperand(1);
14277 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14279 Op0.getOperand(0) != Op1.getOperand(0))
14280 break;
14281 SDValue Src = Op0.getOperand(0);
14282 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14283 if (NumSrcElts != (2 * NumElts))
14284 break;
14285 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14286 Op1.getConstantOperandAPInt(1) == NumElts) &&
14287 !(Op1.getConstantOperandAPInt(1) == 0 &&
14288 Op0.getConstantOperandAPInt(1) == NumElts))
14289 break;
14290 Op = Src;
14291 }
14292
14293 BinOp = (ISD::NodeType)CandidateBinOp;
14294 return Op;
14295}
14296
14298 EVT VT = N->getValueType(0);
14299 EVT EltVT = VT.getVectorElementType();
14300 unsigned NE = VT.getVectorNumElements();
14301
14302 SDLoc dl(N);
14303
14304 // If ResNE is 0, fully unroll the vector op.
14305 if (ResNE == 0)
14306 ResNE = NE;
14307 else if (NE > ResNE)
14308 NE = ResNE;
14309
14310 if (N->getNumValues() == 2) {
14311 SmallVector<SDValue, 8> Scalars0, Scalars1;
14312 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14313 EVT VT1 = N->getValueType(1);
14314 EVT EltVT1 = VT1.getVectorElementType();
14315
14316 unsigned i;
14317 for (i = 0; i != NE; ++i) {
14318 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14319 SDValue Operand = N->getOperand(j);
14320 EVT OperandVT = Operand.getValueType();
14321
14322 // A vector operand; extract a single element.
14323 EVT OperandEltVT = OperandVT.getVectorElementType();
14324 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14325 }
14326
14327 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14328 Scalars0.push_back(EltOp);
14329 Scalars1.push_back(EltOp.getValue(1));
14330 }
14331
14332 for (; i < ResNE; ++i) {
14333 Scalars0.push_back(getUNDEF(EltVT));
14334 Scalars1.push_back(getUNDEF(EltVT1));
14335 }
14336
14337 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14338 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResNE);
14339 SDValue Vec0 = getBuildVector(VecVT, dl, Scalars0);
14340 SDValue Vec1 = getBuildVector(VecVT1, dl, Scalars1);
14341 return getMergeValues({Vec0, Vec1}, dl);
14342 }
14343
14344 assert(N->getNumValues() == 1 &&
14345 "Can't unroll a vector with multiple results!");
14346
14348 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14349
14350 unsigned i;
14351 for (i= 0; i != NE; ++i) {
14352 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14353 SDValue Operand = N->getOperand(j);
14354 EVT OperandVT = Operand.getValueType();
14355 if (OperandVT.isVector()) {
14356 // A vector operand; extract a single element.
14357 EVT OperandEltVT = OperandVT.getVectorElementType();
14358 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14359 } else {
14360 // A scalar operand; just use it as is.
14361 Operands[j] = Operand;
14362 }
14363 }
14364
14365 switch (N->getOpcode()) {
14366 default: {
14367 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14368 N->getFlags()));
14369 break;
14370 }
14371 case ISD::VSELECT:
14372 Scalars.push_back(
14373 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14374 break;
14375 case ISD::SHL:
14376 case ISD::SRA:
14377 case ISD::SRL:
14378 case ISD::ROTL:
14379 case ISD::ROTR:
14380 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14381 getShiftAmountOperand(Operands[0].getValueType(),
14382 Operands[1])));
14383 break;
14385 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14386 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14387 Operands[0],
14388 getValueType(ExtVT)));
14389 break;
14390 }
14391 case ISD::ADDRSPACECAST: {
14392 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14393 Scalars.push_back(getAddrSpaceCast(dl, EltVT, Operands[0],
14394 ASC->getSrcAddressSpace(),
14395 ASC->getDestAddressSpace()));
14396 break;
14397 }
14398 }
14399 }
14400
14401 for (; i < ResNE; ++i)
14402 Scalars.push_back(getUNDEF(EltVT));
14403
14404 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14405 return getBuildVector(VecVT, dl, Scalars);
14406}
14407
14408std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14409 SDNode *N, unsigned ResNE) {
14410 unsigned Opcode = N->getOpcode();
14411 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14412 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14413 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14414 "Expected an overflow opcode");
14415
14416 EVT ResVT = N->getValueType(0);
14417 EVT OvVT = N->getValueType(1);
14418 EVT ResEltVT = ResVT.getVectorElementType();
14419 EVT OvEltVT = OvVT.getVectorElementType();
14420 SDLoc dl(N);
14421
14422 // If ResNE is 0, fully unroll the vector op.
14423 unsigned NE = ResVT.getVectorNumElements();
14424 if (ResNE == 0)
14425 ResNE = NE;
14426 else if (NE > ResNE)
14427 NE = ResNE;
14428
14429 SmallVector<SDValue, 8> LHSScalars;
14430 SmallVector<SDValue, 8> RHSScalars;
14431 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14432 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14433
14434 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14435 SDVTList VTs = getVTList(ResEltVT, SVT);
14436 SmallVector<SDValue, 8> ResScalars;
14437 SmallVector<SDValue, 8> OvScalars;
14438 for (unsigned i = 0; i < NE; ++i) {
14439 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14440 SDValue Ov =
14441 getSelect(dl, OvEltVT, Res.getValue(1),
14442 getBoolConstant(true, dl, OvEltVT, ResVT),
14443 getConstant(0, dl, OvEltVT));
14444
14445 ResScalars.push_back(Res);
14446 OvScalars.push_back(Ov);
14447 }
14448
14449 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14450 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14451
14452 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14453 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14454 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14455 getBuildVector(NewOvVT, dl, OvScalars));
14456}
14457
14460 unsigned Bytes,
14461 int Dist) const {
14462 if (LD->isVolatile() || Base->isVolatile())
14463 return false;
14464 // TODO: probably too restrictive for atomics, revisit
14465 if (!LD->isSimple())
14466 return false;
14467 if (LD->isIndexed() || Base->isIndexed())
14468 return false;
14469 if (LD->getChain() != Base->getChain())
14470 return false;
14471 EVT VT = LD->getMemoryVT();
14472 if (VT.getSizeInBits() / 8 != Bytes)
14473 return false;
14474
14475 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
14476 auto LocDecomp = BaseIndexOffset::match(LD, *this);
14477
14478 int64_t Offset = 0;
14479 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
14480 return (Dist * (int64_t)Bytes == Offset);
14481 return false;
14482}
14483
14484/// InferPtrAlignment - Infer alignment of a load / store address. Return
14485/// std::nullopt if it cannot be inferred.
14487 // If this is a GlobalAddress + cst, return the alignment.
14488 const GlobalValue *GV = nullptr;
14489 int64_t GVOffset = 0;
14490 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14491 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14492 KnownBits Known(PtrWidth);
14494 unsigned AlignBits = Known.countMinTrailingZeros();
14495 if (AlignBits)
14496 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
14497 }
14498
14499 // If this is a direct reference to a stack slot, use information about the
14500 // stack slot's alignment.
14501 int FrameIdx = INT_MIN;
14502 int64_t FrameOffset = 0;
14504 FrameIdx = FI->getIndex();
14505 } else if (isBaseWithConstantOffset(Ptr) &&
14507 // Handle FI+Cst
14508 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14509 FrameOffset = Ptr.getConstantOperandVal(1);
14510 }
14511
14512 if (FrameIdx != INT_MIN) {
14514 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14515 }
14516
14517 return std::nullopt;
14518}
14519
14520/// Split the scalar node with EXTRACT_ELEMENT using the provided
14521/// VTs and return the low/high part.
14522std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14523 const SDLoc &DL,
14524 const EVT &LoVT,
14525 const EVT &HiVT) {
14526 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14527 "Split node must be a scalar type");
14528 SDValue Lo =
14530 SDValue Hi =
14532 return std::make_pair(Lo, Hi);
14533}
14534
14535/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14536/// which is split (or expanded) into two not necessarily identical pieces.
14537std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14538 // Currently all types are split in half.
14539 EVT LoVT, HiVT;
14540 if (!VT.isVector())
14541 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14542 else
14543 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14544
14545 return std::make_pair(LoVT, HiVT);
14546}
14547
14548/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14549/// type, dependent on an enveloping VT that has been split into two identical
14550/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14551std::pair<EVT, EVT>
14553 bool *HiIsEmpty) const {
14554 EVT EltTp = VT.getVectorElementType();
14555 // Examples:
14556 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14557 // custom VL=9 with enveloping VL=8/8 yields 8/1
14558 // custom VL=10 with enveloping VL=8/8 yields 8/2
14559 // etc.
14560 ElementCount VTNumElts = VT.getVectorElementCount();
14561 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14562 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14563 "Mixing fixed width and scalable vectors when enveloping a type");
14564 EVT LoVT, HiVT;
14565 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14566 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14567 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14568 *HiIsEmpty = false;
14569 } else {
14570 // Flag that hi type has zero storage size, but return split envelop type
14571 // (this would be easier if vector types with zero elements were allowed).
14572 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14573 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14574 *HiIsEmpty = true;
14575 }
14576 return std::make_pair(LoVT, HiVT);
14577}
14578
14579/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14580/// low/high part.
14581std::pair<SDValue, SDValue>
14582SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14583 const EVT &HiVT) {
14584 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14585 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14586 "Splitting vector with an invalid mixture of fixed and scalable "
14587 "vector types");
14589 N.getValueType().getVectorMinNumElements() &&
14590 "More vector elements requested than available!");
14591 SDValue Lo, Hi;
14592 Lo = getExtractSubvector(DL, LoVT, N, 0);
14593 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14594 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14595 // IDX with the runtime scaling factor of the result vector type. For
14596 // fixed-width result vectors, that runtime scaling factor is 1.
14598 return std::make_pair(Lo, Hi);
14599}
14600
14601std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14602 const SDLoc &DL) {
14603 // Split the vector length parameter.
14604 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14605 EVT VT = N.getValueType();
14607 "Expecting the mask to be an evenly-sized vector");
14608 SDValue HalfNumElts = getElementCount(
14610 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14611 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14612 return std::make_pair(Lo, Hi);
14613}
14614
14615/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14617 EVT VT = N.getValueType();
14620 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14621}
14622
14625 unsigned Start, unsigned Count,
14626 EVT EltVT) {
14627 EVT VT = Op.getValueType();
14628 if (Count == 0)
14630 if (EltVT == EVT())
14631 EltVT = VT.getVectorElementType();
14632 SDLoc SL(Op);
14633 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14634 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14635 }
14636}
14637
14638// getAddressSpace - Return the address space this GlobalAddress belongs to.
14640 return getGlobal()->getType()->getAddressSpace();
14641}
14642
14645 return Val.MachineCPVal->getType();
14646 return Val.ConstVal->getType();
14647}
14648
14649bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14650 unsigned &SplatBitSize,
14651 bool &HasAnyUndefs,
14652 unsigned MinSplatBits,
14653 bool IsBigEndian) const {
14654 EVT VT = getValueType(0);
14655 assert(VT.isVector() && "Expected a vector type");
14656 unsigned VecWidth = VT.getSizeInBits();
14657 if (MinSplatBits > VecWidth)
14658 return false;
14659
14660 // FIXME: The widths are based on this node's type, but build vectors can
14661 // truncate their operands.
14662 SplatValue = APInt(VecWidth, 0);
14663 SplatUndef = APInt(VecWidth, 0);
14664
14665 // Get the bits. Bits with undefined values (when the corresponding element
14666 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14667 // in SplatValue. If any of the values are not constant, give up and return
14668 // false.
14669 unsigned int NumOps = getNumOperands();
14670 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14671 unsigned EltWidth = VT.getScalarSizeInBits();
14672
14673 for (unsigned j = 0; j < NumOps; ++j) {
14674 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14675 SDValue OpVal = getOperand(i);
14676 unsigned BitPos = j * EltWidth;
14677
14678 if (OpVal.isUndef())
14679 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14680 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14681 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14682 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14683 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14684 else
14685 return false;
14686 }
14687
14688 // The build_vector is all constants or undefs. Find the smallest element
14689 // size that splats the vector.
14690 HasAnyUndefs = (SplatUndef != 0);
14691
14692 // FIXME: This does not work for vectors with elements less than 8 bits.
14693 while (VecWidth > 8) {
14694 // If we can't split in half, stop here.
14695 if (VecWidth & 1)
14696 break;
14697
14698 unsigned HalfSize = VecWidth / 2;
14699 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14700 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14701 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14702 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14703
14704 // If the two halves do not match (ignoring undef bits), stop here.
14705 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14706 MinSplatBits > HalfSize)
14707 break;
14708
14709 SplatValue = HighValue | LowValue;
14710 SplatUndef = HighUndef & LowUndef;
14711
14712 VecWidth = HalfSize;
14713 }
14714
14715 // FIXME: The loop above only tries to split in halves. But if the input
14716 // vector for example is <3 x i16> it wouldn't be able to detect a
14717 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14718 // optimizations. I guess that back in the days when this helper was created
14719 // vectors normally was power-of-2 sized.
14720
14721 SplatBitSize = VecWidth;
14722 return true;
14723}
14724
14726 BitVector *UndefElements) const {
14727 unsigned NumOps = getNumOperands();
14728 if (UndefElements) {
14729 UndefElements->clear();
14730 UndefElements->resize(NumOps);
14731 }
14732 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14733 if (!DemandedElts)
14734 return SDValue();
14735 SDValue Splatted;
14736 for (unsigned i = 0; i != NumOps; ++i) {
14737 if (!DemandedElts[i])
14738 continue;
14739 SDValue Op = getOperand(i);
14740 if (Op.isUndef()) {
14741 if (UndefElements)
14742 (*UndefElements)[i] = true;
14743 } else if (!Splatted) {
14744 Splatted = Op;
14745 } else if (Splatted != Op) {
14746 return SDValue();
14747 }
14748 }
14749
14750 if (!Splatted) {
14751 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14752 assert(getOperand(FirstDemandedIdx).isUndef() &&
14753 "Can only have a splat without a constant for all undefs.");
14754 return getOperand(FirstDemandedIdx);
14755 }
14756
14757 return Splatted;
14758}
14759
14761 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14762 return getSplatValue(DemandedElts, UndefElements);
14763}
14764
14766 SmallVectorImpl<SDValue> &Sequence,
14767 BitVector *UndefElements) const {
14768 unsigned NumOps = getNumOperands();
14769 Sequence.clear();
14770 if (UndefElements) {
14771 UndefElements->clear();
14772 UndefElements->resize(NumOps);
14773 }
14774 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14775 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14776 return false;
14777
14778 // Set the undefs even if we don't find a sequence (like getSplatValue).
14779 if (UndefElements)
14780 for (unsigned I = 0; I != NumOps; ++I)
14781 if (DemandedElts[I] && getOperand(I).isUndef())
14782 (*UndefElements)[I] = true;
14783
14784 // Iteratively widen the sequence length looking for repetitions.
14785 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14786 Sequence.append(SeqLen, SDValue());
14787 for (unsigned I = 0; I != NumOps; ++I) {
14788 if (!DemandedElts[I])
14789 continue;
14790 SDValue &SeqOp = Sequence[I % SeqLen];
14792 if (Op.isUndef()) {
14793 if (!SeqOp)
14794 SeqOp = Op;
14795 continue;
14796 }
14797 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14798 Sequence.clear();
14799 break;
14800 }
14801 SeqOp = Op;
14802 }
14803 if (!Sequence.empty())
14804 return true;
14805 }
14806
14807 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14808 return false;
14809}
14810
14812 BitVector *UndefElements) const {
14813 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14814 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14815}
14816
14819 BitVector *UndefElements) const {
14821 getSplatValue(DemandedElts, UndefElements));
14822}
14823
14826 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14827}
14828
14831 BitVector *UndefElements) const {
14833 getSplatValue(DemandedElts, UndefElements));
14834}
14835
14840
14841int32_t
14843 uint32_t BitWidth) const {
14844 if (ConstantFPSDNode *CN =
14846 bool IsExact;
14847 APSInt IntVal(BitWidth);
14848 const APFloat &APF = CN->getValueAPF();
14849 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14850 APFloat::opOK ||
14851 !IsExact)
14852 return -1;
14853
14854 return IntVal.exactLogBase2();
14855 }
14856 return -1;
14857}
14858
14860 bool IsLittleEndian, unsigned DstEltSizeInBits,
14861 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
14862 // Early-out if this contains anything but Undef/Constant/ConstantFP.
14863 if (!isConstant())
14864 return false;
14865
14866 unsigned NumSrcOps = getNumOperands();
14867 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
14868 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14869 "Invalid bitcast scale");
14870
14871 // Extract raw src bits.
14872 SmallVector<APInt> SrcBitElements(NumSrcOps,
14873 APInt::getZero(SrcEltSizeInBits));
14874 BitVector SrcUndeElements(NumSrcOps, false);
14875
14876 for (unsigned I = 0; I != NumSrcOps; ++I) {
14878 if (Op.isUndef()) {
14879 SrcUndeElements.set(I);
14880 continue;
14881 }
14882 auto *CInt = dyn_cast<ConstantSDNode>(Op);
14883 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
14884 assert((CInt || CFP) && "Unknown constant");
14885 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
14886 : CFP->getValueAPF().bitcastToAPInt();
14887 }
14888
14889 // Recast to dst width.
14890 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
14891 SrcBitElements, UndefElements, SrcUndeElements);
14892 return true;
14893}
14894
14895void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
14896 unsigned DstEltSizeInBits,
14897 SmallVectorImpl<APInt> &DstBitElements,
14898 ArrayRef<APInt> SrcBitElements,
14899 BitVector &DstUndefElements,
14900 const BitVector &SrcUndefElements) {
14901 unsigned NumSrcOps = SrcBitElements.size();
14902 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
14903 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14904 "Invalid bitcast scale");
14905 assert(NumSrcOps == SrcUndefElements.size() &&
14906 "Vector size mismatch");
14907
14908 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
14909 DstUndefElements.clear();
14910 DstUndefElements.resize(NumDstOps, false);
14911 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
14912
14913 // Concatenate src elements constant bits together into dst element.
14914 if (SrcEltSizeInBits <= DstEltSizeInBits) {
14915 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
14916 for (unsigned I = 0; I != NumDstOps; ++I) {
14917 DstUndefElements.set(I);
14918 APInt &DstBits = DstBitElements[I];
14919 for (unsigned J = 0; J != Scale; ++J) {
14920 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14921 if (SrcUndefElements[Idx])
14922 continue;
14923 DstUndefElements.reset(I);
14924 const APInt &SrcBits = SrcBitElements[Idx];
14925 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
14926 "Illegal constant bitwidths");
14927 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
14928 }
14929 }
14930 return;
14931 }
14932
14933 // Split src element constant bits into dst elements.
14934 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
14935 for (unsigned I = 0; I != NumSrcOps; ++I) {
14936 if (SrcUndefElements[I]) {
14937 DstUndefElements.set(I * Scale, (I + 1) * Scale);
14938 continue;
14939 }
14940 const APInt &SrcBits = SrcBitElements[I];
14941 for (unsigned J = 0; J != Scale; ++J) {
14942 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14943 APInt &DstBits = DstBitElements[Idx];
14944 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
14945 }
14946 }
14947}
14948
14950 for (const SDValue &Op : op_values()) {
14951 unsigned Opc = Op.getOpcode();
14952 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
14953 return false;
14954 }
14955 return true;
14956}
14957
14958std::optional<std::pair<APInt, APInt>>
14960 unsigned NumOps = getNumOperands();
14961 if (NumOps < 2)
14962 return std::nullopt;
14963
14964 unsigned EltSize = getValueType(0).getScalarSizeInBits();
14965 APInt Start, Stride;
14966 int FirstIdx = -1, SecondIdx = -1;
14967
14968 // Find the first two non-undef constant elements to determine Start and
14969 // Stride, then verify all remaining elements match the sequence.
14970 for (unsigned I = 0; I < NumOps; ++I) {
14972 if (Op->isUndef())
14973 continue;
14974 if (!isa<ConstantSDNode>(Op))
14975 return std::nullopt;
14976
14977 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
14978 if (FirstIdx < 0) {
14979 FirstIdx = I;
14980 Start = Val;
14981 } else if (SecondIdx < 0) {
14982 SecondIdx = I;
14983 // Compute stride using modular arithmetic. Simple division would handle
14984 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
14985 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
14986 // Note that modular arithmetic is agnostic to signed/unsigned.
14987 unsigned IdxDiff = I - FirstIdx;
14988 APInt ValDiff = Val - Start;
14989
14990 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
14991 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
14992 if (ValDiff.countr_zero() < CommonPow2Bits)
14993 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
14994 IdxDiff >>= CommonPow2Bits;
14995 ValDiff.lshrInPlace(CommonPow2Bits);
14996
14997 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
14998 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
14999 // one, but we could try all candidates to handle more cases.
15000 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15001 if (Stride.isZero())
15002 return std::nullopt;
15003
15004 // Step 3: Adjust Start based on the first defined element's index.
15005 Start -= Stride * FirstIdx;
15006 } else {
15007 // Verify this element matches the sequence.
15008 if (Val != Start + Stride * I)
15009 return std::nullopt;
15010 }
15011 }
15012
15013 // Need at least two defined elements.
15014 if (SecondIdx < 0)
15015 return std::nullopt;
15016
15017 return std::make_pair(Start, Stride);
15018}
15019
15021 // Find the first non-undef value in the shuffle mask.
15022 unsigned i, e;
15023 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15024 /* search */;
15025
15026 // If all elements are undefined, this shuffle can be considered a splat
15027 // (although it should eventually get simplified away completely).
15028 if (i == e)
15029 return true;
15030
15031 // Make sure all remaining elements are either undef or the same as the first
15032 // non-undef value.
15033 for (int Idx = Mask[i]; i != e; ++i)
15034 if (Mask[i] >= 0 && Mask[i] != Idx)
15035 return false;
15036 return true;
15037}
15038
15039// Returns true if it is a constant integer BuildVector or constant integer,
15040// possibly hidden by a bitcast.
15042 SDValue N, bool AllowOpaques) const {
15044
15045 if (auto *C = dyn_cast<ConstantSDNode>(N))
15046 return AllowOpaques || !C->isOpaque();
15047
15049 return true;
15050
15051 // Treat a GlobalAddress supporting constant offset folding as a
15052 // constant integer.
15053 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15054 if (GA->getOpcode() == ISD::GlobalAddress &&
15055 TLI->isOffsetFoldingLegal(GA))
15056 return true;
15057
15058 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15059 isa<ConstantSDNode>(N.getOperand(0)))
15060 return true;
15061 return false;
15062}
15063
15064// Returns true if it is a constant float BuildVector or constant float.
15067 return true;
15068
15070 return true;
15071
15072 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15073 isa<ConstantFPSDNode>(N.getOperand(0)))
15074 return true;
15075
15076 return false;
15077}
15078
15079std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15080 ConstantSDNode *Const =
15081 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15082 if (!Const)
15083 return std::nullopt;
15084
15085 EVT VT = N->getValueType(0);
15086 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15087 switch (TLI->getBooleanContents(N.getValueType())) {
15089 if (CVal.isOne())
15090 return true;
15091 if (CVal.isZero())
15092 return false;
15093 return std::nullopt;
15095 if (CVal.isAllOnes())
15096 return true;
15097 if (CVal.isZero())
15098 return false;
15099 return std::nullopt;
15101 return CVal[0];
15102 }
15103 llvm_unreachable("Unknown BooleanContent enum");
15104}
15105
15106void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15107 assert(!Node->OperandList && "Node already has operands");
15109 "too many operands to fit into SDNode");
15110 SDUse *Ops = OperandRecycler.allocate(
15111 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15112
15113 bool IsDivergent = false;
15114 for (unsigned I = 0; I != Vals.size(); ++I) {
15115 Ops[I].setUser(Node);
15116 Ops[I].setInitial(Vals[I]);
15117 EVT VT = Ops[I].getValueType();
15118
15119 // Skip Chain. It does not carry divergence.
15120 if (VT != MVT::Other &&
15121 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15122 Ops[I].getNode()->isDivergent()) {
15123 IsDivergent = true;
15124 }
15125 }
15126 Node->NumOperands = Vals.size();
15127 Node->OperandList = Ops;
15128 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15129 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15130 Node->SDNodeBits.IsDivergent = IsDivergent;
15131 }
15132 checkForCycles(Node);
15133}
15134
15137 size_t Limit = SDNode::getMaxNumOperands();
15138 while (Vals.size() > Limit) {
15139 unsigned SliceIdx = Vals.size() - Limit;
15140 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15141 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15142 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15143 Vals.emplace_back(NewTF);
15144 }
15145 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15146}
15147
15149 EVT VT, SDNodeFlags Flags) {
15150 switch (Opcode) {
15151 default:
15152 return SDValue();
15153 case ISD::ADD:
15154 case ISD::OR:
15155 case ISD::XOR:
15156 case ISD::UMAX:
15157 case ISD::MUL:
15158 case ISD::AND:
15159 case ISD::UMIN:
15160 case ISD::SMAX:
15161 case ISD::SMIN:
15163 VT);
15164 case ISD::FADD:
15165 // If flags allow, prefer positive zero since it's generally cheaper
15166 // to materialize on most targets.
15167 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15168 case ISD::FMUL:
15169 return getConstantFP(1.0, DL, VT);
15170 case ISD::FMINNUM:
15171 case ISD::FMAXNUM: {
15172 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
15173 const fltSemantics &Semantics = VT.getFltSemantics();
15174 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15175 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15176 APFloat::getLargest(Semantics);
15177 if (Opcode == ISD::FMAXNUM)
15178 NeutralAF.changeSign();
15179
15180 return getConstantFP(NeutralAF, DL, VT);
15181 }
15182 case ISD::FMINIMUM:
15183 case ISD::FMAXIMUM: {
15184 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15185 const fltSemantics &Semantics = VT.getFltSemantics();
15186 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15187 : APFloat::getLargest(Semantics);
15188 if (Opcode == ISD::FMAXIMUM)
15189 NeutralAF.changeSign();
15190
15191 return getConstantFP(NeutralAF, DL, VT);
15192 }
15193
15194 }
15195}
15196
15198 SDValue Acc, SDValue LHS,
15199 SDValue RHS) {
15200 EVT AccVT = Acc.getValueType();
15201 if (AccVT.isFloatingPoint()) {
15202 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15203 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15204 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15205 }
15207 "Unexpected opcode");
15208 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15209 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15210 return getNegative(MLA, DL, AccVT);
15211}
15212
15213/// Helper used to make a call to a library function that has one argument of
15214/// pointer type.
15215///
15216/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15217/// used to get or set floating-point state. They have one argument of pointer
15218/// type, which points to the memory region containing bits of the
15219/// floating-point state. The value returned by such function is ignored in the
15220/// created call.
15221///
15222/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15223/// \param Ptr Pointer used to save/load state.
15224/// \param InChain Ingoing token chain.
15225/// \returns Outgoing chain token.
15227 SDValue InChain,
15228 const SDLoc &DLoc) {
15229 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15231 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15232 RTLIB::LibcallImpl LibcallImpl =
15233 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15234 if (LibcallImpl == RTLIB::Unsupported)
15235 reportFatalUsageError("emitting call to unsupported libcall");
15236
15237 SDValue Callee =
15238 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15240 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
15241 Libcalls->getLibcallImplCallingConv(LibcallImpl),
15242 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15243 return TLI->LowerCallTo(CLI).second;
15244}
15245
15247 assert(From && To && "Invalid SDNode; empty source SDValue?");
15248 auto I = SDEI.find(From);
15249 if (I == SDEI.end())
15250 return;
15251
15252 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15253 // the iterator, hence the need to make a copy to prevent a use-after-free.
15254 NodeExtraInfo NEI = I->second;
15255 if (LLVM_LIKELY(!NEI.PCSections)) {
15256 // No deep copy required for the types of extra info set.
15257 //
15258 // FIXME: Investigate if other types of extra info also need deep copy. This
15259 // depends on the types of nodes they can be attached to: if some extra info
15260 // is only ever attached to nodes where a replacement To node is always the
15261 // node where later use and propagation of the extra info has the intended
15262 // semantics, no deep copy is required.
15263 SDEI[To] = std::move(NEI);
15264 return;
15265 }
15266
15267 const SDNode *EntrySDN = getEntryNode().getNode();
15268
15269 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15270 // through the replacement of From with To. Otherwise, replacements of a node
15271 // (From) with more complex nodes (To and its operands) may result in lost
15272 // extra info where the root node (To) is insignificant in further propagating
15273 // and using extra info when further lowering to MIR.
15274 //
15275 // In the first step pre-populate the visited set with the nodes reachable
15276 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15277 // DAG that is not new and should be left untouched.
15278 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15279 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15280 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15281 if (MaxDepth == 0) {
15282 // Remember this node in case we need to increase MaxDepth and continue
15283 // populating FromReach from this node.
15284 Leafs.emplace_back(N);
15285 return;
15286 }
15287 if (!FromReach.insert(N).second)
15288 return;
15289 for (const SDValue &Op : N->op_values())
15290 Self(Self, Op.getNode(), MaxDepth - 1);
15291 };
15292
15293 // Copy extra info to To and all its transitive operands (that are new).
15295 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15296 if (FromReach.contains(N))
15297 return true;
15298 if (!Visited.insert(N).second)
15299 return true;
15300 if (EntrySDN == N)
15301 return false;
15302 for (const SDValue &Op : N->op_values()) {
15303 if (N == To && Op.getNode() == EntrySDN) {
15304 // Special case: New node's operand is the entry node; just need to
15305 // copy extra info to new node.
15306 break;
15307 }
15308 if (!Self(Self, Op.getNode()))
15309 return false;
15310 }
15311 // Copy only if entry node was not reached.
15312 SDEI[N] = std::move(NEI);
15313 return true;
15314 };
15315
15316 // We first try with a lower MaxDepth, assuming that the path to common
15317 // operands between From and To is relatively short. This significantly
15318 // improves performance in the common case. The initial MaxDepth is big
15319 // enough to avoid retry in the common case; the last MaxDepth is large
15320 // enough to avoid having to use the fallback below (and protects from
15321 // potential stack exhaustion from recursion).
15322 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15323 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15324 // StartFrom is the previous (or initial) set of leafs reachable at the
15325 // previous maximum depth.
15327 std::swap(StartFrom, Leafs);
15328 for (const SDNode *N : StartFrom)
15329 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15330 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15331 return;
15332 // This should happen very rarely (reached the entry node).
15333 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15334 assert(!Leafs.empty());
15335 }
15336
15337 // This should not happen - but if it did, that means the subgraph reachable
15338 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15339 // could not visit all reachable common operands. Consequently, we were able
15340 // to reach the entry node.
15341 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15342 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15343 // Best-effort fallback if assertions disabled.
15344 SDEI[To] = std::move(NEI);
15345}
15346
15347#ifndef NDEBUG
15348static void checkForCyclesHelper(const SDNode *N,
15351 const llvm::SelectionDAG *DAG) {
15352 // If this node has already been checked, don't check it again.
15353 if (Checked.count(N))
15354 return;
15355
15356 // If a node has already been visited on this depth-first walk, reject it as
15357 // a cycle.
15358 if (!Visited.insert(N).second) {
15359 errs() << "Detected cycle in SelectionDAG\n";
15360 dbgs() << "Offending node:\n";
15361 N->dumprFull(DAG); dbgs() << "\n";
15362 abort();
15363 }
15364
15365 for (const SDValue &Op : N->op_values())
15366 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15367
15368 Checked.insert(N);
15369 Visited.erase(N);
15370}
15371#endif
15372
15374 const llvm::SelectionDAG *DAG,
15375 bool force) {
15376#ifndef NDEBUG
15377 bool check = force;
15378#ifdef EXPENSIVE_CHECKS
15379 check = true;
15380#endif // EXPENSIVE_CHECKS
15381 if (check) {
15382 assert(N && "Checking nonexistent SDNode");
15385 checkForCyclesHelper(N, visited, checked, DAG);
15386 }
15387#endif // !NDEBUG
15388}
15389
15390void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15391 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15392}
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
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.
static Type * getValueType(Value *V, bool LookThroughCmp=false)
Returns the "element type" of the given value/instruction V.
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 void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC, SDVTList VTList, ArrayRef< SDValue > OpList)
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 AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList)
AddNodeIDValueTypes - Value type lists are intern'd so we can represent them solely with their pointe...
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 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)
static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)
AddNodeIDOpcode - Add the node opcode to the NodeID 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 void AddNodeIDOperands(FoldingSetNodeID &ID, ArrayRef< SDValue > Ops)
AddNodeIDOperands - Various routines for adding operands to the NodeID data.
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 void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N)
If this is an SDNode with special info, add this info to the NodeID data.
static bool gluePropagatesDivergence(const SDNode *Node)
Return true if a glue output should propagate divergence information.
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 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:343
static constexpr roundingMode rmTowardZero
Definition APFloat.h:357
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:356
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:353
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:355
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:369
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1216
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1304
void copySign(const APFloat &RHS)
Definition APFloat.h:1398
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5929
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1286
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1277
bool isFinite() const
Definition APFloat.h:1580
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1443
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1295
bool isZero() const
Definition APFloat.h:1571
LLVM_READONLY bool isOne() const
Definition APFloat.h:1653
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1234
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1428
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1194
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1322
bool isPosZero() const
Definition APFloat.h:1586
bool isNegZero() const
Definition APFloat.h:1587
void changeSign()
Definition APFloat.h:1393
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1205
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2006
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2090
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1431
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1695
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1076
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
APInt abs() const
Get the absolute value.
Definition APInt.h:1820
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2061
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:259
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1670
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1197
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:790
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:841
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1175
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1664
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1653
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1623
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:652
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2121
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2135
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1084
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:555
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1184
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:398
unsigned logBase2() const
Definition APInt.h:1786
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2071
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1300
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1771
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1392
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:768
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1442
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:483
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:865
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2080
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
This is an SDNode representing atomic operations.
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
const char * getSymbol() const
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:208
void AddInteger(signed I)
Definition FoldingSet.h:237
void AddPointer(const void *Ptr)
Add* - Add various data types to Bit data.
Definition FoldingSet.h:228
Data structure describing the variable locations in a function.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:688
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:328
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
Tracks which library functions to use for a particular subtarget.
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
static MVT getIntegerVT(unsigned BitWidth)
Abstract base class for all machine specific constantpool value subclasses.
virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID)=0
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
A description of a memory reference used in the backend.
const MDNode * getRanges() const
Return the range tag for the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
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 MSCATTER 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.
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.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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.
ArrayRef< SDUse > ops() const
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
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
LLVM_ABI void Profile(FoldingSetNodeID &ID) const
Gather unique data for the node.
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 getVPZeroExtendInReg(SDValue Op, SDValue Mask, SDValue EVL, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
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 AAMDNodes &AAInfo=AAMDNodes())
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 getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS)
Return an AddrSpaceCastSDNode.
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 getBitcastedSExtOrTrunc(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 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.
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 SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands,...
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 getBitcastedZExtOrTrunc(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 SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask, SDValue EVL)
Convert a vector-predicated Op, which must be an integer vector, to the vector-type VT,...
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI bool isEqualTo(SDValue A, SDValue B) const
Test whether two SDValues are known to compare equal.
static constexpr unsigned MaxRecursionDepth
LLVM_ABI 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 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 getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
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 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 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 getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
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.
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 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 getVPLogicalNOT(const SDLoc &DL, SDValue Val, SDValue Mask, SDValue EVL, EVT VT)
Create a vector-predicated logical NOT operation as (VP_XOR Val, BooleanOne, Mask,...
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 getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask, SDValue EVL)
Convert a vector-predicated Op, which must be of integer type, to the vector-type integer type VT,...
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 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:721
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:343
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:36
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.multiplyCoefficientBy(X) will result in a value whos...
Definition TypeSize.h:269
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:3232
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3162
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3149
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3139
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3242
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3213
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3154
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:3222
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3252
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2299
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3204
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:3040
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3237
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2304
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3134
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3144
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.
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...
@ 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
@ 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
@ 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.
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.
bool matchUnaryPredicateImpl(SDValue Op, 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...
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 matchBinaryPredicate(SDValue LHS, SDValue RHS, 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...
LLVM_ABI bool isVPReduction(unsigned Opcode)
Whether this is a vector-predicated reduction opcode.
bool matchUnaryPredicate(SDValue Op, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
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.
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)
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:345
@ Offset
Definition DWP.cpp:578
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:1793
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:1705
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:1748
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:332
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
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:1779
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 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
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:1729
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
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...
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:573
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...
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:1766
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1806
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:374
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.
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.
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)