LLVM 24.0.0git
SelectionDAG.cpp
Go to the documentation of this file.
1//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the SelectionDAG class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/APSInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Twine.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/GlobalValue.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Type.h"
65#include "llvm/Support/Debug.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <cstdlib>
79#include <limits>
80#include <optional>
81#include <string>
82#include <utility>
83#include <vector>
84
85using namespace llvm;
86using namespace llvm::SDPatternMatch;
87
88/// makeVTList - Return an instance of the SDVTList struct initialized with the
89/// specified members.
90static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
91 SDVTList Res = {VTs, NumVTs};
92 return Res;
93}
94
95// Default null implementations of the callbacks.
99
100void SelectionDAG::DAGNodeDeletedListener::anchor() {}
101void SelectionDAG::DAGNodeInsertedListener::anchor() {}
102
103#define DEBUG_TYPE "selectiondag"
104
105static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
106 cl::Hidden, cl::init(true),
107 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
108
109static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
110 cl::desc("Number limit for gluing ld/st of memcpy."),
111 cl::Hidden, cl::init(0));
112
114 MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192),
115 cl::desc("DAG combiner limit number of steps when searching DAG "
116 "for predecessor nodes"));
117
119 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
120}
121
123
124//===----------------------------------------------------------------------===//
125// ConstantFPSDNode Class
126//===----------------------------------------------------------------------===//
127
128/// isExactlyValue - We don't rely on operator== working on double values, as
129/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
130/// As such, this method can be used to do an exact bit-for-bit comparison of
131/// two floating point values.
133 return getValueAPF().bitwiseIsEqual(V);
134}
135
137 const APFloat& Val) {
138 assert(VT.isFloatingPoint() && "Can only convert between FP types");
139
140 // convert modifies in place, so make a copy.
141 APFloat Val2 = APFloat(Val);
142 bool losesInfo;
144 &losesInfo);
145 return !losesInfo;
146}
147
148//===----------------------------------------------------------------------===//
149// ISD Namespace
150//===----------------------------------------------------------------------===//
151
152bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
153 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
154 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
155 unsigned EltSize =
156 N->getValueType(0).getVectorElementType().getSizeInBits();
157 SplatVal = OptAPInt->trunc(EltSize);
158 return true;
159 }
160 }
161
162 auto *BV = dyn_cast<BuildVectorSDNode>(N);
163 if (!BV)
164 return false;
165
166 APInt SplatUndef;
167 unsigned SplatBitSize;
168 bool HasUndefs;
169 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
170 // Endianness does not matter here. We are checking for a splat given the
171 // element size of the vector, and if we find such a splat for little endian
172 // layout, then that should be valid also for big endian (as the full vector
173 // size is known to be a multiple of the element size).
174 const bool IsBigEndian = false;
175 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
176 EltSize, IsBigEndian) &&
177 EltSize == SplatBitSize;
178}
179
180// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
181// specializations of the more general isConstantSplatVector()?
182
183bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
184 // Look through a bit convert.
185 while (N->getOpcode() == ISD::BITCAST)
186 N = N->getOperand(0).getNode();
187
188 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
189 APInt SplatVal;
190 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
191 }
192
193 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
194
195 unsigned i = 0, e = N->getNumOperands();
196
197 // Skip over all of the undef values.
198 while (i != e && N->getOperand(i).isUndef())
199 ++i;
200
201 // Do not accept an all-undef vector.
202 if (i == e) return false;
203
204 // Do not accept build_vectors that aren't all constants or which have non-~0
205 // elements. We have to be a bit careful here, as the type of the constant
206 // may not be the same as the type of the vector elements due to type
207 // legalization (the elements are promoted to a legal type for the target and
208 // a vector of a type may be legal when the base element type is not).
209 // We only want to check enough bits to cover the vector elements, because
210 // we care if the resultant vector is all ones, not whether the individual
211 // constants are.
212 SDValue NotZero = N->getOperand(i);
213 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
214 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
215 if (OptAPInt->countr_one() < EltSize)
216 return false;
217 } else
218 return false;
219
220 // Okay, we have at least one ~0 value, check to see if the rest match or are
221 // undefs. Even with the above element type twiddling, this should be OK, as
222 // the same type legalization should have applied to all the elements.
223 for (++i; i != e; ++i)
224 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
225 return false;
226 return true;
227}
228
229bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
230 // Look through a bit convert.
231 while (N->getOpcode() == ISD::BITCAST)
232 N = N->getOperand(0).getNode();
233
234 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
235 APInt SplatVal;
236 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
237 }
238
239 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
240
241 bool IsAllUndef = true;
242 for (const SDValue &Op : N->op_values()) {
243 if (Op.isUndef())
244 continue;
245 IsAllUndef = false;
246 // Do not accept build_vectors that aren't all constants or which have non-0
247 // elements. We have to be a bit careful here, as the type of the constant
248 // may not be the same as the type of the vector elements due to type
249 // legalization (the elements are promoted to a legal type for the target
250 // and a vector of a type may be legal when the base element type is not).
251 // We only want to check enough bits to cover the vector elements, because
252 // we care if the resultant vector is all zeros, not whether the individual
253 // constants are.
254 if (auto OptAPInt = Op->bitcastToAPInt()) {
255 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
256 if (OptAPInt->countr_zero() < EltSize)
257 return false;
258 } else
259 return false;
260 }
261
262 // Do not accept an all-undef vector.
263 if (IsAllUndef)
264 return false;
265 return true;
266}
267
269 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
270}
271
273 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
274}
275
277 if (N->getOpcode() != ISD::BUILD_VECTOR)
278 return false;
279
280 for (const SDValue &Op : N->op_values()) {
281 if (Op.isUndef())
282 continue;
284 return false;
285 }
286 return true;
287}
288
290 if (N->getOpcode() != ISD::BUILD_VECTOR)
291 return false;
292
293 for (const SDValue &Op : N->op_values()) {
294 if (Op.isUndef())
295 continue;
297 return false;
298 }
299 return true;
300}
301
302bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
303 bool Signed) {
304 assert(N->getValueType(0).isVector() && "Expected a vector!");
305
306 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
307 if (EltSize <= NewEltSize)
308 return false;
309
310 if (N->getOpcode() == ISD::ZERO_EXTEND) {
311 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
312 NewEltSize) &&
313 !Signed;
314 }
315 if (N->getOpcode() == ISD::SIGN_EXTEND) {
316 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
317 NewEltSize) &&
318 Signed;
319 }
320 if (N->getOpcode() != ISD::BUILD_VECTOR)
321 return false;
322
323 for (const SDValue &Op : N->op_values()) {
324 if (Op.isUndef())
325 continue;
327 return false;
328
329 APInt C = Op->getAsAPIntVal().trunc(EltSize);
330 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
331 return false;
332 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
333 return false;
334 }
335
336 return true;
337}
338
340 // Return false if the node has no operands.
341 // This is "logically inconsistent" with the definition of "all" but
342 // is probably the desired behavior.
343 if (N->getNumOperands() == 0)
344 return false;
345 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
346}
347
349 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
350}
351
352template <typename ConstNodeType>
354 std::function<bool(ConstNodeType *)> Match,
355 bool AllowUndefs, bool AllowTruncation) {
356 // FIXME: Add support for scalar UNDEF cases?
357 if (auto *C = dyn_cast<ConstNodeType>(Op))
358 return Match(C);
359
360 // FIXME: Add support for vector UNDEF cases?
361 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
362 ISD::SPLAT_VECTOR != Op.getOpcode())
363 return false;
364
365 EVT SVT = Op.getValueType().getScalarType();
366 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
367 if (AllowUndefs && Op.getOperand(i).isUndef()) {
368 if (!Match(nullptr))
369 return false;
370 continue;
371 }
372
373 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
374 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
375 !Match(Cst))
376 return false;
377 }
378 return true;
379}
380// Build used template types.
382 SDValue, std::function<bool(ConstantSDNode *)>, bool, bool);
384 SDValue, std::function<bool(ConstantFPSDNode *)>, bool, bool);
385
387 SDValue LHS, SDValue RHS,
388 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
389 bool AllowUndefs, bool AllowTypeMismatch) {
390 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
391 return false;
392
393 // TODO: Add support for scalar UNDEF cases?
394 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
395 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
396 return Match(LHSCst, RHSCst);
397
398 // TODO: Add support for vector UNDEF cases?
399 if (LHS.getOpcode() != RHS.getOpcode() ||
400 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
401 LHS.getOpcode() != ISD::SPLAT_VECTOR))
402 return false;
403
404 EVT SVT = LHS.getValueType().getScalarType();
405 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
406 SDValue LHSOp = LHS.getOperand(i);
407 SDValue RHSOp = RHS.getOperand(i);
408 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
409 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
410 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
411 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
412 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
413 return false;
414 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
415 LHSOp.getValueType() != RHSOp.getValueType()))
416 return false;
417 if (!Match(LHSCst, RHSCst))
418 return false;
419 }
420 return true;
421}
422
424 switch (MinMaxOpc) {
425 default:
426 llvm_unreachable("unrecognized opcode");
427 case ISD::UMIN:
428 return ISD::UMAX;
429 case ISD::UMAX:
430 return ISD::UMIN;
431 case ISD::SMIN:
432 return ISD::SMAX;
433 case ISD::SMAX:
434 return ISD::SMIN;
435 }
436}
437
439 switch (MinMaxOpc) {
440 default:
441 llvm_unreachable("unrecognized min/max opcode");
442 case ISD::SMIN:
443 return ISD::UMIN;
444 case ISD::SMAX:
445 return ISD::UMAX;
446 case ISD::UMIN:
447 return ISD::SMIN;
448 case ISD::UMAX:
449 return ISD::SMAX;
450 }
451}
452
454 switch (VecReduceOpcode) {
455 default:
456 llvm_unreachable("Expected VECREDUCE opcode");
459 case ISD::VP_REDUCE_FADD:
460 case ISD::VP_REDUCE_SEQ_FADD:
461 return ISD::FADD;
464 case ISD::VP_REDUCE_FMUL:
465 case ISD::VP_REDUCE_SEQ_FMUL:
466 return ISD::FMUL;
468 case ISD::VP_REDUCE_ADD:
469 return ISD::ADD;
471 case ISD::VP_REDUCE_MUL:
472 return ISD::MUL;
474 case ISD::VP_REDUCE_AND:
475 return ISD::AND;
477 case ISD::VP_REDUCE_OR:
478 return ISD::OR;
480 case ISD::VP_REDUCE_XOR:
481 return ISD::XOR;
483 case ISD::VP_REDUCE_SMAX:
484 return ISD::SMAX;
486 case ISD::VP_REDUCE_SMIN:
487 return ISD::SMIN;
489 case ISD::VP_REDUCE_UMAX:
490 return ISD::UMAX;
492 case ISD::VP_REDUCE_UMIN:
493 return ISD::UMIN;
495 case ISD::VP_REDUCE_FMAX:
496 return ISD::FMAXNUM;
498 case ISD::VP_REDUCE_FMIN:
499 return ISD::FMINNUM;
501 case ISD::VP_REDUCE_FMAXIMUM:
502 return ISD::FMAXIMUM;
504 case ISD::VP_REDUCE_FMINIMUM:
505 return ISD::FMINIMUM;
506 }
507}
508
510 switch (MaskedOpc) {
511 case ISD::MASKED_UDIV:
512 return ISD::UDIV;
513 case ISD::MASKED_SDIV:
514 return ISD::SDIV;
515 case ISD::MASKED_UREM:
516 return ISD::UREM;
517 case ISD::MASKED_SREM:
518 return ISD::SREM;
519 default:
520 llvm_unreachable("Expected masked binop opcode");
521 }
522}
523
524bool ISD::isVPOpcode(unsigned Opcode) {
525 switch (Opcode) {
526 default:
527 return false;
528#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
529 case ISD::VPSD: \
530 return true;
531#include "llvm/IR/VPIntrinsics.def"
532 }
533}
534
535bool ISD::isVPBinaryOp(unsigned Opcode) {
536 switch (Opcode) {
537 default:
538 break;
539#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
540#define VP_PROPERTY_BINARYOP return true;
541#define END_REGISTER_VP_SDNODE(VPSD) break;
542#include "llvm/IR/VPIntrinsics.def"
543 }
544 return false;
545}
546
547bool ISD::isVPReduction(unsigned Opcode) {
548 switch (Opcode) {
549 default:
550 return false;
551 case ISD::VP_REDUCE_ADD:
552 case ISD::VP_REDUCE_MUL:
553 case ISD::VP_REDUCE_AND:
554 case ISD::VP_REDUCE_OR:
555 case ISD::VP_REDUCE_XOR:
556 case ISD::VP_REDUCE_SMAX:
557 case ISD::VP_REDUCE_SMIN:
558 case ISD::VP_REDUCE_UMAX:
559 case ISD::VP_REDUCE_UMIN:
560 case ISD::VP_REDUCE_FMAX:
561 case ISD::VP_REDUCE_FMIN:
562 case ISD::VP_REDUCE_FMAXIMUM:
563 case ISD::VP_REDUCE_FMINIMUM:
564 case ISD::VP_REDUCE_FADD:
565 case ISD::VP_REDUCE_FMUL:
566 case ISD::VP_REDUCE_SEQ_FADD:
567 case ISD::VP_REDUCE_SEQ_FMUL:
568 return true;
569 }
570}
571
572/// The operand position of the vector mask.
573std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
574 switch (Opcode) {
575 default:
576 return std::nullopt;
577#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
578 case ISD::VPSD: \
579 return MASKPOS;
580#include "llvm/IR/VPIntrinsics.def"
581 }
582}
583
584/// The operand position of the explicit vector length parameter.
585std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
586 switch (Opcode) {
587 default:
588 return std::nullopt;
589#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
590 case ISD::VPSD: \
591 return EVLPOS;
592#include "llvm/IR/VPIntrinsics.def"
593 }
594}
595
596std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
597 bool hasFPExcept) {
598 // FIXME: Return strict opcodes in case of fp exceptions.
599 switch (VPOpcode) {
600 default:
601 return std::nullopt;
602#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
603#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
604#define END_REGISTER_VP_SDNODE(VPOPC) break;
605#include "llvm/IR/VPIntrinsics.def"
606 }
607 return std::nullopt;
608}
609
610std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
611 switch (Opcode) {
612 default:
613 return std::nullopt;
614#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
615#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
616#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
617#include "llvm/IR/VPIntrinsics.def"
618 }
619}
620
622 switch (ExtType) {
623 case ISD::EXTLOAD:
624 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
625 case ISD::SEXTLOAD:
626 return ISD::SIGN_EXTEND;
627 case ISD::ZEXTLOAD:
628 return ISD::ZERO_EXTEND;
629 default:
630 break;
631 }
632
633 llvm_unreachable("Invalid LoadExtType");
634}
635
637 // To perform this operation, we just need to swap the L and G bits of the
638 // operation.
639 unsigned OldL = (Operation >> 2) & 1;
640 unsigned OldG = (Operation >> 1) & 1;
641 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
642 (OldL << 1) | // New G bit
643 (OldG << 2)); // New L bit.
644}
645
647 unsigned Operation = Op;
648 if (isIntegerLike)
649 Operation ^= 7; // Flip L, G, E bits, but not U.
650 else
651 Operation ^= 15; // Flip all of the condition bits.
652
654 Operation &= ~8; // Don't let N and U bits get set.
655
656 return ISD::CondCode(Operation);
657}
658
662
664 bool isIntegerLike) {
665 return getSetCCInverseImpl(Op, isIntegerLike);
666}
667
668/// For an integer comparison, return 1 if the comparison is a signed operation
669/// and 2 if the result is an unsigned comparison. Return zero if the operation
670/// does not depend on the sign of the input (setne and seteq).
671static int isSignedOp(ISD::CondCode Opcode) {
672 switch (Opcode) {
673 default: llvm_unreachable("Illegal integer setcc operation!");
674 case ISD::SETEQ:
675 case ISD::SETNE: return 0;
676 case ISD::SETLT:
677 case ISD::SETLE:
678 case ISD::SETGT:
679 case ISD::SETGE: return 1;
680 case ISD::SETULT:
681 case ISD::SETULE:
682 case ISD::SETUGT:
683 case ISD::SETUGE: return 2;
684 }
685}
686
688 EVT Type) {
689 bool IsInteger = Type.isInteger();
690 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
691 // Cannot fold a signed integer setcc with an unsigned integer setcc.
692 return ISD::SETCC_INVALID;
693
694 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
695
696 // If the N and U bits get set, then the resultant comparison DOES suddenly
697 // care about orderedness, and it is true when ordered.
698 if (Op > ISD::SETTRUE2)
699 Op &= ~16; // Clear the U bit if the N bit is set.
700
701 // Canonicalize illegal integer setcc's.
702 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
703 Op = ISD::SETNE;
704
705 return ISD::CondCode(Op);
706}
707
709 EVT Type) {
710 bool IsInteger = Type.isInteger();
711 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
712 // Cannot fold a signed setcc with an unsigned setcc.
713 return ISD::SETCC_INVALID;
714
715 // Combine all of the condition bits.
716 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
717
718 // Canonicalize illegal integer setcc's.
719 if (IsInteger) {
720 switch (Result) {
721 default: break;
722 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
723 case ISD::SETOEQ: // SETEQ & SETU[LG]E
724 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
725 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
726 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
727 }
728 }
729
730 return Result;
731}
732
733//===----------------------------------------------------------------------===//
734// SDNode Profile Support
735//===----------------------------------------------------------------------===//
736
737/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
738static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
739 ID.AddInteger(OpC);
740}
741
742/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
743/// solely with their pointer.
745 ID.AddPointer(VTList.VTs);
746}
747
748/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
751 for (const auto &Op : Ops) {
752 ID.AddPointer(Op.getNode());
753 ID.AddInteger(Op.getResNo());
754 }
755}
756
757/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
760 for (const auto &Op : Ops) {
761 ID.AddPointer(Op.getNode());
762 ID.AddInteger(Op.getResNo());
763 }
764}
765
766static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
767 SDVTList VTList, ArrayRef<SDValue> OpList) {
768 AddNodeIDOpcode(ID, OpC);
769 AddNodeIDValueTypes(ID, VTList);
770 AddNodeIDOperands(ID, OpList);
771}
772
773/// If this is an SDNode with special info, add this info to the NodeID data.
774static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
775 switch (N->getOpcode()) {
778 case ISD::MCSymbol:
779 llvm_unreachable("Should only be used on nodes with operands");
780 default: break; // Normal nodes don't need extra info.
782 case ISD::Constant: {
784 ID.AddPointer(C->getConstantIntValue());
785 ID.AddBoolean(C->isOpaque());
786 break;
787 }
789 case ISD::ConstantFP:
790 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
791 break;
797 ID.AddPointer(GA->getGlobal());
798 ID.AddInteger(GA->getOffset());
799 ID.AddInteger(GA->getTargetFlags());
800 break;
801 }
802 case ISD::BasicBlock:
803 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
804 break;
805 case ISD::Register:
806 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
807 break;
809 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
810 break;
811 case ISD::SRCVALUE:
812 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
813 break;
814 case ISD::FrameIndex:
816 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
817 break;
819 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
820 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
821 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
822 break;
823 case ISD::JumpTable:
825 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
826 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
827 break;
831 ID.AddInteger(CP->getAlign().value());
832 ID.AddInteger(CP->getOffset());
835 else
836 ID.AddPointer(CP->getConstVal());
837 ID.AddInteger(CP->getTargetFlags());
838 break;
839 }
840 case ISD::TargetIndex: {
842 ID.AddInteger(TI->getIndex());
843 ID.AddInteger(TI->getOffset());
844 ID.AddInteger(TI->getTargetFlags());
845 break;
846 }
847 case ISD::LOAD: {
848 const LoadSDNode *LD = cast<LoadSDNode>(N);
849 ID.AddInteger(LD->getMemoryVT().getRawBits());
850 ID.AddInteger(LD->getRawSubclassData());
851 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
852 ID.AddInteger(LD->getMemOperand()->getFlags());
853 break;
854 }
855 case ISD::STORE: {
856 const StoreSDNode *ST = cast<StoreSDNode>(N);
857 ID.AddInteger(ST->getMemoryVT().getRawBits());
858 ID.AddInteger(ST->getRawSubclassData());
859 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
860 ID.AddInteger(ST->getMemOperand()->getFlags());
861 break;
862 }
863 case ISD::VP_LOAD: {
864 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
865 ID.AddInteger(ELD->getMemoryVT().getRawBits());
866 ID.AddInteger(ELD->getRawSubclassData());
867 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
868 ID.AddInteger(ELD->getMemOperand()->getFlags());
869 break;
870 }
871 case ISD::VP_LOAD_FF: {
872 const auto *LD = cast<VPLoadFFSDNode>(N);
873 ID.AddInteger(LD->getMemoryVT().getRawBits());
874 ID.AddInteger(LD->getRawSubclassData());
875 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
876 ID.AddInteger(LD->getMemOperand()->getFlags());
877 break;
878 }
879 case ISD::VP_STORE: {
880 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
881 ID.AddInteger(EST->getMemoryVT().getRawBits());
882 ID.AddInteger(EST->getRawSubclassData());
883 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
884 ID.AddInteger(EST->getMemOperand()->getFlags());
885 break;
886 }
887 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
889 ID.AddInteger(SLD->getMemoryVT().getRawBits());
890 ID.AddInteger(SLD->getRawSubclassData());
891 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
892 break;
893 }
894 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
896 ID.AddInteger(SST->getMemoryVT().getRawBits());
897 ID.AddInteger(SST->getRawSubclassData());
898 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
899 break;
900 }
901 case ISD::VP_GATHER: {
903 ID.AddInteger(EG->getMemoryVT().getRawBits());
904 ID.AddInteger(EG->getRawSubclassData());
905 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
906 ID.AddInteger(EG->getMemOperand()->getFlags());
907 break;
908 }
909 case ISD::VP_SCATTER: {
911 ID.AddInteger(ES->getMemoryVT().getRawBits());
912 ID.AddInteger(ES->getRawSubclassData());
913 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
914 ID.AddInteger(ES->getMemOperand()->getFlags());
915 break;
916 }
917 case ISD::MLOAD: {
919 ID.AddInteger(MLD->getMemoryVT().getRawBits());
920 ID.AddInteger(MLD->getRawSubclassData());
921 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
922 ID.AddInteger(MLD->getMemOperand()->getFlags());
923 break;
924 }
925 case ISD::MSTORE: {
927 ID.AddInteger(MST->getMemoryVT().getRawBits());
928 ID.AddInteger(MST->getRawSubclassData());
929 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
930 ID.AddInteger(MST->getMemOperand()->getFlags());
931 break;
932 }
933 case ISD::MGATHER: {
935 ID.AddInteger(MG->getMemoryVT().getRawBits());
936 ID.AddInteger(MG->getRawSubclassData());
937 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
938 ID.AddInteger(MG->getMemOperand()->getFlags());
939 break;
940 }
941 case ISD::MSCATTER: {
943 ID.AddInteger(MS->getMemoryVT().getRawBits());
944 ID.AddInteger(MS->getRawSubclassData());
945 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
946 ID.AddInteger(MS->getMemOperand()->getFlags());
947 break;
948 }
951 case ISD::ATOMIC_SWAP:
963 case ISD::ATOMIC_LOAD:
964 case ISD::ATOMIC_STORE: {
965 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
966 ID.AddInteger(AT->getMemoryVT().getRawBits());
967 ID.AddInteger(AT->getRawSubclassData());
968 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
969 ID.AddInteger(AT->getMemOperand()->getFlags());
970 break;
971 }
972 case ISD::VECTOR_SHUFFLE: {
973 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
974 for (int M : Mask)
975 ID.AddInteger(M);
976 break;
977 }
978 case ISD::ADDRSPACECAST: {
980 ID.AddInteger(ASC->getSrcAddressSpace());
981 ID.AddInteger(ASC->getDestAddressSpace());
982 break;
983 }
985 case ISD::BlockAddress: {
987 ID.AddPointer(BA->getBlockAddress());
988 ID.AddInteger(BA->getOffset());
989 ID.AddInteger(BA->getTargetFlags());
990 break;
991 }
992 case ISD::AssertAlign:
993 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
994 break;
995 case ISD::PREFETCH:
998 // Handled by MemIntrinsicSDNode check after the switch.
999 break;
1000 case ISD::MDNODE_SDNODE:
1001 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
1002 break;
1003 } // end switch (N->getOpcode())
1004
1005 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
1006 // to check.
1007 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
1008 ID.AddInteger(MN->getRawSubclassData());
1009 ID.AddInteger(MN->getMemoryVT().getRawBits());
1010 for (const MachineMemOperand *MMO : MN->memoperands()) {
1011 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1012 ID.AddInteger(MMO->getFlags());
1013 }
1014 }
1015}
1016
1017/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
1018/// data.
1019static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1020 AddNodeIDOpcode(ID, N->getOpcode());
1021 // Add the return value info.
1022 AddNodeIDValueTypes(ID, N->getVTList());
1023 // Add the operand info.
1024 AddNodeIDOperands(ID, N->ops());
1025
1026 // Handle SDNode leafs with special info.
1027 AddNodeIDCustom(ID, N);
1028}
1029
1030//===----------------------------------------------------------------------===//
1031// SelectionDAG Class
1032//===----------------------------------------------------------------------===//
1033
1034/// doNotCSE - Return true if CSE should not be performed for this node.
1035static bool doNotCSE(SDNode *N) {
1036 if (N->getValueType(0) == MVT::Glue)
1037 return true; // Never CSE anything that produces a glue result.
1038
1039 switch (N->getOpcode()) {
1040 default: break;
1041 case ISD::HANDLENODE:
1042 case ISD::EH_LABEL:
1043 return true; // Never CSE these nodes.
1044 }
1045
1046 // Check that remaining values produced are not flags.
1047 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1048 if (N->getValueType(i) == MVT::Glue)
1049 return true; // Never CSE anything that produces a glue result.
1050
1051 return false;
1052}
1053
1054/// Construct a DemandedElts mask which demands all elements of \p V.
1055/// If \p V is not a fixed-length vector, then this will return a single bit.
1057 EVT VT = V.getValueType();
1058 // Since the number of lanes in a scalable vector is unknown at compile time,
1059 // we track one bit which is implicitly broadcast to all lanes. This means
1060 // that all lanes in a scalable vector are considered demanded.
1062 : APInt(1, 1);
1063}
1064
1065/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1066/// SelectionDAG.
1068 // Create a dummy node (which is not added to allnodes), that adds a reference
1069 // to the root node, preventing it from being deleted.
1070 HandleSDNode Dummy(getRoot());
1071
1072 SmallVector<SDNode*, 128> DeadNodes;
1073
1074 // Add all obviously-dead nodes to the DeadNodes worklist.
1075 for (SDNode &Node : allnodes())
1076 if (Node.use_empty())
1077 DeadNodes.push_back(&Node);
1078
1079 RemoveDeadNodes(DeadNodes);
1080
1081 // If the root changed (e.g. it was a dead load, update the root).
1082 setRoot(Dummy.getValue());
1083}
1084
1085/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1086/// given list, and any nodes that become unreachable as a result.
1088
1089 // Process the worklist, deleting the nodes and adding their uses to the
1090 // worklist.
1091 while (!DeadNodes.empty()) {
1092 SDNode *N = DeadNodes.pop_back_val();
1093 // Skip to next node if we've already managed to delete the node. This could
1094 // happen if replacing a node causes a node previously added to the node to
1095 // be deleted.
1096 if (N->getOpcode() == ISD::DELETED_NODE)
1097 continue;
1098
1099 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1100 DUL->NodeDeleted(N, nullptr);
1101
1102 // Take the node out of the appropriate CSE map.
1103 RemoveNodeFromCSEMaps(N);
1104
1105 // Next, brutally remove the operand list. This is safe to do, as there are
1106 // no cycles in the graph.
1107 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1108 SDUse &Use = *I++;
1109 SDNode *Operand = Use.getNode();
1110 Use.set(SDValue());
1111
1112 // Now that we removed this operand, see if there are no uses of it left.
1113 if (Operand->use_empty())
1114 DeadNodes.push_back(Operand);
1115 }
1116
1117 DeallocateNode(N);
1118 }
1119}
1120
1122 SmallVector<SDNode*, 16> DeadNodes(1, N);
1123
1124 // Create a dummy node that adds a reference to the root node, preventing
1125 // it from being deleted. (This matters if the root is an operand of the
1126 // dead node.)
1127 HandleSDNode Dummy(getRoot());
1128
1129 RemoveDeadNodes(DeadNodes);
1130}
1131
1133 // First take this out of the appropriate CSE map.
1134 RemoveNodeFromCSEMaps(N);
1135
1136 // Finally, remove uses due to operands of this node, remove from the
1137 // AllNodes list, and delete the node.
1138 DeleteNodeNotInCSEMaps(N);
1139}
1140
1141void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1142 assert(N->getIterator() != AllNodes.begin() &&
1143 "Cannot delete the entry node!");
1144 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1145
1146 // Drop all of the operands and decrement used node's use counts.
1147 N->DropOperands();
1148
1149 DeallocateNode(N);
1150}
1151
1152void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1153 assert(!(V->isVariadic() && isParameter));
1154 if (isParameter)
1155 ByvalParmDbgValues.push_back(V);
1156 else
1157 DbgValues.push_back(V);
1158 for (const SDNode *Node : V->getSDNodes())
1159 if (Node)
1160 DbgValMap[Node].push_back(V);
1161}
1162
1164 DbgValMapType::iterator I = DbgValMap.find(Node);
1165 if (I == DbgValMap.end())
1166 return;
1167 for (auto &Val: I->second)
1168 Val->setIsInvalidated();
1169 DbgValMap.erase(I);
1170}
1171
1172void SelectionDAG::DeallocateNode(SDNode *N) {
1173 // If we have operands, deallocate them.
1175
1176 NodeAllocator.Deallocate(AllNodes.remove(N));
1177
1178 // Set the opcode to DELETED_NODE to help catch bugs when node
1179 // memory is reallocated.
1180 // FIXME: There are places in SDag that have grown a dependency on the opcode
1181 // value in the released node.
1182 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1183 N->NodeType = ISD::DELETED_NODE;
1184
1185 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1186 // them and forget about that node.
1187 DbgInfo->erase(N);
1188
1189 // Invalidate extra info.
1190 SDEI.erase(N);
1191}
1192
1193#ifndef NDEBUG
1194/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1195void SelectionDAG::verifyNode(SDNode *N) const {
1196 switch (N->getOpcode()) {
1197 default:
1198 if (N->isTargetOpcode())
1200 break;
1201 case ISD::BUILD_PAIR: {
1202 EVT VT = N->getValueType(0);
1203 assert(N->getNumValues() == 1 && "Too many results!");
1204 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1205 "Wrong return type!");
1206 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1207 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1208 "Mismatched operand types!");
1209 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1210 "Wrong operand type!");
1211 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1212 "Wrong return type size");
1213 break;
1214 }
1215 case ISD::BUILD_VECTOR: {
1216 assert(N->getNumValues() == 1 && "Too many results!");
1217 assert(N->getValueType(0).isVector() && "Wrong return type!");
1218 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1219 "Wrong number of operands!");
1220 EVT EltVT = N->getValueType(0).getVectorElementType();
1221 for (const SDUse &Op : N->ops()) {
1222 assert((Op.getValueType() == EltVT ||
1223 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1224 EltVT.bitsLE(Op.getValueType()))) &&
1225 "Wrong operand type!");
1226 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1227 "Operands must all have the same type");
1228 }
1229 break;
1230 }
1231 case ISD::SADDO:
1232 case ISD::UADDO:
1233 case ISD::SSUBO:
1234 case ISD::USUBO:
1235 assert(N->getNumValues() == 2 && "Wrong number of results!");
1236 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1237 "Invalid add/sub overflow op!");
1238 assert(N->getVTList().VTs[0].isInteger() &&
1239 N->getVTList().VTs[1].isInteger() &&
1240 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1241 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1242 "Binary operator types must match!");
1243 break;
1244 }
1245}
1246#endif // NDEBUG
1247
1248/// Insert a newly allocated node into the DAG.
1249///
1250/// Handles insertion into the all nodes list and CSE map, as well as
1251/// verification and other common operations when a new node is allocated.
1252void SelectionDAG::InsertNode(SDNode *N) {
1253 AllNodes.push_back(N);
1254#ifndef NDEBUG
1255 N->PersistentId = NextPersistentId++;
1256 verifyNode(N);
1257#endif
1258 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1259 DUL->NodeInserted(N);
1260}
1261
1262/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1263/// correspond to it. This is useful when we're about to delete or repurpose
1264/// the node. We don't want future request for structurally identical nodes
1265/// to return N anymore.
1266bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1267 bool Erased = false;
1268 switch (N->getOpcode()) {
1269 case ISD::HANDLENODE: return false; // noop.
1270 case ISD::CONDCODE:
1271 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1272 "Cond code doesn't exist!");
1273 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1274 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1275 break;
1277 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1278 break;
1280 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1281 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1282 ESN->getSymbol(), ESN->getTargetFlags()));
1283 break;
1284 }
1285 case ISD::MCSymbol: {
1286 auto *MCSN = cast<MCSymbolSDNode>(N);
1287 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1288 break;
1289 }
1290 case ISD::VALUETYPE: {
1291 EVT VT = cast<VTSDNode>(N)->getVT();
1292 if (VT.isExtended()) {
1293 Erased = ExtendedValueTypeNodes.erase(VT);
1294 } else {
1295 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1296 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1297 }
1298 break;
1299 }
1300 default:
1301 // Remove it from the CSE Map.
1302 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1303 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1304 Erased = CSEMap.RemoveNode(N);
1305 break;
1306 }
1307#ifndef NDEBUG
1308 // Verify that the node was actually in one of the CSE maps, unless it has a
1309 // glue result (which cannot be CSE'd) or is one of the special cases that are
1310 // not subject to CSE.
1311 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1312 !N->isMachineOpcode() && !doNotCSE(N)) {
1313 N->dump(this);
1314 dbgs() << "\n";
1315 llvm_unreachable("Node is not in map!");
1316 }
1317#endif
1318 return Erased;
1319}
1320
1321/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1322/// maps and modified in place. Add it back to the CSE maps, unless an identical
1323/// node already exists, in which case transfer all its users to the existing
1324/// node. This transfer can potentially trigger recursive merging.
1325void
1326SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1327 // For node types that aren't CSE'd, just act as if no identical node
1328 // already exists.
1329 if (!doNotCSE(N)) {
1330 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1331 if (Existing != N) {
1332 // If there was already an existing matching node, use ReplaceAllUsesWith
1333 // to replace the dead one with the existing one. This can cause
1334 // recursive merging of other unrelated nodes down the line.
1335 Existing->intersectFlagsWith(N->getFlags());
1336 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1338 cast<MemSDNode>(N)->memoperands();
1339 // Range and cache hint metadata are not part of the DAG CSE key because
1340 // we prefer to CSE even when metadata does not match. Merge potentially
1341 // differing metadata conservatively.
1342 MemNode->refineMMOMetadata(NewMMOs);
1343 }
1344 ReplaceAllUsesWith(N, Existing);
1345
1346 // N is now dead. Inform the listeners and delete it.
1347 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1348 DUL->NodeDeleted(N, Existing);
1349 DeleteNodeNotInCSEMaps(N);
1350 return;
1351 }
1352 }
1353
1354 // If the node doesn't already exist, we updated it. Inform listeners.
1355 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1356 DUL->NodeUpdated(N);
1357}
1358
1359/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1360/// were replaced with those specified. If this node is never memoized,
1361/// return null, otherwise return a pointer to the slot it would take. If a
1362/// node already exists with these operands, the slot will be non-null.
1363SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1364 void *&InsertPos) {
1365 if (doNotCSE(N))
1366 return nullptr;
1367
1368 SDValue Ops[] = { Op };
1369 FoldingSetNodeID ID;
1370 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1371 AddNodeIDCustom(ID, N);
1372 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1373 if (Node)
1374 Node->intersectFlagsWith(N->getFlags());
1375 return Node;
1376}
1377
1378/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1379/// were replaced with those specified. If this node is never memoized,
1380/// return null, otherwise return a pointer to the slot it would take. If a
1381/// node already exists with these operands, the slot will be non-null.
1382SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1383 SDValue Op1, SDValue Op2,
1384 void *&InsertPos) {
1385 if (doNotCSE(N))
1386 return nullptr;
1387
1388 SDValue Ops[] = { Op1, Op2 };
1389 FoldingSetNodeID ID;
1390 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1391 AddNodeIDCustom(ID, N);
1392 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1393 if (Node)
1394 Node->intersectFlagsWith(N->getFlags());
1395 return Node;
1396}
1397
1398/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1399/// were replaced with those specified. If this node is never memoized,
1400/// return null, otherwise return a pointer to the slot it would take. If a
1401/// node already exists with these operands, the slot will be non-null.
1402SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1403 void *&InsertPos) {
1404 if (doNotCSE(N))
1405 return nullptr;
1406
1407 FoldingSetNodeID ID;
1408 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1409 AddNodeIDCustom(ID, N);
1410 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1411 if (Node)
1412 Node->intersectFlagsWith(N->getFlags());
1413 return Node;
1414}
1415
1417 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1418 : VT.getTypeForEVT(*getContext());
1419
1420 return getDataLayout().getABITypeAlign(Ty);
1421}
1422
1423// EntryNode could meaningfully have debug info if we can find it...
1425 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1426 getVTList(MVT::Other, MVT::Glue)),
1427 Root(getEntryNode()) {
1428 InsertNode(&EntryNode);
1429 DbgInfo = new SDDbgInfo();
1430}
1431
1433 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1434 const TargetLibraryInfo *LibraryInfo,
1435 const LibcallLoweringInfo *LibcallsInfo,
1436 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1438 FunctionVarLocs const *VarLocs) {
1439 MF = &NewMF;
1440 SDAGISelPass = PassPtr;
1441 ORE = &NewORE;
1444 LibInfo = LibraryInfo;
1445 Libcalls = LibcallsInfo;
1446 Context = &MF->getFunction().getContext();
1447 UA = NewUA;
1448 PSI = PSIin;
1449 BFI = BFIin;
1450 MMI = &MMIin;
1451 FnVarLocs = VarLocs;
1452}
1453
1455 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1456 allnodes_clear();
1457 OperandRecycler.clear(OperandAllocator);
1458 delete DbgInfo;
1459}
1460
1462 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1463}
1464
1465void SelectionDAG::allnodes_clear() {
1466 assert(&*AllNodes.begin() == &EntryNode);
1467 AllNodes.remove(AllNodes.begin());
1468 while (!AllNodes.empty())
1469 DeallocateNode(&AllNodes.front());
1470#ifndef NDEBUG
1471 NextPersistentId = 0;
1472#endif
1473}
1474
1475SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1476 void *&InsertPos) {
1477 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1478 if (N) {
1479 switch (N->getOpcode()) {
1480 default: break;
1481 case ISD::Constant:
1482 case ISD::ConstantFP:
1483 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1484 "debug location. Use another overload.");
1485 }
1486 }
1487 return N;
1488}
1489
1490SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1491 const SDLoc &DL, void *&InsertPos) {
1492 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1493 if (N) {
1494 switch (N->getOpcode()) {
1495 case ISD::Constant:
1496 case ISD::ConstantFP:
1497 // Erase debug location from the node if the node is used at several
1498 // different places. Do not propagate one location to all uses as it
1499 // will cause a worse single stepping debugging experience.
1500 if (N->getDebugLoc() != DL.getDebugLoc())
1501 N->setDebugLoc(DebugLoc());
1502 break;
1503 default:
1504 // When the node's point of use is located earlier in the instruction
1505 // sequence than its prior point of use, update its debug info to the
1506 // earlier location.
1507 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1508 N->setDebugLoc(DL.getDebugLoc());
1509 break;
1510 }
1511 }
1512 return N;
1513}
1514
1516 allnodes_clear();
1517 OperandRecycler.clear(OperandAllocator);
1518 OperandAllocator.Reset();
1519 CSEMap.clear();
1520
1521 ExtendedValueTypeNodes.clear();
1522 ExternalSymbols.clear();
1523 TargetExternalSymbols.clear();
1524 MCSymbols.clear();
1525 SDEI.clear();
1526 llvm::fill(CondCodeNodes, nullptr);
1527 llvm::fill(ValueTypeNodes, nullptr);
1528
1529 EntryNode.UseList = nullptr;
1530 InsertNode(&EntryNode);
1531 Root = getEntryNode();
1532 DbgInfo->clear();
1533}
1534
1536 return VT.bitsGT(Op.getValueType())
1537 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1538 : getNode(ISD::FP_ROUND, DL, VT, Op,
1539 getIntPtrConstant(0, DL, /*isTarget=*/true));
1540}
1541
1542std::pair<SDValue, SDValue>
1544 const SDLoc &DL, EVT VT) {
1545 assert(!VT.bitsEq(Op.getValueType()) &&
1546 "Strict no-op FP extend/round not allowed.");
1547 SDValue Res =
1548 VT.bitsGT(Op.getValueType())
1549 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1550 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1551 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1552
1553 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1554}
1555
1557 return VT.bitsGT(Op.getValueType()) ?
1558 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1559 getNode(ISD::TRUNCATE, DL, VT, Op);
1560}
1561
1563 return VT.bitsGT(Op.getValueType()) ?
1564 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1565 getNode(ISD::TRUNCATE, DL, VT, Op);
1566}
1567
1569 return VT.bitsGT(Op.getValueType()) ?
1570 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1571 getNode(ISD::TRUNCATE, DL, VT, Op);
1572}
1573
1575 EVT VT) {
1576 assert(!VT.isVector());
1577 auto Type = Op.getValueType();
1578 SDValue DestOp;
1579 if (Type == VT)
1580 return Op;
1581 auto Size = Op.getValueSizeInBits();
1582 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1583 if (DestOp.getValueType() == VT)
1584 return DestOp;
1585
1586 return getAnyExtOrTrunc(DestOp, DL, VT);
1587}
1588
1590 EVT VT) {
1591 assert(!VT.isVector());
1592 auto Type = Op.getValueType();
1593 SDValue DestOp;
1594 if (Type == VT)
1595 return Op;
1596 auto Size = Op.getValueSizeInBits();
1597 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1598 if (DestOp.getValueType() == VT)
1599 return DestOp;
1600
1601 return getSExtOrTrunc(DestOp, DL, VT);
1602}
1603
1605 EVT VT) {
1606 assert(!VT.isVector());
1607 auto Type = Op.getValueType();
1608 SDValue DestOp;
1609 if (Type == VT)
1610 return Op;
1611 auto Size = Op.getValueSizeInBits();
1612 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1613 if (DestOp.getValueType() == VT)
1614 return DestOp;
1615
1616 return getZExtOrTrunc(DestOp, DL, VT);
1617}
1618
1620 EVT OpVT) {
1621 if (VT.bitsLE(Op.getValueType()))
1622 return getNode(ISD::TRUNCATE, SL, VT, Op);
1623
1624 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1625 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1626}
1627
1629 EVT OpVT = Op.getValueType();
1630 assert(VT.isInteger() && OpVT.isInteger() &&
1631 "Cannot getZeroExtendInReg FP types");
1632 assert(VT.isVector() == OpVT.isVector() &&
1633 "getZeroExtendInReg type should be vector iff the operand "
1634 "type is vector!");
1635 assert((!VT.isVector() ||
1637 "Vector element counts must match in getZeroExtendInReg");
1638 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1639 if (OpVT == VT)
1640 return Op;
1641 // TODO: Use computeKnownBits instead of AssertZext.
1642 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1643 ->getVT()
1644 .getScalarType()
1645 .bitsLE(VT.getScalarType()))
1646 return Op;
1648 VT.getScalarSizeInBits());
1649 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1650}
1651
1653 SDValue EVL, const SDLoc &DL,
1654 EVT VT) {
1655 EVT OpVT = Op.getValueType();
1656 assert(VT.isInteger() && OpVT.isInteger() &&
1657 "Cannot getVPZeroExtendInReg FP types");
1658 assert(VT.isVector() && OpVT.isVector() &&
1659 "getVPZeroExtendInReg type and operand type should be vector!");
1661 "Vector element counts must match in getZeroExtendInReg");
1662 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1663 if (OpVT == VT)
1664 return Op;
1666 VT.getScalarSizeInBits());
1667 return getNode(ISD::VP_AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT), Mask,
1668 EVL);
1669}
1670
1672 // Only unsigned pointer semantics are supported right now. In the future this
1673 // might delegate to TLI to check pointer signedness.
1674 return getZExtOrTrunc(Op, DL, VT);
1675}
1676
1678 // Only unsigned pointer semantics are supported right now. In the future this
1679 // might delegate to TLI to check pointer signedness.
1680 return getZeroExtendInReg(Op, DL, VT);
1681}
1682
1684 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1685}
1686
1687/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1689 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1690}
1691
1693 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1694 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1695}
1696
1698 SDValue Mask, SDValue EVL, EVT VT) {
1699 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1700 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1701}
1702
1704 SDValue Mask, SDValue EVL) {
1705 return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL);
1706}
1707
1709 SDValue Mask, SDValue EVL) {
1710 if (VT.bitsGT(Op.getValueType()))
1711 return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL);
1712 if (VT.bitsLT(Op.getValueType()))
1713 return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL);
1714 return Op;
1715}
1716
1718 EVT OpVT) {
1719 if (!V)
1720 return getConstant(0, DL, VT);
1721
1722 switch (TLI->getBooleanContents(OpVT)) {
1725 return getConstant(1, DL, VT);
1727 return getAllOnesConstant(DL, VT);
1728 }
1729 llvm_unreachable("Unexpected boolean content enum!");
1730}
1731
1733 bool isT, bool isO) {
1734 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1735 DL, VT, isT, isO);
1736}
1737
1739 bool isT, bool isO) {
1740 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1741}
1742
1744 EVT VT, bool isT, bool isO) {
1745 assert(VT.isInteger() && "Cannot create FP integer constant!");
1746
1747 EVT EltVT = VT.getScalarType();
1748 const ConstantInt *Elt = &Val;
1749
1750 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1751 // to-be-splatted scalar ConstantInt.
1752 if (isa<VectorType>(Elt->getType()))
1753 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1754
1755 // In some cases the vector type is legal but the element type is illegal and
1756 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1757 // inserted value (the type does not need to match the vector element type).
1758 // Any extra bits introduced will be truncated away.
1759 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1761 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1762 APInt NewVal;
1763 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1764 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1765 else
1766 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1767 Elt = ConstantInt::get(*getContext(), NewVal);
1768 }
1769 // In other cases the element type is illegal and needs to be expanded, for
1770 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1771 // the value into n parts and use a vector type with n-times the elements.
1772 // Then bitcast to the type requested.
1773 // Legalizing constants too early makes the DAGCombiner's job harder so we
1774 // only legalize if the DAG tells us we must produce legal types.
1775 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1776 TLI->getTypeAction(*getContext(), EltVT) ==
1778 const APInt &NewVal = Elt->getValue();
1779 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1780 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1781
1782 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1783 if (VT.isScalableVector() ||
1784 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1785 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1786 "Can only handle an even split!");
1787 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1788
1789 SmallVector<SDValue, 2> ScalarParts;
1790 for (unsigned i = 0; i != Parts; ++i)
1791 ScalarParts.push_back(getConstant(
1792 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1793 ViaEltVT, isT, isO));
1794
1795 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1796 }
1797
1798 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1799 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1800
1801 // Check the temporary vector is the correct size. If this fails then
1802 // getTypeToTransformTo() probably returned a type whose size (in bits)
1803 // isn't a power-of-2 factor of the requested type size.
1804 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1805
1806 SmallVector<SDValue, 2> EltParts;
1807 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1808 EltParts.push_back(getConstant(
1809 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1810 ViaEltVT, isT, isO));
1811
1812 // EltParts is currently in little endian order. If we actually want
1813 // big-endian order then reverse it now.
1814 if (getDataLayout().isBigEndian())
1815 std::reverse(EltParts.begin(), EltParts.end());
1816
1817 // The elements must be reversed when the element order is different
1818 // to the endianness of the elements (because the BITCAST is itself a
1819 // vector shuffle in this situation). However, we do not need any code to
1820 // perform this reversal because getConstant() is producing a vector
1821 // splat.
1822 // This situation occurs in MIPS MSA.
1823
1825 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1826 llvm::append_range(Ops, EltParts);
1827
1828 SDValue V =
1829 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1830 return V;
1831 }
1832
1833 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1834 "APInt size does not match type size!");
1835 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1836 SDVTList VTs = getVTList(EltVT);
1838 AddNodeIDNode(ID, Opc, VTs, {});
1839 ID.AddPointer(Elt);
1840 ID.AddBoolean(isO);
1841 void *IP = nullptr;
1842 SDNode *N = nullptr;
1843 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1844 if (!VT.isVector())
1845 return SDValue(N, 0);
1846
1847 if (!N) {
1848 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1849 if (!isT)
1850 N->setDebugLoc(DL.getDebugLoc());
1851 CSEMap.InsertNode(N, IP);
1852 InsertNode(N);
1853 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1854 }
1855
1856 SDValue Result(N, 0);
1857 if (VT.isVector())
1858 Result = getSplat(VT, DL, Result);
1859 return Result;
1860}
1861
1863 bool isT, bool isO) {
1864 unsigned Size = VT.getScalarSizeInBits();
1865 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1866}
1867
1869 bool IsOpaque) {
1871 IsTarget, IsOpaque);
1872}
1873
1875 bool isTarget) {
1876 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1877}
1878
1880 const SDLoc &DL) {
1881 assert(VT.isInteger() && "Shift amount is not an integer type!");
1882 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1883 return getConstant(Val, DL, ShiftVT);
1884}
1885
1887 const SDLoc &DL) {
1888 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1889 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1890}
1891
1893 bool isTarget) {
1894 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1895}
1896
1898 bool isTarget) {
1899 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1900}
1901
1903 EVT VT, bool isTarget) {
1904 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1905
1906 EVT EltVT = VT.getScalarType();
1907 const ConstantFP *Elt = &V;
1908
1909 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1910 // the to-be-splatted scalar ConstantFP.
1911 if (isa<VectorType>(Elt->getType()))
1912 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1913
1914 // Do the map lookup using the actual bit pattern for the floating point
1915 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1916 // we don't have issues with SNANs.
1917 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1918 SDVTList VTs = getVTList(EltVT);
1920 AddNodeIDNode(ID, Opc, VTs, {});
1921 ID.AddPointer(Elt);
1922 void *IP = nullptr;
1923 SDNode *N = nullptr;
1924 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1925 if (!VT.isVector())
1926 return SDValue(N, 0);
1927
1928 if (!N) {
1929 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1930 CSEMap.InsertNode(N, IP);
1931 InsertNode(N);
1932 }
1933
1934 SDValue Result(N, 0);
1935 if (VT.isVector())
1936 Result = getSplat(VT, DL, Result);
1937 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1938 return Result;
1939}
1940
1942 bool isTarget) {
1943 EVT EltVT = VT.getScalarType();
1944 if (EltVT == MVT::f32)
1945 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1946 if (EltVT == MVT::f64)
1947 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1948 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1949 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1950 bool Ignored;
1951 APFloat APF = APFloat(Val);
1953 &Ignored);
1954 return getConstantFP(APF, DL, VT, isTarget);
1955 }
1956 llvm_unreachable("Unsupported type in getConstantFP");
1957}
1958
1960 EVT VT, int64_t Offset, bool isTargetGA,
1961 unsigned TargetFlags) {
1962 assert((TargetFlags == 0 || isTargetGA) &&
1963 "Cannot set target flags on target-independent globals");
1964
1965 // Truncate (with sign-extension) the offset value to the pointer size.
1967 if (BitWidth < 64)
1969
1970 unsigned Opc;
1971 if (GV->isThreadLocal())
1973 else
1975
1976 SDVTList VTs = getVTList(VT);
1978 AddNodeIDNode(ID, Opc, VTs, {});
1979 ID.AddPointer(GV);
1980 ID.AddInteger(Offset);
1981 ID.AddInteger(TargetFlags);
1982 void *IP = nullptr;
1983 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1984 return SDValue(E, 0);
1985
1986 auto *N = newSDNode<GlobalAddressSDNode>(
1987 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1988 CSEMap.InsertNode(N, IP);
1989 InsertNode(N);
1990 return SDValue(N, 0);
1991}
1992
1994 SDVTList VTs = getVTList(MVT::Untyped);
1997 ID.AddPointer(GV);
1998 void *IP = nullptr;
1999 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP))
2000 return SDValue(E, 0);
2001
2002 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
2003 CSEMap.InsertNode(N, IP);
2004 InsertNode(N);
2005 return SDValue(N, 0);
2006}
2007
2008SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
2009 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
2010 SDVTList VTs = getVTList(VT);
2012 AddNodeIDNode(ID, Opc, VTs, {});
2013 ID.AddInteger(FI);
2014 void *IP = nullptr;
2015 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2016 return SDValue(E, 0);
2017
2018 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
2019 CSEMap.InsertNode(N, IP);
2020 InsertNode(N);
2021 return SDValue(N, 0);
2022}
2023
2024SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
2025 unsigned TargetFlags) {
2026 assert((TargetFlags == 0 || isTarget) &&
2027 "Cannot set target flags on target-independent jump tables");
2028 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
2029 SDVTList VTs = getVTList(VT);
2031 AddNodeIDNode(ID, Opc, VTs, {});
2032 ID.AddInteger(JTI);
2033 ID.AddInteger(TargetFlags);
2034 void *IP = nullptr;
2035 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2036 return SDValue(E, 0);
2037
2038 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
2039 CSEMap.InsertNode(N, IP);
2040 InsertNode(N);
2041 return SDValue(N, 0);
2042}
2043
2045 const SDLoc &DL) {
2047 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2048 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2049}
2050
2052 MaybeAlign Alignment, int Offset,
2053 bool isTarget, unsigned TargetFlags) {
2054 assert((TargetFlags == 0 || isTarget) &&
2055 "Cannot set target flags on target-independent globals");
2056 if (!Alignment)
2057 Alignment = shouldOptForSize()
2058 ? getDataLayout().getABITypeAlign(C->getType())
2059 : getDataLayout().getPrefTypeAlign(C->getType());
2060 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2061 SDVTList VTs = getVTList(VT);
2063 AddNodeIDNode(ID, Opc, VTs, {});
2064 ID.AddInteger(Alignment->value());
2065 ID.AddInteger(Offset);
2066 ID.AddPointer(C);
2067 ID.AddInteger(TargetFlags);
2068 void *IP = nullptr;
2069 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2070 return SDValue(E, 0);
2071
2072 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2073 TargetFlags);
2074 CSEMap.InsertNode(N, IP);
2075 InsertNode(N);
2076 SDValue V = SDValue(N, 0);
2077 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2078 return V;
2079}
2080
2082 MaybeAlign Alignment, int Offset,
2083 bool isTarget, unsigned TargetFlags) {
2084 assert((TargetFlags == 0 || isTarget) &&
2085 "Cannot set target flags on target-independent globals");
2086 if (!Alignment)
2087 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2088 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2089 SDVTList VTs = getVTList(VT);
2091 AddNodeIDNode(ID, Opc, VTs, {});
2092 ID.AddInteger(Alignment->value());
2093 ID.AddInteger(Offset);
2094 C->addSelectionDAGCSEId(ID);
2095 ID.AddInteger(TargetFlags);
2096 void *IP = nullptr;
2097 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2098 return SDValue(E, 0);
2099
2100 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2101 TargetFlags);
2102 CSEMap.InsertNode(N, IP);
2103 InsertNode(N);
2104 return SDValue(N, 0);
2105}
2106
2109 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), {});
2110 ID.AddPointer(MBB);
2111 void *IP = nullptr;
2112 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2113 return SDValue(E, 0);
2114
2115 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2116 CSEMap.InsertNode(N, IP);
2117 InsertNode(N);
2118 return SDValue(N, 0);
2119}
2120
2122 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2123 ValueTypeNodes.size())
2124 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2125
2126 SDNode *&N = VT.isExtended() ?
2127 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2128
2129 if (N) return SDValue(N, 0);
2130 N = newSDNode<VTSDNode>(VT);
2131 InsertNode(N);
2132 return SDValue(N, 0);
2133}
2134
2136 SDNode *&N = ExternalSymbols[Sym];
2137 if (N) return SDValue(N, 0);
2138 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2139 InsertNode(N);
2140 return SDValue(N, 0);
2141}
2142
2143SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2145 return getExternalSymbol(SymName.data(), VT);
2146}
2147
2149 SDNode *&N = MCSymbols[Sym];
2150 if (N)
2151 return SDValue(N, 0);
2152 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2153 InsertNode(N);
2154 return SDValue(N, 0);
2155}
2156
2158 unsigned TargetFlags) {
2159 SDNode *&N =
2160 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2161 if (N) return SDValue(N, 0);
2162 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2163 InsertNode(N);
2164 return SDValue(N, 0);
2165}
2166
2168 EVT VT, unsigned TargetFlags) {
2170 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2171}
2172
2174 if ((unsigned)Cond >= CondCodeNodes.size())
2175 CondCodeNodes.resize(Cond+1);
2176
2177 if (!CondCodeNodes[Cond]) {
2178 auto *N = newSDNode<CondCodeSDNode>(Cond);
2179 CondCodeNodes[Cond] = N;
2180 InsertNode(N);
2181 }
2182
2183 return SDValue(CondCodeNodes[Cond], 0);
2184}
2185
2187 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2188 "APInt size does not match type size!");
2189
2190 if (MulImm == 0)
2191 return getConstant(0, DL, VT);
2192
2193 const MachineFunction &MF = getMachineFunction();
2194 const Function &F = MF.getFunction();
2195 ConstantRange CR = getVScaleRange(&F, 64);
2196 if (const APInt *C = CR.getSingleElement())
2197 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2198
2199 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2200}
2201
2202/// \returns a value of type \p VT that represents the runtime value of \p
2203/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2204/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2205/// or TypeSize.
2206template <typename Ty>
2208 EVT VT, Ty Quantity) {
2209 if (Quantity.isScalable())
2210 return DAG.getVScale(
2211 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2212
2213 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2214}
2215
2217 ElementCount EC) {
2218 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2219}
2220
2222 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2223}
2224
2226 ElementCount EC) {
2227 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2228 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2229 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2230 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2231}
2232
2234 APInt One(ResVT.getScalarSizeInBits(), 1);
2235 return getStepVector(DL, ResVT, One);
2236}
2237
2239 const APInt &StepVal) {
2240 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2241 if (ResVT.isScalableVector())
2242 return getNode(
2243 ISD::STEP_VECTOR, DL, ResVT,
2244 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2245
2246 SmallVector<SDValue, 16> OpsStepConstants;
2247 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2248 OpsStepConstants.push_back(
2249 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2250 return getBuildVector(ResVT, DL, OpsStepConstants);
2251}
2252
2253/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2254/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2259
2261 SDValue N2, ArrayRef<int> Mask) {
2262 assert(VT.getVectorNumElements() == Mask.size() &&
2263 "Must have the same number of vector elements as mask elements!");
2264 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2265 "Invalid VECTOR_SHUFFLE");
2266
2267 // Canonicalize shuffle undef, undef -> undef
2268 if (N1.isUndef() && N2.isUndef()) {
2269 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2270 return getPOISON(VT);
2271 return getUNDEF(VT);
2272 }
2273
2274 // Validate that all indices in Mask are within the range of the elements
2275 // input to the shuffle.
2276 int NElts = Mask.size();
2277 assert(llvm::all_of(Mask,
2278 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2279 "Index out of range");
2280
2281 // Copy the mask so we can do any needed cleanup.
2282 SmallVector<int, 8> MaskVec(Mask);
2283
2284 // Canonicalize shuffle v, v -> v, poison
2285 if (N1 == N2) {
2286 N2 = getPOISON(VT);
2287 for (int i = 0; i != NElts; ++i)
2288 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2289 }
2290
2291 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2292 if (N1.isUndef())
2293 commuteShuffle(N1, N2, MaskVec);
2294
2295 if (TLI->hasVectorBlend()) {
2296 // If shuffling a splat, try to blend the splat instead. We do this here so
2297 // that even when this arises during lowering we don't have to re-handle it.
2298 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2299 BitVector UndefElements;
2300 SDValue Splat = BV->getSplatValue(&UndefElements);
2301 if (!Splat)
2302 return;
2303
2304 for (int i = 0; i < NElts; ++i) {
2305 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2306 continue;
2307
2308 // If this input comes from undef, mark it as such.
2309 if (UndefElements[MaskVec[i] - Offset]) {
2310 MaskVec[i] = -1;
2311 continue;
2312 }
2313
2314 // If we can blend a non-undef lane, use that instead.
2315 if (!UndefElements[i])
2316 MaskVec[i] = i + Offset;
2317 }
2318 };
2319 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2320 BlendSplat(N1BV, 0);
2321 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2322 BlendSplat(N2BV, NElts);
2323 }
2324
2325 // Canonicalize all index into lhs, -> shuffle lhs, poison
2326 // Canonicalize all index into rhs, -> shuffle rhs, poison
2327 bool AllLHS = true, AllRHS = true;
2328 bool N2Undef = N2.isUndef();
2329 for (int i = 0; i != NElts; ++i) {
2330 if (MaskVec[i] >= NElts) {
2331 if (N2Undef)
2332 MaskVec[i] = -1;
2333 else
2334 AllLHS = false;
2335 } else if (MaskVec[i] >= 0) {
2336 AllRHS = false;
2337 }
2338 }
2339 if (AllLHS && AllRHS)
2340 return getPOISON(VT);
2341 if (AllLHS && !N2Undef)
2342 N2 = getPOISON(VT);
2343 if (AllRHS) {
2344 N1 = getPOISON(VT);
2345 commuteShuffle(N1, N2, MaskVec);
2346 }
2347 // Reset our undef status after accounting for the mask.
2348 N2Undef = N2.isUndef();
2349 // Re-check whether both sides ended up undef.
2350 if (N1.isUndef() && N2Undef) {
2351 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2352 return getPOISON(VT);
2353 return getUNDEF(VT);
2354 }
2355
2356 // If Identity shuffle return that node.
2357 bool Identity = true, AllSame = true;
2358 for (int i = 0; i != NElts; ++i) {
2359 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2360 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2361 }
2362 if (Identity && NElts)
2363 return N1;
2364
2365 // Shuffling a constant splat doesn't change the result.
2366 if (N2Undef) {
2367 SDValue V = N1;
2368
2369 // Look through any bitcasts. We check that these don't change the number
2370 // (and size) of elements and just changes their types.
2371 while (V.getOpcode() == ISD::BITCAST)
2372 V = V->getOperand(0);
2373
2374 // A splat should always show up as a build vector node.
2375 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2376 BitVector UndefElements;
2377 SDValue Splat = BV->getSplatValue(&UndefElements);
2378 // If this is a splat of an undef, shuffling it is also undef.
2379 if (Splat && Splat.isUndef())
2380 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2381
2382 bool SameNumElts =
2383 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2384
2385 // We only have a splat which can skip shuffles if there is a splatted
2386 // value and no undef lanes rearranged by the shuffle.
2387 if (Splat && UndefElements.none()) {
2388 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2389 // number of elements match or the value splatted is a zero constant.
2390 if (SameNumElts || isNullConstant(Splat))
2391 return N1;
2392 }
2393
2394 // If the shuffle itself creates a splat, build the vector directly.
2395 if (AllSame && SameNumElts) {
2396 EVT BuildVT = BV->getValueType(0);
2397 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2398 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2399
2400 // We may have jumped through bitcasts, so the type of the
2401 // BUILD_VECTOR may not match the type of the shuffle.
2402 if (BuildVT != VT)
2403 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2404 return NewBV;
2405 }
2406 }
2407 }
2408
2409 SDVTList VTs = getVTList(VT);
2411 SDValue Ops[2] = { N1, N2 };
2413 for (int i = 0; i != NElts; ++i)
2414 ID.AddInteger(MaskVec[i]);
2415
2416 void* IP = nullptr;
2417 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2418 return SDValue(E, 0);
2419
2420 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2421 // SDNode doesn't have access to it. This memory will be "leaked" when
2422 // the node is deallocated, but recovered when the NodeAllocator is released.
2423 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2424 llvm::copy(MaskVec, MaskAlloc);
2425
2426 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2427 dl.getDebugLoc(), MaskAlloc);
2428 createOperands(N, Ops);
2429
2430 CSEMap.InsertNode(N, IP);
2431 InsertNode(N);
2432 SDValue V = SDValue(N, 0);
2433 NewSDValueDbgMsg(V, "Creating new node: ", this);
2434 return V;
2435}
2436
2438 EVT VT = SV.getValueType(0);
2439 SmallVector<int, 8> MaskVec(SV.getMask());
2441
2442 SDValue Op0 = SV.getOperand(0);
2443 SDValue Op1 = SV.getOperand(1);
2444 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2445}
2446
2448 SDVTList VTs = getVTList(VT);
2450 AddNodeIDNode(ID, ISD::Register, VTs, {});
2451 ID.AddInteger(Reg.id());
2452 void *IP = nullptr;
2453 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2454 return SDValue(E, 0);
2455
2456 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2457 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2458 CSEMap.InsertNode(N, IP);
2459 InsertNode(N);
2460 return SDValue(N, 0);
2461}
2462
2465 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), {});
2466 ID.AddPointer(RegMask);
2467 void *IP = nullptr;
2468 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2469 return SDValue(E, 0);
2470
2471 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2472 CSEMap.InsertNode(N, IP);
2473 InsertNode(N);
2474 return SDValue(N, 0);
2475}
2476
2478 MCSymbol *Label) {
2479 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2480}
2481
2482SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2483 SDValue Root, MCSymbol *Label) {
2485 SDValue Ops[] = { Root };
2486 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2487 ID.AddPointer(Label);
2488 void *IP = nullptr;
2489 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2490 return SDValue(E, 0);
2491
2492 auto *N =
2493 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2494 createOperands(N, Ops);
2495
2496 CSEMap.InsertNode(N, IP);
2497 InsertNode(N);
2498 return SDValue(N, 0);
2499}
2500
2502 int64_t Offset, bool isTarget,
2503 unsigned TargetFlags) {
2504 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2505 SDVTList VTs = getVTList(VT);
2506
2508 AddNodeIDNode(ID, Opc, VTs, {});
2509 ID.AddPointer(BA);
2510 ID.AddInteger(Offset);
2511 ID.AddInteger(TargetFlags);
2512 void *IP = nullptr;
2513 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2514 return SDValue(E, 0);
2515
2516 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2517 CSEMap.InsertNode(N, IP);
2518 InsertNode(N);
2519 return SDValue(N, 0);
2520}
2521
2524 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), {});
2525 ID.AddPointer(V);
2526
2527 void *IP = nullptr;
2528 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2529 return SDValue(E, 0);
2530
2531 auto *N = newSDNode<SrcValueSDNode>(V);
2532 CSEMap.InsertNode(N, IP);
2533 InsertNode(N);
2534 return SDValue(N, 0);
2535}
2536
2539 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2540 ID.AddPointer(MD);
2541
2542 void *IP = nullptr;
2543 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2544 return SDValue(E, 0);
2545
2546 auto *N = newSDNode<MDNodeSDNode>(MD);
2547 CSEMap.InsertNode(N, IP);
2548 InsertNode(N);
2549 return SDValue(N, 0);
2550}
2551
2553 if (VT == V.getValueType())
2554 return V;
2555
2556 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2557}
2558
2560 unsigned SrcAS, unsigned DestAS) {
2561 SDVTList VTs = getVTList(VT);
2562 SDValue Ops[] = {Ptr};
2565 ID.AddInteger(SrcAS);
2566 ID.AddInteger(DestAS);
2567
2568 void *IP = nullptr;
2569 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2570 return SDValue(E, 0);
2571
2572 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2573 VTs, SrcAS, DestAS);
2574 createOperands(N, Ops);
2575
2576 CSEMap.InsertNode(N, IP);
2577 InsertNode(N);
2578 return SDValue(N, 0);
2579}
2580
2582 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2583}
2584
2586 UndefPoisonKind Kind) {
2587 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2588 return V;
2589 return getFreeze(V);
2590}
2591
2592/// getShiftAmountOperand - Return the specified value casted to
2593/// the target's desired shift amount type.
2595 EVT OpTy = Op.getValueType();
2596 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2597 if (OpTy == ShTy || OpTy.isVector()) return Op;
2598
2599 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2600}
2601
2603 SDLoc dl(Node);
2605 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2606 EVT VT = Node->getValueType(0);
2607 SDValue Tmp1 = Node->getOperand(0);
2608 SDValue Tmp2 = Node->getOperand(1);
2609 const MaybeAlign MA(Node->getConstantOperandVal(3));
2610
2611 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2612 Tmp2, MachinePointerInfo(V));
2613 SDValue VAList = VAListLoad;
2614
2615 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2616 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2617 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2618
2619 VAList = getNode(
2620 ISD::AND, dl, VAList.getValueType(), VAList,
2621 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2622 }
2623
2624 // Increment the pointer, VAList, to the next vaarg
2625 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2626 getConstant(getDataLayout().getTypeAllocSize(
2627 VT.getTypeForEVT(*getContext())),
2628 dl, VAList.getValueType()));
2629 // Store the incremented VAList to the legalized pointer
2630 Tmp1 =
2631 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2632 // Load the actual argument out of the pointer VAList
2633 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2634}
2635
2637 SDLoc dl(Node);
2639 // This defaults to loading a pointer from the input and storing it to the
2640 // output, returning the chain.
2641 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2642 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2643 SDValue Tmp1 =
2644 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2645 Node->getOperand(2), MachinePointerInfo(VS));
2646 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2647 MachinePointerInfo(VD));
2648}
2649
2651 const DataLayout &DL = getDataLayout();
2652 Type *Ty = VT.getTypeForEVT(*getContext());
2653 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2654
2655 if (TLI->isTypeLegal(VT) || !VT.isVector())
2656 return RedAlign;
2657
2658 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2659 const Align StackAlign = TFI->getStackAlign();
2660
2661 // See if we can choose a smaller ABI alignment in cases where it's an
2662 // illegal vector type that will get broken down.
2663 if (RedAlign > StackAlign) {
2664 EVT IntermediateVT;
2665 MVT RegisterVT;
2666 unsigned NumIntermediates;
2667 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2668 NumIntermediates, RegisterVT);
2669 Ty = IntermediateVT.getTypeForEVT(*getContext());
2670 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2671 if (RedAlign2 < RedAlign)
2672 RedAlign = RedAlign2;
2673
2674 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2675 // If the stack is not realignable, the alignment should be limited to the
2676 // StackAlignment
2677 RedAlign = std::min(RedAlign, StackAlign);
2678 }
2679
2680 return RedAlign;
2681}
2682
2684 MachineFrameInfo &MFI = MF->getFrameInfo();
2685 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2686 int StackID = 0;
2687 if (Bytes.isScalable())
2688 StackID = TFI->getStackIDForScalableVectors();
2689 // The stack id gives an indication of whether the object is scalable or
2690 // not, so it's safe to pass in the minimum size here.
2691 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2692 false, nullptr, StackID);
2693 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2694}
2695
2697 Type *Ty = VT.getTypeForEVT(*getContext());
2698 Align StackAlign =
2699 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2700 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2701}
2702
2704 TypeSize VT1Size = VT1.getStoreSize();
2705 TypeSize VT2Size = VT2.getStoreSize();
2706 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2707 "Don't know how to choose the maximum size when creating a stack "
2708 "temporary");
2709 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2710 ? VT1Size
2711 : VT2Size;
2712
2713 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2714 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2715 const DataLayout &DL = getDataLayout();
2716 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2717 return CreateStackTemporary(Bytes, Align);
2718}
2719
2721 ISD::CondCode Cond, const SDLoc &dl,
2722 SDNodeFlags Flags) {
2723 EVT OpVT = N1.getValueType();
2724
2725 auto GetUndefBooleanConstant = [&]() {
2726 if (VT.getScalarType() == MVT::i1 ||
2727 TLI->getBooleanContents(OpVT) ==
2729 return getUNDEF(VT);
2730 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2731 // so we cannot use getUNDEF(). Return zero instead.
2732 return getConstant(0, dl, VT);
2733 };
2734
2735 // These setcc operations always fold.
2736 switch (Cond) {
2737 default: break;
2738 case ISD::SETFALSE:
2739 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2740 case ISD::SETTRUE:
2741 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2742
2743 case ISD::SETOEQ:
2744 case ISD::SETOGT:
2745 case ISD::SETOGE:
2746 case ISD::SETOLT:
2747 case ISD::SETOLE:
2748 case ISD::SETONE:
2749 case ISD::SETO:
2750 case ISD::SETUO:
2751 case ISD::SETUEQ:
2752 case ISD::SETUNE:
2753 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2754 break;
2755 }
2756
2757 if (OpVT.isInteger()) {
2758 // For EQ and NE, we can always pick a value for the undef to make the
2759 // predicate pass or fail, so we can return undef.
2760 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2761 // icmp eq/ne X, undef -> undef.
2762 if ((N1.isUndef() || N2.isUndef()) &&
2763 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2764 return GetUndefBooleanConstant();
2765
2766 // If both operands are undef, we can return undef for int comparison.
2767 // icmp undef, undef -> undef.
2768 if (N1.isUndef() && N2.isUndef())
2769 return GetUndefBooleanConstant();
2770
2771 // icmp X, X -> true/false
2772 // icmp X, undef -> true/false because undef could be X.
2773 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2774 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2775 }
2776
2778 const APInt &C2 = N2C->getAPIntValue();
2780 const APInt &C1 = N1C->getAPIntValue();
2781
2783 dl, VT, OpVT);
2784 }
2785 }
2786
2787 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2788 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2789
2790 if (N1CFP && N2CFP) {
2791 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2792 switch (Cond) {
2793 default: break;
2794 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2795 return GetUndefBooleanConstant();
2796 [[fallthrough]];
2797 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2798 OpVT);
2799 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2800 return GetUndefBooleanConstant();
2801 [[fallthrough]];
2803 R==APFloat::cmpLessThan, dl, VT,
2804 OpVT);
2805 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2806 return GetUndefBooleanConstant();
2807 [[fallthrough]];
2808 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2809 OpVT);
2810 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2811 return GetUndefBooleanConstant();
2812 [[fallthrough]];
2814 VT, OpVT);
2815 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2816 return GetUndefBooleanConstant();
2817 [[fallthrough]];
2819 R==APFloat::cmpEqual, dl, VT,
2820 OpVT);
2821 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2822 return GetUndefBooleanConstant();
2823 [[fallthrough]];
2825 R==APFloat::cmpEqual, dl, VT, OpVT);
2826 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2827 OpVT);
2828 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2829 OpVT);
2831 R==APFloat::cmpEqual, dl, VT,
2832 OpVT);
2833 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2834 OpVT);
2836 R==APFloat::cmpLessThan, dl, VT,
2837 OpVT);
2839 R==APFloat::cmpUnordered, dl, VT,
2840 OpVT);
2842 VT, OpVT);
2843 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2844 OpVT);
2845 }
2846 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2847 // Ensure that the constant occurs on the RHS.
2849 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2850 return SDValue();
2851 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2852 /*IsSignaling=*/false, Flags);
2853 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2854 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2855 // If an operand is known to be a nan (or undef that could be a nan), we can
2856 // fold it.
2857 // Choosing NaN for the undef will always make unordered comparison succeed
2858 // and ordered comparison fails.
2859 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2860 switch (ISD::getUnorderedFlavor(Cond)) {
2861 default:
2862 llvm_unreachable("Unknown flavor!");
2863 case 0: // Known false.
2864 return getBoolConstant(false, dl, VT, OpVT);
2865 case 1: // Known true.
2866 return getBoolConstant(true, dl, VT, OpVT);
2867 case 2: // Undefined.
2868 return GetUndefBooleanConstant();
2869 }
2870 }
2871
2872 // Could not fold it.
2873 return SDValue();
2874}
2875
2876/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2877/// use this predicate to simplify operations downstream.
2879 unsigned BitWidth = Op.getScalarValueSizeInBits();
2881}
2882
2883// TODO: Should have argument to specify if sign bit of nan is ignorable.
2885 if (Depth >= MaxRecursionDepth)
2886 return false; // Limit search depth.
2887
2888 unsigned Opc = Op.getOpcode();
2889 switch (Opc) {
2890 case ISD::FABS:
2891 return true;
2892 case ISD::AssertNoFPClass: {
2893 FPClassTest NoFPClass =
2894 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2895
2896 const FPClassTest TestMask = fcNan | fcNegative;
2897 return (NoFPClass & TestMask) == TestMask;
2898 }
2899 case ISD::ARITH_FENCE:
2900 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2901 case ISD::FEXP:
2902 case ISD::FEXP2:
2903 case ISD::FEXP10:
2904 return Op->getFlags().hasNoNaNs();
2905 case ISD::FMINNUM:
2906 case ISD::FMINNUM_IEEE:
2907 case ISD::FMINIMUM:
2908 case ISD::FMINIMUMNUM:
2909 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2910 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2911 case ISD::FMAXNUM:
2912 case ISD::FMAXNUM_IEEE:
2913 case ISD::FMAXIMUM:
2914 case ISD::FMAXIMUMNUM:
2915 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2916 // is sufficient.
2917 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2918 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2919 default:
2920 return false;
2921 }
2922
2923 llvm_unreachable("covered opcode switch");
2924}
2925
2926/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2927/// this predicate to simplify operations downstream. Mask is known to be zero
2928/// for bits that V cannot have.
2930 unsigned Depth) const {
2931 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2932}
2933
2934/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2935/// DemandedElts. We use this predicate to simplify operations downstream.
2936/// Mask is known to be zero for bits that V cannot have.
2938 const APInt &DemandedElts,
2939 unsigned Depth) const {
2940 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2941}
2942
2943/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2944/// DemandedElts. We use this predicate to simplify operations downstream.
2946 unsigned Depth /* = 0 */) const {
2947 return computeKnownBits(V, DemandedElts, Depth).isZero();
2948}
2949
2950/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2952 unsigned Depth) const {
2953 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2954}
2955
2957 const APInt &DemandedElts,
2958 unsigned Depth) const {
2959 EVT VT = Op.getValueType();
2960 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2961
2962 unsigned NumElts = VT.getVectorNumElements();
2963 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2964
2965 APInt KnownZeroElements = APInt::getZero(NumElts);
2966 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2967 if (!DemandedElts[EltIdx])
2968 continue; // Don't query elements that are not demanded.
2969 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2970 if (MaskedVectorIsZero(Op, Mask, Depth))
2971 KnownZeroElements.setBit(EltIdx);
2972 }
2973 return KnownZeroElements;
2974}
2975
2976/// isSplatValue - Return true if the vector V has the same value
2977/// across all DemandedElts. For scalable vectors, we don't know the
2978/// number of lanes at compile time. Instead, we use a 1 bit APInt
2979/// to represent a conservative value for all lanes; that is, that
2980/// one bit value is implicitly splatted across all lanes.
2981bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2982 APInt &UndefElts, unsigned Depth) const {
2983 unsigned Opcode = V.getOpcode();
2984 EVT VT = V.getValueType();
2985 assert(VT.isVector() && "Vector type expected");
2986 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2987 "scalable demanded bits are ignored");
2988
2989 if (!DemandedElts)
2990 return false; // No demanded elts, better to assume we don't know anything.
2991
2992 if (Depth >= MaxRecursionDepth)
2993 return false; // Limit search depth.
2994
2995 // Deal with some common cases here that work for both fixed and scalable
2996 // vector types.
2997 switch (Opcode) {
2998 case ISD::SPLAT_VECTOR:
2999 UndefElts = V.getOperand(0).isUndef()
3000 ? APInt::getAllOnes(DemandedElts.getBitWidth())
3001 : APInt(DemandedElts.getBitWidth(), 0);
3002 return true;
3003 case ISD::ADD:
3004 case ISD::SUB:
3005 case ISD::AND:
3006 case ISD::XOR:
3007 case ISD::OR: {
3008 APInt UndefLHS, UndefRHS;
3009 SDValue LHS = V.getOperand(0);
3010 SDValue RHS = V.getOperand(1);
3011 // Only recognize splats with the same demanded undef elements for both
3012 // operands, otherwise we might fail to handle binop-specific undef
3013 // handling.
3014 // e.g. (and undef, 0) -> 0 etc.
3015 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
3016 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
3017 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
3018 UndefElts = UndefLHS | UndefRHS;
3019 return true;
3020 }
3021 return false;
3022 }
3023 case ISD::ABS:
3025 case ISD::TRUNCATE:
3026 case ISD::SIGN_EXTEND:
3027 case ISD::ZERO_EXTEND:
3028 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3029 default:
3030 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3031 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3032 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3033 Depth);
3034 break;
3035 }
3036
3037 // We don't support other cases than those above for scalable vectors at
3038 // the moment.
3039 if (VT.isScalableVector())
3040 return false;
3041
3042 unsigned NumElts = VT.getVectorNumElements();
3043 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3044 UndefElts = APInt::getZero(NumElts);
3045
3046 switch (Opcode) {
3047 case ISD::BUILD_VECTOR: {
3048 SDValue Scl;
3049 for (unsigned i = 0; i != NumElts; ++i) {
3050 SDValue Op = V.getOperand(i);
3051 if (Op.isUndef()) {
3052 UndefElts.setBit(i);
3053 continue;
3054 }
3055 if (!DemandedElts[i])
3056 continue;
3057 if (Scl && Scl != Op)
3058 return false;
3059 Scl = Op;
3060 }
3061 return true;
3062 }
3063 case ISD::VECTOR_SHUFFLE: {
3064 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3065 APInt DemandedLHS = APInt::getZero(NumElts);
3066 APInt DemandedRHS = APInt::getZero(NumElts);
3067 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3068 for (int i = 0; i != (int)NumElts; ++i) {
3069 int M = Mask[i];
3070 if (M < 0) {
3071 UndefElts.setBit(i);
3072 continue;
3073 }
3074 if (!DemandedElts[i])
3075 continue;
3076 if (M < (int)NumElts)
3077 DemandedLHS.setBit(M);
3078 else
3079 DemandedRHS.setBit(M - NumElts);
3080 }
3081
3082 // If we aren't demanding either op, assume there's no splat.
3083 // If we are demanding both ops, assume there's no splat.
3084 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3085 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3086 return false;
3087
3088 // See if the demanded elts of the source op is a splat or we only demand
3089 // one element, which should always be a splat.
3090 // TODO: Handle source ops splats with undefs.
3091 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3092 APInt SrcUndefs;
3093 return (SrcElts.popcount() == 1) ||
3094 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3095 (SrcElts & SrcUndefs).isZero());
3096 };
3097 if (!DemandedLHS.isZero())
3098 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3099 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3100 }
3102 // Offset the demanded elts by the subvector index.
3103 SDValue Src = V.getOperand(0);
3104 // We don't support scalable vectors at the moment.
3105 if (Src.getValueType().isScalableVector())
3106 return false;
3107 uint64_t Idx = V.getConstantOperandVal(1);
3108 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3109 APInt UndefSrcElts;
3110 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3111 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3112 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3113 return true;
3114 }
3115 break;
3116 }
3120 // Widen the demanded elts by the src element count.
3121 SDValue Src = V.getOperand(0);
3122 // We don't support scalable vectors at the moment.
3123 if (Src.getValueType().isScalableVector())
3124 return false;
3125 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3126 APInt UndefSrcElts;
3127 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3128 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3129 UndefElts = UndefSrcElts.trunc(NumElts);
3130 return true;
3131 }
3132 break;
3133 }
3134 case ISD::BITCAST: {
3135 SDValue Src = V.getOperand(0);
3136 EVT SrcVT = Src.getValueType();
3137 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3138 unsigned BitWidth = VT.getScalarSizeInBits();
3139
3140 // Ignore bitcasts from unsupported types.
3141 // TODO: Add fp support?
3142 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3143 break;
3144
3145 // Bitcast 'small element' vector to 'large element' vector.
3146 if ((BitWidth % SrcBitWidth) == 0) {
3147 // See if each sub element is a splat.
3148 unsigned Scale = BitWidth / SrcBitWidth;
3149 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3150 APInt ScaledDemandedElts =
3151 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3152 for (unsigned I = 0; I != Scale; ++I) {
3153 APInt SubUndefElts;
3154 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3155 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3156 SubDemandedElts &= ScaledDemandedElts;
3157 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3158 return false;
3159 // TODO: Add support for merging sub undef elements.
3160 if (!SubUndefElts.isZero())
3161 return false;
3162 }
3163 return true;
3164 }
3165 break;
3166 }
3167 }
3168
3169 return false;
3170}
3171
3172/// Helper wrapper to main isSplatValue function.
3173bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3174 EVT VT = V.getValueType();
3175 assert(VT.isVector() && "Vector type expected");
3176
3177 APInt UndefElts;
3178 // Since the number of lanes in a scalable vector is unknown at compile time,
3179 // we track one bit which is implicitly broadcast to all lanes. This means
3180 // that all lanes in a scalable vector are considered demanded.
3181 APInt DemandedElts
3183 return isSplatValue(V, DemandedElts, UndefElts) &&
3184 (AllowUndefs || !UndefElts);
3185}
3186
3189
3190 EVT VT = V.getValueType();
3191 unsigned Opcode = V.getOpcode();
3192 switch (Opcode) {
3193 default: {
3194 APInt UndefElts;
3195 // Since the number of lanes in a scalable vector is unknown at compile time,
3196 // we track one bit which is implicitly broadcast to all lanes. This means
3197 // that all lanes in a scalable vector are considered demanded.
3198 APInt DemandedElts
3200
3201 if (isSplatValue(V, DemandedElts, UndefElts)) {
3202 if (VT.isScalableVector()) {
3203 // DemandedElts and UndefElts are ignored for scalable vectors, since
3204 // the only supported cases are SPLAT_VECTOR nodes.
3205 SplatIdx = 0;
3206 } else {
3207 // Handle case where all demanded elements are UNDEF.
3208 if (DemandedElts.isSubsetOf(UndefElts)) {
3209 SplatIdx = 0;
3210 return getUNDEF(VT);
3211 }
3212 SplatIdx = (UndefElts & DemandedElts).countr_one();
3213 }
3214 return V;
3215 }
3216 break;
3217 }
3218 case ISD::SPLAT_VECTOR:
3219 SplatIdx = 0;
3220 return V;
3221 case ISD::VECTOR_SHUFFLE: {
3222 assert(!VT.isScalableVector());
3223 // Check if this is a shuffle node doing a splat.
3224 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3225 // getTargetVShiftNode currently struggles without the splat source.
3226 auto *SVN = cast<ShuffleVectorSDNode>(V);
3227 if (!SVN->isSplat())
3228 break;
3229 int Idx = SVN->getSplatIndex();
3230 int NumElts = V.getValueType().getVectorNumElements();
3231 SplatIdx = Idx % NumElts;
3232 return V.getOperand(Idx / NumElts);
3233 }
3234 }
3235
3236 return SDValue();
3237}
3238
3240 int SplatIdx;
3241 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3242 EVT SVT = SrcVector.getValueType().getScalarType();
3243 EVT LegalSVT = SVT;
3244 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3245 if (!SVT.isInteger())
3246 return SDValue();
3247 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3248 if (LegalSVT.bitsLT(SVT))
3249 return SDValue();
3250 }
3251 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3252 }
3253 return SDValue();
3254}
3255
3256std::optional<ConstantRange>
3258 unsigned Depth) const {
3259 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3260 V.getOpcode() == ISD::SRA) &&
3261 "Unknown shift node");
3262 // Shifting more than the bitwidth is not valid.
3263 unsigned BitWidth = V.getScalarValueSizeInBits();
3264
3265 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3266 const APInt &ShAmt = Cst->getAPIntValue();
3267 if (ShAmt.uge(BitWidth))
3268 return std::nullopt;
3269 return ConstantRange(ShAmt);
3270 }
3271
3272 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3273 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3274 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3275 if (!DemandedElts[i])
3276 continue;
3277 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3278 if (!SA) {
3279 MinAmt = MaxAmt = nullptr;
3280 break;
3281 }
3282 const APInt &ShAmt = SA->getAPIntValue();
3283 if (ShAmt.uge(BitWidth))
3284 return std::nullopt;
3285 if (!MinAmt || MinAmt->ugt(ShAmt))
3286 MinAmt = &ShAmt;
3287 if (!MaxAmt || MaxAmt->ult(ShAmt))
3288 MaxAmt = &ShAmt;
3289 }
3290 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3291 "Failed to find matching min/max shift amounts");
3292 if (MinAmt && MaxAmt)
3293 return ConstantRange(*MinAmt, *MaxAmt + 1);
3294 }
3295
3296 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3297 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3298 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3299 if (KnownAmt.getMaxValue().ult(BitWidth))
3300 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3301
3302 return std::nullopt;
3303}
3304
3305std::optional<unsigned>
3307 unsigned Depth) const {
3308 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3309 V.getOpcode() == ISD::SRA) &&
3310 "Unknown shift node");
3311 if (std::optional<ConstantRange> AmtRange =
3312 getValidShiftAmountRange(V, DemandedElts, Depth))
3313 if (const APInt *ShAmt = AmtRange->getSingleElement())
3314 return ShAmt->getZExtValue();
3315 return std::nullopt;
3316}
3317
3318std::optional<unsigned>
3320 APInt DemandedElts = getDemandAllEltsMask(V);
3321 return getValidShiftAmount(V, DemandedElts, Depth);
3322}
3323
3324std::optional<unsigned>
3326 unsigned Depth) const {
3327 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3328 V.getOpcode() == ISD::SRA) &&
3329 "Unknown shift node");
3330 if (std::optional<ConstantRange> AmtRange =
3331 getValidShiftAmountRange(V, DemandedElts, Depth))
3332 return AmtRange->getUnsignedMin().getZExtValue();
3333 return std::nullopt;
3334}
3335
3336std::optional<unsigned>
3338 APInt DemandedElts = getDemandAllEltsMask(V);
3339 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3340}
3341
3342std::optional<unsigned>
3344 unsigned Depth) const {
3345 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3346 V.getOpcode() == ISD::SRA) &&
3347 "Unknown shift node");
3348 if (std::optional<ConstantRange> AmtRange =
3349 getValidShiftAmountRange(V, DemandedElts, Depth))
3350 return AmtRange->getUnsignedMax().getZExtValue();
3351 return std::nullopt;
3352}
3353
3354std::optional<unsigned>
3356 APInt DemandedElts = getDemandAllEltsMask(V);
3357 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3358}
3359
3360/// Determine which bits of Op are known to be either zero or one and return
3361/// them in Known. For vectors, the known bits are those that are shared by
3362/// every vector element.
3364 APInt DemandedElts = getDemandAllEltsMask(Op);
3365 return computeKnownBits(Op, DemandedElts, Depth);
3366}
3367
3368/// Determine which bits of Op are known to be either zero or one and return
3369/// them in Known. The DemandedElts argument allows us to only collect the known
3370/// bits that are shared by the requested vector elements.
3372 unsigned Depth) const {
3373 unsigned BitWidth = Op.getScalarValueSizeInBits();
3374
3375 KnownBits Known(BitWidth); // Don't know anything.
3376
3377 if (auto OptAPInt = Op->bitcastToAPInt()) {
3378 // We know all of the bits for a constant!
3379 return KnownBits::makeConstant(*std::move(OptAPInt));
3380 }
3381
3382 if (Depth >= MaxRecursionDepth)
3383 return Known; // Limit search depth.
3384
3385 KnownBits Known2;
3386 unsigned NumElts = DemandedElts.getBitWidth();
3387 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3388 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3389 assert((!Op.getValueType().isFixedLengthVector() ||
3390 NumElts == Op.getValueType().getVectorNumElements()) &&
3391 "Unexpected vector size");
3392
3393 if (!DemandedElts)
3394 return Known; // No demanded elts, better to assume we don't know anything.
3395
3396 unsigned Opcode = Op.getOpcode();
3397 switch (Opcode) {
3398 case ISD::MERGE_VALUES:
3399 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3400 Depth + 1);
3401 case ISD::SPLAT_VECTOR: {
3402 SDValue SrcOp = Op.getOperand(0);
3403 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3404 "Expected SPLAT_VECTOR implicit truncation");
3405 // Implicitly truncate the bits to match the official semantics of
3406 // SPLAT_VECTOR.
3408 break;
3409 }
3411 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3412 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3413 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3414 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3415 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3416 }
3417 break;
3418 }
3419 case ISD::STEP_VECTOR: {
3420 const APInt &Step = Op.getConstantOperandAPInt(0);
3421
3422 if (Step.isPowerOf2())
3423 Known.Zero.setLowBits(Step.logBase2());
3424
3426
3427 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3428 break;
3429 const APInt MinNumElts =
3430 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3431
3432 bool Overflow;
3433 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3435 .umul_ov(MinNumElts, Overflow);
3436 if (Overflow)
3437 break;
3438
3439 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3440 if (Overflow)
3441 break;
3442
3443 Known.Zero.setHighBits(MaxValue.countl_zero());
3444 break;
3445 }
3446 case ISD::BUILD_VECTOR:
3447 assert(!Op.getValueType().isScalableVector());
3448 // Collect the known bits that are shared by every demanded vector element.
3449 Known.setAllConflict();
3450 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3451 if (!DemandedElts[i])
3452 continue;
3453
3454 SDValue SrcOp = Op.getOperand(i);
3455 if (SrcOp.getOpcode() == ISD::POISON)
3456 continue;
3457
3458 Known2 = computeKnownBits(SrcOp, Depth + 1);
3459
3460 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3461 if (SrcOp.getValueSizeInBits() != BitWidth) {
3462 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3463 "Expected BUILD_VECTOR implicit truncation");
3464 Known2 = Known2.trunc(BitWidth);
3465 }
3466
3467 // Known bits are the values that are shared by every demanded element.
3468 Known = Known.intersectWith(Known2);
3469
3470 // If we don't know any bits, early out.
3471 if (Known.isUnknown())
3472 break;
3473 }
3474
3475 // If every demanded element was poison, we know nothing.
3476 if (Known.hasConflict())
3477 Known.resetAll();
3478 break;
3479 case ISD::VECTOR_COMPRESS: {
3480 SDValue Vec = Op.getOperand(0);
3481 SDValue PassThru = Op.getOperand(2);
3482 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3483 // If we don't know any bits, early out.
3484 if (Known.isUnknown())
3485 break;
3486 Known2 = computeKnownBits(Vec, Depth + 1);
3487 Known = Known.intersectWith(Known2);
3488 break;
3489 }
3490 case ISD::VECTOR_SHUFFLE: {
3491 assert(!Op.getValueType().isScalableVector());
3492 // Collect the known bits that are shared by every vector element referenced
3493 // by the shuffle.
3494 APInt DemandedLHS, DemandedRHS;
3496 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3497 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3498 DemandedLHS, DemandedRHS))
3499 break;
3500
3501 // Known bits are the values that are shared by every demanded element.
3502 Known.setAllConflict();
3503 if (!!DemandedLHS) {
3504 SDValue LHS = Op.getOperand(0);
3505 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3506 Known = Known.intersectWith(Known2);
3507 }
3508 // If we don't know any bits, early out.
3509 if (Known.isUnknown())
3510 break;
3511 if (!!DemandedRHS) {
3512 SDValue RHS = Op.getOperand(1);
3513 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3514 Known = Known.intersectWith(Known2);
3515 }
3516 break;
3517 }
3518 case ISD::VSCALE: {
3520 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3522 break;
3523 }
3524 case ISD::CONCAT_VECTORS: {
3525 if (Op.getValueType().isScalableVector())
3526 break;
3527 // Split DemandedElts and test each of the demanded subvectors.
3528 Known.setAllConflict();
3529 EVT SubVectorVT = Op.getOperand(0).getValueType();
3530 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3531 unsigned NumSubVectors = Op.getNumOperands();
3532 for (unsigned i = 0; i != NumSubVectors; ++i) {
3533 APInt DemandedSub =
3534 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3535 if (!!DemandedSub) {
3536 SDValue Sub = Op.getOperand(i);
3537 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3538 Known = Known.intersectWith(Known2);
3539 }
3540 // If we don't know any bits, early out.
3541 if (Known.isUnknown())
3542 break;
3543 }
3544 break;
3545 }
3546 case ISD::INSERT_SUBVECTOR: {
3547 if (Op.getValueType().isScalableVector())
3548 break;
3549 // Demand any elements from the subvector and the remainder from the src its
3550 // inserted into.
3551 SDValue Src = Op.getOperand(0);
3552 SDValue Sub = Op.getOperand(1);
3553 uint64_t Idx = Op.getConstantOperandVal(2);
3554 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3555 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3556 APInt DemandedSrcElts = DemandedElts;
3557 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3558
3559 Known.setAllConflict();
3560 if (!!DemandedSubElts) {
3561 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3562 if (Known.isUnknown())
3563 break; // early-out.
3564 }
3565 if (!!DemandedSrcElts) {
3566 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3567 Known = Known.intersectWith(Known2);
3568 }
3569 break;
3570 }
3572 // Offset the demanded elts by the subvector index.
3573 SDValue Src = Op.getOperand(0);
3574
3575 APInt DemandedSrcElts;
3576 if (Src.getValueType().isScalableVector())
3577 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3578 else {
3579 uint64_t Idx = Op.getConstantOperandVal(1);
3580 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3581 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3582 }
3583 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3584 break;
3585 }
3586 case ISD::SCALAR_TO_VECTOR: {
3587 if (Op.getValueType().isScalableVector())
3588 break;
3589 // We know about scalar_to_vector as much as we know about it source,
3590 // which becomes the first element of otherwise unknown vector.
3591 if (DemandedElts != 1)
3592 break;
3593
3594 SDValue N0 = Op.getOperand(0);
3595 Known = computeKnownBits(N0, Depth + 1);
3596 if (N0.getValueSizeInBits() != BitWidth)
3597 Known = Known.trunc(BitWidth);
3598
3599 break;
3600 }
3601 case ISD::BITCAST: {
3602 if (Op.getValueType().isScalableVector())
3603 break;
3604
3605 SDValue N0 = Op.getOperand(0);
3606 EVT SubVT = N0.getValueType();
3607 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3608
3609 // Ignore bitcasts from unsupported types.
3610 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3611 break;
3612
3613 // Fast handling of 'identity' bitcasts.
3614 if (BitWidth == SubBitWidth) {
3615 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3616 break;
3617 }
3618
3619 bool IsLE = getDataLayout().isLittleEndian();
3620
3621 // Bitcast 'small element' vector to 'large element' scalar/vector.
3622 if ((BitWidth % SubBitWidth) == 0) {
3623 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3624
3625 // Collect known bits for the (larger) output by collecting the known
3626 // bits from each set of sub elements and shift these into place.
3627 // We need to separately call computeKnownBits for each set of
3628 // sub elements as the knownbits for each is likely to be different.
3629 unsigned SubScale = BitWidth / SubBitWidth;
3630 APInt SubDemandedElts(NumElts * SubScale, 0);
3631 for (unsigned i = 0; i != NumElts; ++i)
3632 if (DemandedElts[i])
3633 SubDemandedElts.setBit(i * SubScale);
3634
3635 for (unsigned i = 0; i != SubScale; ++i) {
3636 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3637 Depth + 1);
3638 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3639 Known.insertBits(Known2, SubBitWidth * Shifts);
3640 }
3641 }
3642
3643 // Bitcast 'large element' scalar/vector to 'small element' vector.
3644 if ((SubBitWidth % BitWidth) == 0) {
3645 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3646
3647 // Collect known bits for the (smaller) output by collecting the known
3648 // bits from the overlapping larger input elements and extracting the
3649 // sub sections we actually care about.
3650 unsigned SubScale = SubBitWidth / BitWidth;
3651 APInt SubDemandedElts =
3652 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3653 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3654
3655 Known.setAllConflict();
3656 for (unsigned i = 0; i != NumElts; ++i)
3657 if (DemandedElts[i]) {
3658 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3659 unsigned Offset = (Shifts % SubScale) * BitWidth;
3660 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3661 // If we don't know any bits, early out.
3662 if (Known.isUnknown())
3663 break;
3664 }
3665 }
3666 break;
3667 }
3668 case ISD::AND:
3669 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3670 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3671
3672 Known &= Known2;
3673 break;
3674 case ISD::OR:
3675 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3676 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3677
3678 Known |= Known2;
3679 break;
3680 case ISD::XOR:
3681 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3682 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3683
3684 Known ^= Known2;
3685 break;
3686 case ISD::MUL: {
3687 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3688 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3689 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3690 // TODO: SelfMultiply can be poison, but not undef.
3691 if (SelfMultiply)
3692 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3693 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3694 Depth + 1);
3695 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3696
3697 // If the multiplication is known not to overflow, the product of a number
3698 // with itself is non-negative. Only do this if we didn't already computed
3699 // the opposite value for the sign bit.
3700 if (Op->getFlags().hasNoSignedWrap() &&
3701 Op.getOperand(0) == Op.getOperand(1) &&
3702 !Known.isNegative())
3703 Known.makeNonNegative();
3704 break;
3705 }
3706 case ISD::MULHU: {
3707 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3708 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3709 Known = KnownBits::mulhu(Known, Known2);
3710 break;
3711 }
3712 case ISD::MULHS: {
3713 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3714 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3715 Known = KnownBits::mulhs(Known, Known2);
3716 break;
3717 }
3718 case ISD::ABDU: {
3719 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3720 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3721 Known = KnownBits::abdu(Known, Known2);
3722 break;
3723 }
3724 case ISD::ABDS: {
3725 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3726 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3727 Known = KnownBits::abds(Known, Known2);
3728 unsigned SignBits1 =
3729 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3730 if (SignBits1 == 1)
3731 break;
3732 unsigned SignBits0 =
3733 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3734 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3735 break;
3736 }
3737 case ISD::UMUL_LOHI: {
3738 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3739 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3740 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3741 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3742 if (Op.getResNo() == 0)
3743 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3744 else
3745 Known = KnownBits::mulhu(Known, Known2);
3746 break;
3747 }
3748 case ISD::SMUL_LOHI: {
3749 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3750 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3751 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3752 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3753 if (Op.getResNo() == 0)
3754 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3755 else
3756 Known = KnownBits::mulhs(Known, Known2);
3757 break;
3758 }
3759 case ISD::AVGFLOORU: {
3760 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3761 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3762 Known = KnownBits::avgFloorU(Known, Known2);
3763 break;
3764 }
3765 case ISD::AVGCEILU: {
3766 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3767 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3768 Known = KnownBits::avgCeilU(Known, Known2);
3769 break;
3770 }
3771 case ISD::AVGFLOORS: {
3772 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3773 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3774 Known = KnownBits::avgFloorS(Known, Known2);
3775 break;
3776 }
3777 case ISD::AVGCEILS: {
3778 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3779 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3780 Known = KnownBits::avgCeilS(Known, Known2);
3781 break;
3782 }
3783 case ISD::SELECT:
3784 case ISD::VSELECT:
3785 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3786 // If we don't know any bits, early out.
3787 if (Known.isUnknown())
3788 break;
3789 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3790
3791 // Only known if known in both the LHS and RHS.
3792 Known = Known.intersectWith(Known2);
3793 break;
3794 case ISD::SELECT_CC:
3795 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3796 // If we don't know any bits, early out.
3797 if (Known.isUnknown())
3798 break;
3799 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3800
3801 // Only known if known in both the LHS and RHS.
3802 Known = Known.intersectWith(Known2);
3803 break;
3804 case ISD::SMULO:
3805 case ISD::UMULO:
3806 if (Op.getResNo() != 1)
3807 break;
3808 // The boolean result conforms to getBooleanContents.
3809 // If we know the result of a setcc has the top bits zero, use this info.
3810 // We know that we have an integer-based boolean since these operations
3811 // are only available for integer.
3812 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3814 BitWidth > 1)
3815 Known.Zero.setBitsFrom(1);
3816 break;
3817 case ISD::SETCC:
3818 case ISD::SETCCCARRY:
3819 case ISD::STRICT_FSETCC:
3820 case ISD::STRICT_FSETCCS: {
3821 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3822 // If we know the result of a setcc has the top bits zero, use this info.
3823 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3825 BitWidth > 1)
3826 Known.Zero.setBitsFrom(1);
3827 break;
3828 }
3829 case ISD::SHL: {
3830 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3831 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3832
3833 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3834 bool NSW = Op->getFlags().hasNoSignedWrap();
3835
3836 bool ShAmtNonZero = Known2.isNonZero();
3837
3838 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3839
3840 // Minimum shift low bits are known zero.
3841 if (std::optional<unsigned> ShMinAmt =
3842 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3843 Known.Zero.setLowBits(*ShMinAmt);
3844 break;
3845 }
3846 case ISD::SRL:
3847 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3848 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3849 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3850 Op->getFlags().hasExact());
3851
3852 // Minimum shift high bits are known zero.
3853 if (std::optional<unsigned> ShMinAmt =
3854 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3855 Known.Zero.setHighBits(*ShMinAmt);
3856 break;
3857 case ISD::SRA:
3858 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3859 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3860 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3861 Op->getFlags().hasExact());
3862 break;
3863 case ISD::ROTL:
3864 case ISD::ROTR:
3865 if (ConstantSDNode *C =
3866 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3867 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3868
3869 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3870
3871 // Canonicalize to ROTR.
3872 if (Opcode == ISD::ROTL && Amt != 0)
3873 Amt = BitWidth - Amt;
3874
3875 Known.Zero = Known.Zero.rotr(Amt);
3876 Known.One = Known.One.rotr(Amt);
3877 }
3878 break;
3879 case ISD::FSHL:
3880 case ISD::FSHR:
3881 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3882 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3883
3884 // For fshl, 0-shift returns the 1st arg.
3885 // For fshr, 0-shift returns the 2nd arg.
3886 if (Amt == 0) {
3887 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3888 DemandedElts, Depth + 1);
3889 break;
3890 }
3891
3892 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3893 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3894 const APInt ShAmt(BitWidth, Amt);
3895 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3896 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3897 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3898 : KnownBits::fshr(Known, Known2, ShAmt);
3899 }
3900 break;
3901 case ISD::SHL_PARTS:
3902 case ISD::SRA_PARTS:
3903 case ISD::SRL_PARTS: {
3904 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3905
3906 // Collect lo/hi source values and concatenate.
3907 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3908 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3909 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3910 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3911 Known = Known2.concat(Known);
3912
3913 // Collect shift amount.
3914 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3915
3916 if (Opcode == ISD::SHL_PARTS)
3917 Known = KnownBits::shl(Known, Known2);
3918 else if (Opcode == ISD::SRA_PARTS)
3919 Known = KnownBits::ashr(Known, Known2);
3920 else // if (Opcode == ISD::SRL_PARTS)
3921 Known = KnownBits::lshr(Known, Known2);
3922
3923 // TODO: Minimum shift low/high bits are known zero.
3924
3925 if (Op.getResNo() == 0)
3926 Known = Known.extractBits(LoBits, 0);
3927 else
3928 Known = Known.extractBits(HiBits, LoBits);
3929 break;
3930 }
3932 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3933 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3934 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3935 break;
3936 }
3937 case ISD::CTTZ:
3938 case ISD::CTTZ_ZERO_POISON: {
3939 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3940 // If we have a known 1, its position is our upper bound.
3941 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3942 unsigned LowBits = llvm::bit_width(PossibleTZ);
3943 Known.Zero.setBitsFrom(LowBits);
3944 break;
3945 }
3946 case ISD::CTLZ:
3947 case ISD::CTLZ_ZERO_POISON: {
3948 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3949 // If we have a known 1, its position is our upper bound.
3950 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3951 unsigned LowBits = llvm::bit_width(PossibleLZ);
3952 Known.Zero.setBitsFrom(LowBits);
3953 break;
3954 }
3955 case ISD::CTLS: {
3956 unsigned MinRedundantSignBits =
3957 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3958 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3960 Known = Range.toKnownBits();
3961 break;
3962 }
3963 case ISD::CTPOP: {
3964 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3965 // If we know some of the bits are zero, they can't be one.
3966 unsigned PossibleOnes = Known2.countMaxPopulation();
3967 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3968 break;
3969 }
3970 case ISD::PARITY: {
3971 // Parity returns 0 everywhere but the LSB.
3972 Known.Zero.setBitsFrom(1);
3973 break;
3974 }
3975 case ISD::PDEP: {
3976 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3977 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3978 Known = KnownBits::pdep(Known2, Known);
3979 break;
3980 }
3981 case ISD::PEXT: {
3982 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3983 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3984 Known = KnownBits::pext(Known2, Known);
3985 break;
3986 }
3987 case ISD::CLMUL: {
3988 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3989 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3990 Known = KnownBits::clmul(Known, Known2);
3991 break;
3992 }
3993 case ISD::MGATHER:
3994 case ISD::MLOAD: {
3995 ISD::LoadExtType ETy =
3996 (Opcode == ISD::MGATHER)
3997 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3998 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3999 if (ETy == ISD::ZEXTLOAD) {
4000 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
4001 KnownBits Known0(MemVT.getScalarSizeInBits());
4002 return Known0.zext(BitWidth);
4003 }
4004 break;
4005 }
4006 case ISD::LOAD: {
4008 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4009 if (ISD::isNON_EXTLoad(LD) && Cst) {
4010 // Determine any common known bits from the loaded constant pool value.
4011 Type *CstTy = Cst->getType();
4012 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4013 !Op.getValueType().isScalableVector()) {
4014 // If its a vector splat, then we can (quickly) reuse the scalar path.
4015 // NOTE: We assume all elements match and none are UNDEF.
4016 if (CstTy->isVectorTy()) {
4017 if (const Constant *Splat = Cst->getSplatValue()) {
4018 Cst = Splat;
4019 CstTy = Cst->getType();
4020 }
4021 }
4022 // TODO - do we need to handle different bitwidths?
4023 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4024 // Iterate across all vector elements finding common known bits.
4025 Known.setAllConflict();
4026 for (unsigned i = 0; i != NumElts; ++i) {
4027 if (!DemandedElts[i])
4028 continue;
4029 if (Constant *Elt = Cst->getAggregateElement(i)) {
4030 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4031 const APInt &Value = CInt->getValue();
4032 Known.One &= Value;
4033 Known.Zero &= ~Value;
4034 continue;
4035 }
4036 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4037 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4038 Known.One &= Value;
4039 Known.Zero &= ~Value;
4040 continue;
4041 }
4042 }
4043 Known.One.clearAllBits();
4044 Known.Zero.clearAllBits();
4045 break;
4046 }
4047 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4048 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4049 Known = KnownBits::makeConstant(CInt->getValue());
4050 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4051 Known =
4052 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4053 }
4054 }
4055 }
4056 } else if (Op.getResNo() == 0) {
4057 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4058 KnownBits KnownScalarMemory(ScalarMemorySize);
4059 if (const MDNode *MD = LD->getRanges())
4060 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4061
4062 // Extend the Known bits from memory to the size of the scalar result.
4063 if (ISD::isZEXTLoad(Op.getNode()))
4064 Known = KnownScalarMemory.zext(BitWidth);
4065 else if (ISD::isSEXTLoad(Op.getNode()))
4066 Known = KnownScalarMemory.sext(BitWidth);
4067 else if (ISD::isEXTLoad(Op.getNode()))
4068 Known = KnownScalarMemory.anyext(BitWidth);
4069 else
4070 Known = KnownScalarMemory;
4071 assert(Known.getBitWidth() == BitWidth);
4072 return Known;
4073 }
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 Known = Known.zext(BitWidth);
4083 break;
4084 }
4085 case ISD::ZERO_EXTEND: {
4086 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4087 Known = Known.zext(BitWidth);
4088 break;
4089 }
4091 if (Op.getValueType().isScalableVector())
4092 break;
4093 EVT InVT = Op.getOperand(0).getValueType();
4094 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4095 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4096 // If the sign bit is known to be zero or one, then sext will extend
4097 // it to the top bits, else it will just zext.
4098 Known = Known.sext(BitWidth);
4099 break;
4100 }
4101 case ISD::SIGN_EXTEND: {
4102 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4103 // If the sign bit is known to be zero or one, then sext will extend
4104 // it to the top bits, else it will just zext.
4105 Known = Known.sext(BitWidth);
4106 break;
4107 }
4109 if (Op.getValueType().isScalableVector())
4110 break;
4111 EVT InVT = Op.getOperand(0).getValueType();
4112 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4113 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4114 Known = Known.anyext(BitWidth);
4115 break;
4116 }
4117 case ISD::ANY_EXTEND: {
4118 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4119 Known = Known.anyext(BitWidth);
4120 break;
4121 }
4122 case ISD::TRUNCATE: {
4123 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4124 Known = Known.trunc(BitWidth);
4125 break;
4126 }
4127 case ISD::TRUNCATE_SSAT_S: {
4128 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4129 Known = Known.truncSSat(BitWidth);
4130 break;
4131 }
4132 case ISD::TRUNCATE_SSAT_U: {
4133 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4134 Known = Known.truncSSatU(BitWidth);
4135 break;
4136 }
4137 case ISD::TRUNCATE_USAT_U: {
4138 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4139 Known = Known.truncUSat(BitWidth);
4140 break;
4141 }
4142 case ISD::AssertZext: {
4143 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4145 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4146 Known.Zero |= (~InMask);
4147 Known.One &= (~Known.Zero);
4148 break;
4149 }
4150 case ISD::AssertAlign: {
4151 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4152 assert(LogOfAlign != 0);
4153
4154 // TODO: Should use maximum with source
4155 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4156 // well as clearing one bits.
4157 Known.Zero.setLowBits(LogOfAlign);
4158 Known.One.clearLowBits(LogOfAlign);
4159 break;
4160 }
4161 case ISD::AssertNoFPClass: {
4162 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4163
4164 FPClassTest NoFPClass =
4165 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4166 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4167 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4168 // Cannot be negative.
4169 Known.makeNonNegative();
4170 }
4171
4172 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4173 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4174 // Cannot be positive.
4175 Known.makeNegative();
4176 }
4177
4178 break;
4179 }
4180 case ISD::FABS:
4181 // fabs clears the sign bit
4182 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4183 Known.makeNonNegative();
4184 break;
4185 case ISD::FGETSIGN:
4186 // All bits are zero except the low bit.
4187 Known.Zero.setBitsFrom(1);
4188 break;
4189 case ISD::ADD: {
4190 SDNodeFlags Flags = Op.getNode()->getFlags();
4191 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4192 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4193 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4195 Op.getOperand(0), DemandedElts,
4197 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4198 Flags.hasNoUnsignedWrap(), SelfAdd);
4199 break;
4200 }
4201 case ISD::SUB: {
4202 SDNodeFlags Flags = Op.getNode()->getFlags();
4203 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4204 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4205 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4206 Flags.hasNoUnsignedWrap());
4207 break;
4208 }
4209 case ISD::USUBO:
4210 case ISD::SSUBO:
4211 case ISD::USUBO_CARRY:
4212 case ISD::SSUBO_CARRY:
4213 if (Op.getResNo() == 1) {
4214 // If we know the result of a setcc has the top bits zero, use this info.
4215 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4217 BitWidth > 1)
4218 Known.Zero.setBitsFrom(1);
4219 break;
4220 }
4221 [[fallthrough]];
4222 case ISD::SUBC: {
4223 assert(Op.getResNo() == 0 &&
4224 "We only compute knownbits for the difference here.");
4225
4226 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4227 KnownBits Borrow(1);
4228 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4229 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4230 // Borrow has bit width 1
4231 Borrow = Borrow.trunc(1);
4232 } else {
4233 Borrow.setAllZero();
4234 }
4235
4236 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4237 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4238 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4239 break;
4240 }
4241 case ISD::UADDO:
4242 case ISD::SADDO:
4243 case ISD::UADDO_CARRY:
4244 case ISD::SADDO_CARRY:
4245 if (Op.getResNo() == 1) {
4246 // If we know the result of a setcc has the top bits zero, use this info.
4247 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4249 BitWidth > 1)
4250 Known.Zero.setBitsFrom(1);
4251 break;
4252 }
4253 [[fallthrough]];
4254 case ISD::ADDC:
4255 case ISD::ADDE: {
4256 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4257
4258 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4259 KnownBits Carry(1);
4260 if (Opcode == ISD::ADDE)
4261 // Can't track carry from glue, set carry to unknown.
4262 Carry.resetAll();
4263 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4264 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4265 // Carry has bit width 1
4266 Carry = Carry.trunc(1);
4267 } else {
4268 Carry.setAllZero();
4269 }
4270
4271 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4272 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4273 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4274 break;
4275 }
4276 case ISD::UDIV: {
4277 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4278 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4279 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4280 break;
4281 }
4282 case ISD::SDIV: {
4283 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4284 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4285 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4286 break;
4287 }
4288 case ISD::SREM: {
4289 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4290 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4291 Known = KnownBits::srem(Known, Known2);
4292 break;
4293 }
4294 case ISD::UREM: {
4295 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4296 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4297 Known = KnownBits::urem(Known, Known2);
4298 break;
4299 }
4300 case ISD::EXTRACT_ELEMENT: {
4301 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4302 const unsigned Index = Op.getConstantOperandVal(1);
4303 const unsigned EltBitWidth = Op.getValueSizeInBits();
4304
4305 // Remove low part of known bits mask
4306 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4307 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4308
4309 // Remove high part of known bit mask
4310 Known = Known.trunc(EltBitWidth);
4311 break;
4312 }
4314 SDValue InVec = Op.getOperand(0);
4315 SDValue EltNo = Op.getOperand(1);
4316 EVT VecVT = InVec.getValueType();
4317 // computeKnownBits not yet implemented for scalable vectors.
4318 if (VecVT.isScalableVector())
4319 break;
4320 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4321 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4322
4323 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4324 // anything about the extended bits.
4325 if (BitWidth > EltBitWidth)
4326 Known = Known.trunc(EltBitWidth);
4327
4328 // If we know the element index, just demand that vector element, else for
4329 // an unknown element index, ignore DemandedElts and demand them all.
4330 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4331 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4332 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4333 DemandedSrcElts =
4334 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4335
4336 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4337 if (BitWidth > EltBitWidth)
4338 Known = Known.anyext(BitWidth);
4339 break;
4340 }
4342 if (Op.getValueType().isScalableVector())
4343 break;
4344
4345 // If we know the element index, split the demand between the
4346 // source vector and the inserted element, otherwise assume we need
4347 // the original demanded vector elements and the value.
4348 SDValue InVec = Op.getOperand(0);
4349 SDValue InVal = Op.getOperand(1);
4350 SDValue EltNo = Op.getOperand(2);
4351 bool DemandedVal = true;
4352 APInt DemandedVecElts = DemandedElts;
4353 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4354 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4355 unsigned EltIdx = CEltNo->getZExtValue();
4356 DemandedVal = !!DemandedElts[EltIdx];
4357 DemandedVecElts.clearBit(EltIdx);
4358 }
4359 Known.setAllConflict();
4360 if (DemandedVal) {
4361 Known2 = computeKnownBits(InVal, Depth + 1);
4362 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4363 }
4364 if (!!DemandedVecElts) {
4365 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4366 Known = Known.intersectWith(Known2);
4367 }
4368 break;
4369 }
4370 case ISD::BITREVERSE: {
4371 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4372 Known = Known2.reverseBits();
4373 break;
4374 }
4375 case ISD::BSWAP: {
4376 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4377 Known = Known2.byteSwap();
4378 break;
4379 }
4380 case ISD::ABS:
4381 case ISD::ABS_MIN_POISON: {
4382 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4383 Known = Known2.abs();
4384 Known.Zero.setHighBits(
4385 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4386 break;
4387 }
4388 case ISD::USUBSAT: {
4389 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4390 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4391 Known = KnownBits::usub_sat(Known, Known2);
4392 break;
4393 }
4394 case ISD::UMIN: {
4395 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4396 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4397 Known = KnownBits::umin(Known, Known2);
4398 break;
4399 }
4400 case ISD::UMAX: {
4401 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4402 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4403 Known = KnownBits::umax(Known, Known2);
4404 break;
4405 }
4406 case ISD::SMIN:
4407 case ISD::SMAX: {
4408 // If we have a clamp pattern, we know that the number of sign bits will be
4409 // the minimum of the clamp min/max range.
4410 bool IsMax = (Opcode == ISD::SMAX);
4411 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4412 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4413 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4414 CstHigh =
4415 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4416 if (CstLow && CstHigh) {
4417 if (!IsMax)
4418 std::swap(CstLow, CstHigh);
4419
4420 const APInt &ValueLow = CstLow->getAPIntValue();
4421 const APInt &ValueHigh = CstHigh->getAPIntValue();
4422 if (ValueLow.sle(ValueHigh)) {
4423 unsigned LowSignBits = ValueLow.getNumSignBits();
4424 unsigned HighSignBits = ValueHigh.getNumSignBits();
4425 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4426 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4427 Known.One.setHighBits(MinSignBits);
4428 break;
4429 }
4430 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4431 Known.Zero.setHighBits(MinSignBits);
4432 break;
4433 }
4434 }
4435 }
4436
4437 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4438 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4439 if (IsMax)
4440 Known = KnownBits::smax(Known, Known2);
4441 else
4442 Known = KnownBits::smin(Known, Known2);
4443
4444 // For SMAX, if CstLow is non-negative we know the result will be
4445 // non-negative and thus all sign bits are 0.
4446 // TODO: There's an equivalent of this for smin with negative constant for
4447 // known ones.
4448 if (IsMax && CstLow) {
4449 const APInt &ValueLow = CstLow->getAPIntValue();
4450 if (ValueLow.isNonNegative()) {
4451 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4452 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4453 }
4454 }
4455
4456 break;
4457 }
4458 case ISD::UINT_TO_FP: {
4459 Known.makeNonNegative();
4460 break;
4461 }
4462 case ISD::SINT_TO_FP: {
4463 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4464 if (Known2.isNonNegative())
4465 Known.makeNonNegative();
4466 else if (Known2.isNegative())
4467 Known.makeNegative();
4468 break;
4469 }
4470 case ISD::FP_TO_UINT_SAT: {
4471 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4472 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4474 break;
4475 }
4476 case ISD::ATOMIC_LOAD: {
4477 // If we are looking at the loaded value.
4478 if (Op.getResNo() == 0) {
4479 auto *AT = cast<AtomicSDNode>(Op);
4480 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4481 KnownBits KnownScalarMemory(ScalarMemorySize);
4482 if (const MDNode *MD = AT->getRanges())
4483 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4484
4485 switch (AT->getExtensionType()) {
4486 case ISD::ZEXTLOAD:
4487 Known = KnownScalarMemory.zext(BitWidth);
4488 break;
4489 case ISD::SEXTLOAD:
4490 Known = KnownScalarMemory.sext(BitWidth);
4491 break;
4492 case ISD::EXTLOAD:
4493 switch (TLI->getExtendForAtomicOps()) {
4494 case ISD::ZERO_EXTEND:
4495 Known = KnownScalarMemory.zext(BitWidth);
4496 break;
4497 case ISD::SIGN_EXTEND:
4498 Known = KnownScalarMemory.sext(BitWidth);
4499 break;
4500 default:
4501 Known = KnownScalarMemory.anyext(BitWidth);
4502 break;
4503 }
4504 break;
4505 case ISD::NON_EXTLOAD:
4506 Known = KnownScalarMemory;
4507 break;
4508 }
4509 assert(Known.getBitWidth() == BitWidth);
4510 }
4511 break;
4512 }
4514 if (Op.getResNo() == 1) {
4515 // The boolean result conforms to getBooleanContents.
4516 // If we know the result of a setcc has the top bits zero, use this info.
4517 // We know that we have an integer-based boolean since these operations
4518 // are only available for integer.
4519 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4521 BitWidth > 1)
4522 Known.Zero.setBitsFrom(1);
4523 break;
4524 }
4525 [[fallthrough]];
4527 case ISD::ATOMIC_SWAP:
4538 case ISD::ATOMIC_LOAD_UMAX: {
4539 // If we are looking at the loaded value.
4540 if (Op.getResNo() == 0) {
4541 auto *AT = cast<AtomicSDNode>(Op);
4542 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4543
4544 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4545 Known.Zero.setBitsFrom(MemBits);
4546 }
4547 break;
4548 }
4549 case ISD::FrameIndex:
4550 case ISD::TargetFrameIndex: {
4551 const MachineFunction &MF = getMachineFunction();
4552 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4553 TLI->computeKnownBitsForStackObjectPointer(
4554 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4555 break;
4556 }
4557
4558 default:
4559 if (Opcode < ISD::BUILTIN_OP_END)
4560 break;
4561 [[fallthrough]];
4565 // Allow the target to implement this method for its nodes.
4566 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4567 break;
4568 }
4569
4570 return Known;
4571}
4572
4573/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4586
4589 // X + 0 never overflow
4590 if (isNullConstant(N1))
4591 return OFK_Never;
4592
4593 // If both operands each have at least two sign bits, the addition
4594 // cannot overflow.
4595 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4596 return OFK_Never;
4597
4598 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4599 return OFK_Sometime;
4600}
4601
4604 // X + 0 never overflow
4605 if (isNullConstant(N1))
4606 return OFK_Never;
4607
4608 // mulhi + 1 never overflow
4609 KnownBits N1Known = computeKnownBits(N1);
4610 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4611 N1Known.getMaxValue().ult(2))
4612 return OFK_Never;
4613
4614 KnownBits N0Known = computeKnownBits(N0);
4615 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4616 N0Known.getMaxValue().ult(2))
4617 return OFK_Never;
4618
4619 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4620 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4621 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4622 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4623}
4624
4627 // X - 0 never overflow
4628 if (isNullConstant(N1))
4629 return OFK_Never;
4630
4631 // If both operands each have at least two sign bits, the subtraction
4632 // cannot overflow.
4633 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4634 return OFK_Never;
4635
4636 KnownBits N0Known = computeKnownBits(N0);
4637 KnownBits N1Known = computeKnownBits(N1);
4638 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4639 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4640 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4641}
4642
4645 // X - 0 never overflow
4646 if (isNullConstant(N1))
4647 return OFK_Never;
4648
4649 ConstantRange N0Range =
4650 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4651 ConstantRange N1Range =
4652 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4653 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4654}
4655
4658 // X * 0 and X * 1 never overflow.
4659 if (isNullConstant(N1) || isOneConstant(N1))
4660 return OFK_Never;
4661
4664 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4665}
4666
4669 // X * 0 and X * 1 never overflow.
4670 if (isNullConstant(N1) || isOneConstant(N1))
4671 return OFK_Never;
4672
4673 // Get the size of the result.
4674 unsigned BitWidth = N0.getScalarValueSizeInBits();
4675
4676 // Sum of the sign bits.
4677 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4678
4679 // If we have enough sign bits, then there's no overflow.
4680 if (SignBits > BitWidth + 1)
4681 return OFK_Never;
4682
4683 if (SignBits == BitWidth + 1) {
4684 // The overflow occurs when the true multiplication of the
4685 // the operands is the minimum negative number.
4686 KnownBits N0Known = computeKnownBits(N0);
4687 KnownBits N1Known = computeKnownBits(N1);
4688 // If one of the operands is non-negative, then there's no
4689 // overflow.
4690 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4691 return OFK_Never;
4692 }
4693
4694 return OFK_Sometime;
4695}
4696
4698 unsigned Depth) const {
4699 APInt DemandedElts = getDemandAllEltsMask(Op);
4700 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4701}
4702
4704 const APInt &DemandedElts,
4705 bool ForSigned,
4706 unsigned Depth) const {
4707 EVT VT = Op.getValueType();
4708 unsigned BitWidth = VT.getScalarSizeInBits();
4709
4710 if (Depth >= MaxRecursionDepth)
4711 return ConstantRange::getFull(BitWidth);
4712
4713 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4714 return ConstantRange(C->getAPIntValue());
4715
4716 unsigned Opcode = Op.getOpcode();
4717 switch (Opcode) {
4718 case ISD::VSCALE: {
4720 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4721 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4722 }
4723 default:
4724 break;
4725 }
4726
4727 return ConstantRange::getFull(BitWidth);
4728}
4729
4732 unsigned Depth) const {
4733 APInt DemandedElts = getDemandAllEltsMask(Op);
4734 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4735 Depth);
4736}
4737
4739 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4740 unsigned Depth) const {
4741 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4743 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4746 return CR1.intersectWith(CR2, RangeType);
4747}
4748
4750 unsigned Depth) const {
4751 APInt DemandedElts = getDemandAllEltsMask(Val);
4752 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4753}
4754
4756 const APInt &DemandedElts,
4757 bool OrZero, unsigned Depth) const {
4758 if (Depth >= MaxRecursionDepth)
4759 return false; // Limit search depth.
4760
4761 EVT OpVT = Val.getValueType();
4762 unsigned BitWidth = OpVT.getScalarSizeInBits();
4763 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4764 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4765 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4766 assert(
4767 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4768 "Unexpected vector size");
4769
4770 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4771 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4772 return (OrZero && V.isZero()) || V.isPowerOf2();
4773 };
4774
4775 // Is the constant a known power of 2 or zero?
4776 if (ISD::matchUnaryPredicate(Val, IsPowerOfTwoOrZero))
4777 return true;
4778
4779 switch (Val.getOpcode()) {
4780 case ISD::BUILD_VECTOR:
4781 // Are all operands of a build vector constant powers of two or zero?
4782 if (all_of(enumerate(Val->ops()), [&](auto P) {
4783 auto *C = dyn_cast<ConstantSDNode>(P.value());
4784 return !DemandedElts[P.index()] || (C && IsPowerOfTwoOrZero(C));
4785 }))
4786 return true;
4787 break;
4788
4789 case ISD::SPLAT_VECTOR:
4790 // Is the operand of a splat vector a constant power of two?
4791 if (auto *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
4792 if (IsPowerOfTwoOrZero(C))
4793 return true;
4794 break;
4795
4797 SDValue InVec = Val.getOperand(0);
4798 SDValue EltNo = Val.getOperand(1);
4799 EVT VecVT = InVec.getValueType();
4800
4801 // Skip scalable vectors or implicit extensions.
4802 if (VecVT.isScalableVector() ||
4803 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4804 break;
4805
4806 // If we know the element index, just demand that vector element, else for
4807 // an unknown element index, ignore DemandedElts and demand them all.
4808 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4809 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4810 APInt DemandedSrcElts =
4811 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4812 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4813 : APInt::getAllOnes(NumSrcElts);
4814 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4815 }
4816
4817 case ISD::AND: {
4818 // Looking for `x & -x` pattern:
4819 // If x == 0:
4820 // x & -x -> 0
4821 // If x != 0:
4822 // x & -x -> non-zero pow2
4823 // so if we find the pattern return whether we know `x` is non-zero.
4824 SDValue X, Z;
4825 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4826 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4827 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4828 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4829 break;
4830 }
4831
4832 case ISD::SHL: {
4833 // A left-shift of a constant one will have exactly one bit set because
4834 // shifting the bit off the end is undefined.
4835 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4836 if (C && C->getAPIntValue() == 1)
4837 return true;
4838 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4839 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4840 Depth + 1);
4841 }
4842
4843 case ISD::SRL: {
4844 // A logical right-shift of a constant sign-bit will have exactly
4845 // one bit set.
4846 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4847 if (C && C->getAPIntValue().isSignMask())
4848 return true;
4849 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4850 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4851 Depth + 1);
4852 }
4853
4854 case ISD::TRUNCATE:
4855 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4856 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4857 Depth + 1);
4858
4859 case ISD::ROTL:
4860 case ISD::ROTR:
4861 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4862 Depth + 1);
4863 case ISD::BSWAP:
4864 case ISD::BITREVERSE:
4865 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4866 Depth + 1);
4867
4868 case ISD::SMIN:
4869 case ISD::SMAX:
4870 case ISD::UMIN:
4871 case ISD::UMAX:
4872 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4873 Depth + 1) &&
4874 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4875 Depth + 1);
4876
4877 case ISD::SELECT:
4878 case ISD::VSELECT:
4879 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4880 Depth + 1) &&
4881 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4882 Depth + 1);
4883
4884 case ISD::ZERO_EXTEND:
4885 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4886 Depth + 1);
4887
4888 case ISD::VSCALE:
4889 // vscale(power-of-two) is a power-of-two
4890 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4891 Depth + 1);
4892
4893 case ISD::VECTOR_SHUFFLE: {
4895 // Demanded elements with undef shuffle mask elements are unknown
4896 // - we cannot guarantee they are a power of two, so return false.
4897 APInt DemandedLHS, DemandedRHS;
4899 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4900 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4901 DemandedLHS, DemandedRHS))
4902 return false;
4903
4904 // All demanded elements from LHS must be known power of two.
4905 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4906 OrZero, Depth + 1))
4907 return false;
4908
4909 // All demanded elements from RHS must be known power of two.
4910 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4911 OrZero, Depth + 1))
4912 return false;
4913
4914 return true;
4915 }
4916 }
4917
4918 // More could be done here, though the above checks are enough
4919 // to handle some common cases.
4920 return false;
4921}
4922
4924 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4925 return C1->getValueAPF().getExactLog2Abs() >= 0;
4926
4927 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4928 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4929
4930 return false;
4931}
4932
4934 APInt DemandedElts = getDemandAllEltsMask(Op);
4935 return ComputeNumSignBits(Op, DemandedElts, Depth);
4936}
4937
4938unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4939 unsigned Depth) const {
4940 EVT VT = Op.getValueType();
4941 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4942 unsigned VTBits = VT.getScalarSizeInBits();
4943 unsigned NumElts = DemandedElts.getBitWidth();
4944 unsigned Tmp, Tmp2;
4945 unsigned FirstAnswer = 1;
4946
4947 assert((!VT.isScalableVector() || NumElts == 1) &&
4948 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4949
4950 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4951 const APInt &Val = C->getAPIntValue();
4952 return Val.getNumSignBits();
4953 }
4954
4955 if (Depth >= MaxRecursionDepth)
4956 return 1; // Limit search depth.
4957
4958 if (!DemandedElts)
4959 return 1; // No demanded elts, better to assume we don't know anything.
4960
4961 unsigned Opcode = Op.getOpcode();
4962 switch (Opcode) {
4963 default: break;
4964 case ISD::AssertSext:
4965 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4966 return VTBits-Tmp+1;
4967 case ISD::AssertZext:
4968 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4969 return VTBits-Tmp;
4970 case ISD::FREEZE:
4971 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4973 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4974 break;
4975 case ISD::MERGE_VALUES:
4976 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4977 Depth + 1);
4978 case ISD::SPLAT_VECTOR: {
4979 // Check if the sign bits of source go down as far as the truncated value.
4980 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4981 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4982 if (NumSrcSignBits > (NumSrcBits - VTBits))
4983 return NumSrcSignBits - (NumSrcBits - VTBits);
4984 break;
4985 }
4986 case ISD::BUILD_VECTOR:
4987 assert(!VT.isScalableVector());
4988 Tmp = VTBits;
4989 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4990 if (!DemandedElts[i])
4991 continue;
4992
4993 SDValue SrcOp = Op.getOperand(i);
4994 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4995 // for constant nodes to ensure we only look at the sign bits.
4997 APInt T = C->getAPIntValue().trunc(VTBits);
4998 Tmp2 = T.getNumSignBits();
4999 } else {
5000 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
5001
5002 if (SrcOp.getValueSizeInBits() != VTBits) {
5003 assert(SrcOp.getValueSizeInBits() > VTBits &&
5004 "Expected BUILD_VECTOR implicit truncation");
5005 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
5006 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5007 }
5008 }
5009 Tmp = std::min(Tmp, Tmp2);
5010 }
5011 return Tmp;
5012
5013 case ISD::VECTOR_COMPRESS: {
5014 SDValue Vec = Op.getOperand(0);
5015 SDValue PassThru = Op.getOperand(2);
5016 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5017 if (Tmp == 1)
5018 return 1;
5019 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5020 Tmp = std::min(Tmp, Tmp2);
5021 return Tmp;
5022 }
5023
5024 case ISD::VECTOR_SHUFFLE: {
5025 // Collect the minimum number of sign bits that are shared by every vector
5026 // element referenced by the shuffle.
5027 APInt DemandedLHS, DemandedRHS;
5029 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5030 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5031 DemandedLHS, DemandedRHS))
5032 return 1;
5033
5034 Tmp = std::numeric_limits<unsigned>::max();
5035 if (!!DemandedLHS)
5036 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5037 if (!!DemandedRHS) {
5038 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5039 Tmp = std::min(Tmp, Tmp2);
5040 }
5041 // If we don't know anything, early out and try computeKnownBits fall-back.
5042 if (Tmp == 1)
5043 break;
5044 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5045 return Tmp;
5046 }
5047
5048 case ISD::BITCAST: {
5049 if (VT.isScalableVector())
5050 break;
5051 SDValue N0 = Op.getOperand(0);
5052 EVT SrcVT = N0.getValueType();
5053 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5054
5055 // Ignore bitcasts from unsupported types..
5056 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5057 break;
5058
5059 // Fast handling of 'identity' bitcasts.
5060 if (VTBits == SrcBits)
5061 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5062
5063 bool IsLE = getDataLayout().isLittleEndian();
5064
5065 // Bitcast 'large element' scalar/vector to 'small element' vector.
5066 if ((SrcBits % VTBits) == 0) {
5067 assert(VT.isVector() && "Expected bitcast to vector");
5068
5069 unsigned Scale = SrcBits / VTBits;
5070 APInt SrcDemandedElts =
5071 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5072
5073 // Fast case - sign splat can be simply split across the small elements.
5074 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5075 if (Tmp == SrcBits)
5076 return VTBits;
5077
5078 // Slow case - determine how far the sign extends into each sub-element.
5079 Tmp2 = VTBits;
5080 for (unsigned i = 0; i != NumElts; ++i)
5081 if (DemandedElts[i]) {
5082 unsigned SubOffset = i % Scale;
5083 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5084 SubOffset = SubOffset * VTBits;
5085 if (Tmp <= SubOffset)
5086 return 1;
5087 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5088 }
5089 return Tmp2;
5090 }
5091 break;
5092 }
5093
5095 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5096 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5097 return VTBits - Tmp + 1;
5098 case ISD::SIGN_EXTEND:
5099 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5100 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5102 // Max of the input and what this extends.
5103 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5104 Tmp = VTBits-Tmp+1;
5105 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5106 return std::max(Tmp, Tmp2);
5108 if (VT.isScalableVector())
5109 break;
5110 SDValue Src = Op.getOperand(0);
5111 EVT SrcVT = Src.getValueType();
5112 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5113 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5114 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5115 }
5116 case ISD::SRA:
5117 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5118 // SRA X, C -> adds C sign bits.
5119 if (std::optional<unsigned> ShAmt =
5120 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5121 Tmp = std::min(Tmp + *ShAmt, VTBits);
5122 return Tmp;
5123 case ISD::SHL:
5124 if (std::optional<ConstantRange> ShAmtRange =
5125 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5126 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5127 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5128 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5129 // shifted out, then we can compute the number of sign bits for the
5130 // operand being extended. A future improvement could be to pass along the
5131 // "shifted left by" information in the recursive calls to
5132 // ComputeKnownSignBits. Allowing us to handle this more generically.
5133 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5134 SDValue Ext = Op.getOperand(0);
5135 EVT ExtVT = Ext.getValueType();
5136 SDValue Extendee = Ext.getOperand(0);
5137 EVT ExtendeeVT = Extendee.getValueType();
5138 unsigned SizeDifference =
5139 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5140 if (SizeDifference <= MinShAmt) {
5141 Tmp = SizeDifference +
5142 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5143 if (MaxShAmt < Tmp)
5144 return Tmp - MaxShAmt;
5145 }
5146 }
5147 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5148 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5149 if (MaxShAmt < Tmp)
5150 return Tmp - MaxShAmt;
5151 }
5152 break;
5153 case ISD::AND:
5154 case ISD::OR:
5155 case ISD::XOR: // NOT is handled here.
5156 // Logical binary ops preserve the number of sign bits at the worst.
5157 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5158 if (Tmp != 1) {
5159 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5160 FirstAnswer = std::min(Tmp, Tmp2);
5161 // We computed what we know about the sign bits as our first
5162 // answer. Now proceed to the generic code that uses
5163 // computeKnownBits, and pick whichever answer is better.
5164 }
5165 break;
5166
5167 case ISD::SELECT:
5168 case ISD::VSELECT:
5169 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5170 if (Tmp == 1) return 1; // Early out.
5171 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5172 return std::min(Tmp, Tmp2);
5173 case ISD::SELECT_CC:
5174 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5175 if (Tmp == 1) return 1; // Early out.
5176 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5177 return std::min(Tmp, Tmp2);
5178
5179 case ISD::SMIN:
5180 case ISD::SMAX: {
5181 // If we have a clamp pattern, we know that the number of sign bits will be
5182 // the minimum of the clamp min/max range.
5183 bool IsMax = (Opcode == ISD::SMAX);
5184 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5185 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5186 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5187 CstHigh =
5188 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5189 if (CstLow && CstHigh) {
5190 if (!IsMax)
5191 std::swap(CstLow, CstHigh);
5192 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5193 Tmp = CstLow->getAPIntValue().getNumSignBits();
5194 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5195 return std::min(Tmp, Tmp2);
5196 }
5197 }
5198
5199 // Fallback - just get the minimum number of sign bits of the operands.
5200 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5201 if (Tmp == 1)
5202 return 1; // Early out.
5203 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5204 return std::min(Tmp, Tmp2);
5205 }
5206 case ISD::UMIN:
5207 case ISD::UMAX:
5208 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5209 if (Tmp == 1)
5210 return 1; // Early out.
5211 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5212 return std::min(Tmp, Tmp2);
5213 case ISD::SSUBO_CARRY:
5214 case ISD::USUBO_CARRY:
5215 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5216 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5217 return VTBits;
5218 [[fallthrough]];
5219 case ISD::SADDO:
5220 case ISD::UADDO:
5221 case ISD::SADDO_CARRY:
5222 case ISD::UADDO_CARRY:
5223 case ISD::SSUBO:
5224 case ISD::USUBO:
5225 case ISD::SMULO:
5226 case ISD::UMULO:
5227 if (Op.getResNo() != 1)
5228 break;
5229 // The boolean result conforms to getBooleanContents. Fall through.
5230 // If setcc returns 0/-1, all bits are sign bits.
5231 // We know that we have an integer-based boolean since these operations
5232 // are only available for integer.
5233 if (TLI->getBooleanContents(VT.isVector(), false) ==
5235 return VTBits;
5236 break;
5237 case ISD::SETCC:
5238 case ISD::SETCCCARRY:
5239 case ISD::STRICT_FSETCC:
5240 case ISD::STRICT_FSETCCS: {
5241 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5242 // If setcc returns 0/-1, all bits are sign bits.
5243 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5245 return VTBits;
5246 break;
5247 }
5249 // Semantically similar to icmp ult.
5250 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5252 return VTBits;
5253 break;
5254 case ISD::ROTL:
5255 case ISD::ROTR: {
5256 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5257 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5258 FirstAnswer = SignBitsOps::rot(
5259 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5260 Opcode == ISD::ROTR);
5261 break;
5262 }
5263 case ISD::ADD:
5264 case ISD::ADDC:
5265 // TODO: Move Operand 1 check before Operand 0 check
5266 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5267 if (Tmp == 1) return 1; // Early out.
5268
5269 // Special case decrementing a value (ADD X, -1):
5270 if (ConstantSDNode *CRHS =
5271 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5272 if (CRHS->isAllOnes()) {
5274 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5275
5276 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5277 // sign bits set.
5278 if ((Known.Zero | 1).isAllOnes())
5279 return VTBits;
5280
5281 // If we are subtracting one from a positive number, there is no carry
5282 // out of the result.
5283 if (Known.isNonNegative())
5284 return Tmp;
5285 }
5286
5287 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5288 if (Tmp2 == 1) return 1; // Early out.
5289
5290 // Add can have at most one carry bit. Thus we know that the output
5291 // is, at worst, one more bit than the inputs.
5292 return std::min(Tmp, Tmp2) - 1;
5293 case ISD::SUB:
5294 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5295 if (Tmp2 == 1) return 1; // Early out.
5296
5297 // Handle NEG.
5298 if (ConstantSDNode *CLHS =
5299 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5300 if (CLHS->isZero()) {
5302 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5303 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5304 // sign bits set.
5305 if ((Known.Zero | 1).isAllOnes())
5306 return VTBits;
5307
5308 // If the input is known to be positive (the sign bit is known clear),
5309 // the output of the NEG has the same number of sign bits as the input.
5310 if (Known.isNonNegative())
5311 return Tmp2;
5312
5313 // Otherwise, we treat this like a SUB.
5314 }
5315
5316 // Sub can have at most one carry bit. Thus we know that the output
5317 // is, at worst, one more bit than the inputs.
5318 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5319 if (Tmp == 1) return 1; // Early out.
5320 return std::min(Tmp, Tmp2) - 1;
5321 case ISD::MUL: {
5322 // The output of the Mul can be at most twice the valid bits in the inputs.
5323 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5324 if (SignBitsOp0 == 1)
5325 break;
5326 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5327 if (SignBitsOp1 == 1)
5328 break;
5329 unsigned OutValidBits =
5330 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5331 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5332 }
5333 case ISD::AVGCEILS:
5334 case ISD::AVGFLOORS:
5335 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5336 if (Tmp == 1)
5337 return 1; // Early out.
5338 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5339 return std::min(Tmp, Tmp2);
5340 case ISD::SREM:
5341 // The sign bit is the LHS's sign bit, except when the result of the
5342 // remainder is zero. The magnitude of the result should be less than or
5343 // equal to the magnitude of the LHS. Therefore, the result should have
5344 // at least as many sign bits as the left hand side.
5345 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5346 case ISD::TRUNCATE: {
5347 // Check if the sign bits of source go down as far as the truncated value.
5348 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5349 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5350 if (NumSrcSignBits > (NumSrcBits - VTBits))
5351 return NumSrcSignBits - (NumSrcBits - VTBits);
5352 break;
5353 }
5354 case ISD::EXTRACT_ELEMENT: {
5355 if (VT.isScalableVector())
5356 break;
5357 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5358 const int BitWidth = Op.getValueSizeInBits();
5359 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5360
5361 // Get reverse index (starting from 1), Op1 value indexes elements from
5362 // little end. Sign starts at big end.
5363 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5364
5365 // If the sign portion ends in our element the subtraction gives correct
5366 // result. Otherwise it gives either negative or > bitwidth result
5367 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5368 }
5370 if (VT.isScalableVector())
5371 break;
5372 // If we know the element index, split the demand between the
5373 // source vector and the inserted element, otherwise assume we need
5374 // the original demanded vector elements and the value.
5375 SDValue InVec = Op.getOperand(0);
5376 SDValue InVal = Op.getOperand(1);
5377 SDValue EltNo = Op.getOperand(2);
5378 bool DemandedVal = true;
5379 APInt DemandedVecElts = DemandedElts;
5380 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5381 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5382 unsigned EltIdx = CEltNo->getZExtValue();
5383 DemandedVal = !!DemandedElts[EltIdx];
5384 DemandedVecElts.clearBit(EltIdx);
5385 }
5386 Tmp = std::numeric_limits<unsigned>::max();
5387 if (DemandedVal) {
5388 // TODO - handle implicit truncation of inserted elements.
5389 if (InVal.getScalarValueSizeInBits() != VTBits)
5390 break;
5391 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5392 Tmp = std::min(Tmp, Tmp2);
5393 }
5394 if (!!DemandedVecElts) {
5395 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5396 Tmp = std::min(Tmp, Tmp2);
5397 }
5398 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5399 return Tmp;
5400 }
5402 SDValue InVec = Op.getOperand(0);
5403 SDValue EltNo = Op.getOperand(1);
5404 EVT VecVT = InVec.getValueType();
5405 // ComputeNumSignBits not yet implemented for scalable vectors.
5406 if (VecVT.isScalableVector())
5407 break;
5408 const unsigned BitWidth = Op.getValueSizeInBits();
5409 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5410 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5411
5412 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5413 // anything about sign bits. But if the sizes match we can derive knowledge
5414 // about sign bits from the vector operand.
5415 if (BitWidth != EltBitWidth)
5416 break;
5417
5418 // If we know the element index, just demand that vector element, else for
5419 // an unknown element index, ignore DemandedElts and demand them all.
5420 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5421 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5422 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5423 DemandedSrcElts =
5424 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5425
5426 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5427 }
5429 // Offset the demanded elts by the subvector index.
5430 SDValue Src = Op.getOperand(0);
5431
5432 APInt DemandedSrcElts;
5433 if (Src.getValueType().isScalableVector())
5434 DemandedSrcElts = APInt(1, 1);
5435 else {
5436 uint64_t Idx = Op.getConstantOperandVal(1);
5437 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5438 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5439 }
5440 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5441 }
5442 case ISD::CONCAT_VECTORS: {
5443 if (VT.isScalableVector())
5444 break;
5445 // Determine the minimum number of sign bits across all demanded
5446 // elts of the input vectors. Early out if the result is already 1.
5447 Tmp = std::numeric_limits<unsigned>::max();
5448 EVT SubVectorVT = Op.getOperand(0).getValueType();
5449 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5450 unsigned NumSubVectors = Op.getNumOperands();
5451 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5452 APInt DemandedSub =
5453 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5454 if (!DemandedSub)
5455 continue;
5456 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5457 Tmp = std::min(Tmp, Tmp2);
5458 }
5459 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5460 return Tmp;
5461 }
5462 case ISD::INSERT_SUBVECTOR: {
5463 if (VT.isScalableVector())
5464 break;
5465 // Demand any elements from the subvector and the remainder from the src its
5466 // inserted into.
5467 SDValue Src = Op.getOperand(0);
5468 SDValue Sub = Op.getOperand(1);
5469 uint64_t Idx = Op.getConstantOperandVal(2);
5470 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5471 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5472 APInt DemandedSrcElts = DemandedElts;
5473 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5474
5475 Tmp = std::numeric_limits<unsigned>::max();
5476 if (!!DemandedSubElts) {
5477 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5478 if (Tmp == 1)
5479 return 1; // early-out
5480 }
5481 if (!!DemandedSrcElts) {
5482 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5483 Tmp = std::min(Tmp, Tmp2);
5484 }
5485 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5486 return Tmp;
5487 }
5488 case ISD::LOAD: {
5489 // If we are looking at the loaded value of the SDNode.
5490 if (Op.getResNo() != 0)
5491 break;
5492
5494 if (const MDNode *Ranges = LD->getRanges()) {
5495 if (DemandedElts != 1)
5496 break;
5497
5499 if (VTBits > CR.getBitWidth()) {
5500 switch (LD->getExtensionType()) {
5501 case ISD::SEXTLOAD:
5502 CR = CR.signExtend(VTBits);
5503 break;
5504 case ISD::ZEXTLOAD:
5505 CR = CR.zeroExtend(VTBits);
5506 break;
5507 default:
5508 break;
5509 }
5510 }
5511
5512 if (VTBits != CR.getBitWidth())
5513 break;
5514 return std::min(CR.getSignedMin().getNumSignBits(),
5516 }
5517
5518 unsigned ExtType = LD->getExtensionType();
5519 switch (ExtType) {
5520 default:
5521 break;
5522 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5523 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5524 return VTBits - Tmp + 1;
5525 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5526 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5527 return VTBits - Tmp;
5528 case ISD::NON_EXTLOAD:
5529 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5530 // We only need to handle vectors - computeKnownBits should handle
5531 // scalar cases.
5532 Type *CstTy = Cst->getType();
5533 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5534 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5535 VTBits == CstTy->getScalarSizeInBits()) {
5536 Tmp = VTBits;
5537 for (unsigned i = 0; i != NumElts; ++i) {
5538 if (!DemandedElts[i])
5539 continue;
5540 if (Constant *Elt = Cst->getAggregateElement(i)) {
5541 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5542 const APInt &Value = CInt->getValue();
5543 Tmp = std::min(Tmp, Value.getNumSignBits());
5544 continue;
5545 }
5546 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5547 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5548 Tmp = std::min(Tmp, Value.getNumSignBits());
5549 continue;
5550 }
5551 }
5552 // Unknown type. Conservatively assume no bits match sign bit.
5553 return 1;
5554 }
5555 return Tmp;
5556 }
5557 }
5558 break;
5559 }
5560
5561 break;
5562 }
5565 case ISD::ATOMIC_SWAP:
5577 case ISD::ATOMIC_LOAD: {
5578 auto *AT = cast<AtomicSDNode>(Op);
5579 // If we are looking at the loaded value.
5580 if (Op.getResNo() == 0) {
5581 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5582 if (Tmp == VTBits)
5583 return 1; // early-out
5584
5585 // For atomic_load, prefer to use the extension type.
5586 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5587 switch (AT->getExtensionType()) {
5588 default:
5589 break;
5590 case ISD::SEXTLOAD:
5591 return VTBits - Tmp + 1;
5592 case ISD::ZEXTLOAD:
5593 return VTBits - Tmp;
5594 }
5595 }
5596
5597 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5598 return VTBits - Tmp + 1;
5599 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5600 return VTBits - Tmp;
5601 }
5602 break;
5603 }
5604 }
5605
5606 // Allow the target to implement this method for its nodes.
5607 if (Opcode >= ISD::BUILTIN_OP_END ||
5608 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5609 Opcode == ISD::INTRINSIC_W_CHAIN ||
5610 Opcode == ISD::INTRINSIC_VOID) {
5611 // TODO: This can probably be removed once target code is audited. This
5612 // is here purely to reduce patch size and review complexity.
5613 if (!VT.isScalableVector()) {
5614 unsigned NumBits =
5615 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5616 if (NumBits > 1)
5617 FirstAnswer = std::max(FirstAnswer, NumBits);
5618 }
5619 }
5620
5621 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5622 // use this information.
5623 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5624 return std::max(FirstAnswer, Known.countMinSignBits());
5625}
5626
5628 unsigned Depth) const {
5629 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5630 return Op.getScalarValueSizeInBits() - SignBits + 1;
5631}
5632
5634 const APInt &DemandedElts,
5635 unsigned Depth) const {
5636 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5637 return Op.getScalarValueSizeInBits() - SignBits + 1;
5638}
5639
5641 UndefPoisonKind Kind,
5642 unsigned Depth) const {
5643 // Early out for FREEZE.
5644 if (Op.getOpcode() == ISD::FREEZE)
5645 return true;
5646
5647 APInt DemandedElts = getDemandAllEltsMask(Op);
5648 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5649}
5650
5652 const APInt &DemandedElts,
5653 UndefPoisonKind Kind,
5654 unsigned Depth) const {
5655 unsigned Opcode = Op.getOpcode();
5656
5657 // Early out for FREEZE.
5658 if (Opcode == ISD::FREEZE)
5659 return true;
5660
5661 if (Depth >= MaxRecursionDepth)
5662 return false; // Limit search depth.
5663
5664 if (isIntOrFPConstant(Op))
5665 return true;
5666
5667 switch (Opcode) {
5668 case ISD::CONDCODE:
5669 case ISD::VALUETYPE:
5670 case ISD::FrameIndex:
5672 case ISD::CopyFromReg:
5673 return true;
5674
5675 case ISD::POISON:
5676 return !includesPoison(Kind);
5677
5678 case ISD::UNDEF:
5679 return !includesUndef(Kind);
5680
5681 case ISD::BITCAST: {
5682 SDValue Src = Op.getOperand(0);
5683 EVT SrcVT = Src.getValueType();
5684 EVT DstVT = Op.getValueType();
5685
5686 if (!SrcVT.isVector() || !DstVT.isVector())
5687 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5688
5689 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5690 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5691 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5692 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5693
5694 if (SrcEltBits == DstEltBits)
5695 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5696 Depth + 1);
5697
5698 if (SrcEltBits < DstEltBits) {
5699 if (DstEltBits % SrcEltBits != 0)
5700 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5701
5702 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5703 "Unexpected vector bitcast");
5704 APInt DemandedSrcElts =
5705 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5706 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5707 Depth + 1);
5708 }
5709
5710 if (SrcEltBits % DstEltBits != 0)
5711 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5712
5713 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5714 "Unexpected vector bitcast");
5715 APInt DemandedSrcElts =
5716 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5717 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5718 Depth + 1);
5719 }
5720
5721 case ISD::BUILD_VECTOR:
5722 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5723 // this shouldn't affect the result.
5724 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5725 if (!DemandedElts[i])
5726 continue;
5727 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5728 return false;
5729 }
5730 return true;
5731
5732 case ISD::CONCAT_VECTORS: {
5733 EVT VT = Op.getValueType();
5734 if (!VT.isFixedLengthVector())
5735 break;
5736
5737 EVT SubVT = Op.getOperand(0).getValueType();
5738 unsigned NumSubElts = SubVT.getVectorNumElements();
5739 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5740 APInt DemandedSubElts =
5741 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5742 if (!!DemandedSubElts &&
5743 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5744 Kind, Depth + 1))
5745 return false;
5746 }
5747 return true;
5748 }
5749
5751 SDValue Src = Op.getOperand(0);
5752 if (Src.getValueType().isScalableVector())
5753 break;
5754 uint64_t Idx = Op.getConstantOperandVal(1);
5755 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5756 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5757 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5758 Depth + 1);
5759 }
5760
5761 case ISD::INSERT_SUBVECTOR: {
5762 if (Op.getValueType().isScalableVector())
5763 break;
5764 SDValue Src = Op.getOperand(0);
5765 SDValue Sub = Op.getOperand(1);
5766 uint64_t Idx = Op.getConstantOperandVal(2);
5767 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5768 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5769 APInt DemandedSrcElts = DemandedElts;
5770 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5771
5772 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5773 Sub, DemandedSubElts, Kind, Depth + 1))
5774 return false;
5775 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5776 Src, DemandedSrcElts, Kind, Depth + 1))
5777 return false;
5778 return true;
5779 }
5780
5782 SDValue Src = Op.getOperand(0);
5783 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5784 EVT SrcVT = Src.getValueType();
5785 if (SrcVT.isFixedLengthVector() && IndexC &&
5786 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5787 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5788 IndexC->getZExtValue());
5789 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5790 Depth + 1);
5791 }
5792 break;
5793 }
5794
5796 SDValue InVec = Op.getOperand(0);
5797 SDValue InVal = Op.getOperand(1);
5798 SDValue EltNo = Op.getOperand(2);
5799 EVT VT = InVec.getValueType();
5800 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5801 if (IndexC && VT.isFixedLengthVector() &&
5802 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5803 if (DemandedElts[IndexC->getZExtValue()] &&
5804 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5805 return false;
5806 APInt InVecDemandedElts = DemandedElts;
5807 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5808 if (!!InVecDemandedElts &&
5810 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5811 InVecDemandedElts, Kind, Depth + 1))
5812 return false;
5813 return true;
5814 }
5815 break;
5816 }
5817
5819 // Check upper (known undef) elements.
5820 if (DemandedElts.ugt(1) && includesUndef(Kind))
5821 return false;
5822 // Check element zero.
5823 if (DemandedElts[0] &&
5824 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5825 return false;
5826 return true;
5827
5828 case ISD::SPLAT_VECTOR:
5829 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5830
5831 case ISD::SELECT: {
5832 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5833 /*ConsiderFlags*/ true, Depth) &&
5834 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5835 Depth + 1) &&
5836 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5837 Kind, Depth + 1) &&
5838 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5839 Kind, Depth + 1);
5840 }
5841
5842 case ISD::VECTOR_SHUFFLE: {
5843 APInt DemandedLHS, DemandedRHS;
5844 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5845 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5846 DemandedElts, DemandedLHS, DemandedRHS,
5847 /*AllowUndefElts=*/false))
5848 return false;
5849 if (!DemandedLHS.isZero() &&
5850 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5851 Depth + 1))
5852 return false;
5853 if (!DemandedRHS.isZero() &&
5854 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5855 Depth + 1))
5856 return false;
5857 return true;
5858 }
5859
5860 case ISD::SHL:
5861 case ISD::SRL:
5862 case ISD::SRA:
5863 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5864 // enough to check operand 0 if Op can't create undef/poison.
5865 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5866 /*ConsiderFlags*/ true, Depth) &&
5867 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5868 Kind, Depth + 1);
5869
5870 case ISD::BSWAP:
5871 case ISD::CTPOP:
5872 case ISD::BITREVERSE:
5873 case ISD::AND:
5874 case ISD::OR:
5875 case ISD::XOR:
5876 case ISD::ADD:
5877 case ISD::SUB:
5878 case ISD::MUL:
5879 case ISD::SADDSAT:
5880 case ISD::UADDSAT:
5881 case ISD::SSUBSAT:
5882 case ISD::USUBSAT:
5883 case ISD::SSHLSAT:
5884 case ISD::USHLSAT:
5885 case ISD::SMIN:
5886 case ISD::SMAX:
5887 case ISD::UMIN:
5888 case ISD::UMAX:
5889 case ISD::ZERO_EXTEND:
5890 case ISD::SIGN_EXTEND:
5891 case ISD::ANY_EXTEND:
5892 case ISD::TRUNCATE:
5893 case ISD::VSELECT: {
5894 // If Op can't create undef/poison and none of its operands are undef/poison
5895 // then Op is never undef/poison. A difference from the more common check
5896 // below, outside the switch, is that we handle elementwise operations for
5897 // which the DemandedElts mask is valid for all operands here.
5898 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5899 /*ConsiderFlags*/ true, Depth) &&
5900 all_of(Op->ops(), [&](SDValue V) {
5901 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5902 Depth + 1);
5903 });
5904 }
5905
5906 // TODO: Search for noundef attributes from library functions.
5907
5908 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5909
5910 default:
5911 // Allow the target to implement this method for its nodes.
5912 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5913 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5914 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5915 Op, DemandedElts, *this, Kind, Depth);
5916 break;
5917 }
5918
5919 // If Op can't create undef/poison and none of its operands are undef/poison
5920 // then Op is never undef/poison.
5921 // NOTE: TargetNodes can handle this in themselves in
5922 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5923 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5924 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5925 all_of(Op->ops(), [&](SDValue V) {
5926 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5927 });
5928}
5929
5931 bool ConsiderFlags,
5932 unsigned Depth) const {
5933 APInt DemandedElts = getDemandAllEltsMask(Op);
5934 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5935}
5936
5938 UndefPoisonKind Kind,
5939 bool ConsiderFlags,
5940 unsigned Depth) const {
5941 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5942 return true;
5943
5944 unsigned Opcode = Op.getOpcode();
5945 switch (Opcode) {
5946 case ISD::AssertSext:
5947 case ISD::AssertZext:
5948 case ISD::AssertAlign:
5950 // Assertion nodes can create poison if the assertion fails.
5951 return includesPoison(Kind);
5952
5953 case ISD::FREEZE:
5957 case ISD::SADDSAT:
5958 case ISD::UADDSAT:
5959 case ISD::SSUBSAT:
5960 case ISD::USUBSAT:
5961 case ISD::MULHU:
5962 case ISD::MULHS:
5963 case ISD::AVGFLOORS:
5964 case ISD::AVGFLOORU:
5965 case ISD::AVGCEILS:
5966 case ISD::AVGCEILU:
5967 case ISD::ABDU:
5968 case ISD::ABDS:
5969 case ISD::SMIN:
5970 case ISD::SMAX:
5971 case ISD::SCMP:
5972 case ISD::UMIN:
5973 case ISD::UMAX:
5974 case ISD::UCMP:
5975 case ISD::AND:
5976 case ISD::XOR:
5977 case ISD::ROTL:
5978 case ISD::ROTR:
5979 case ISD::FSHL:
5980 case ISD::FSHR:
5981 case ISD::BSWAP:
5982 case ISD::CTTZ:
5983 case ISD::CTLZ:
5984 case ISD::CTLS:
5985 case ISD::CTPOP:
5986 case ISD::BITREVERSE:
5987 case ISD::PARITY:
5988 case ISD::SIGN_EXTEND:
5989 case ISD::TRUNCATE:
5993 case ISD::BITCAST:
5994 case ISD::BUILD_VECTOR:
5995 case ISD::BUILD_PAIR:
5996 case ISD::SPLAT_VECTOR:
5997 case ISD::FABS:
5998 case ISD::FCEIL:
5999 case ISD::FFLOOR:
6000 case ISD::FTRUNC:
6001 case ISD::FRINT:
6002 case ISD::FNEARBYINT:
6003 case ISD::FROUND:
6004 case ISD::FROUNDEVEN:
6005 return false;
6006
6007 case ISD::ABS:
6008 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6009 // Different to Intrinsic::abs.
6010 return false;
6012 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6013 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6014
6015 case ISD::ADDC:
6016 case ISD::SUBC:
6017 case ISD::ADDE:
6018 case ISD::SUBE:
6019 case ISD::SADDO:
6020 case ISD::SSUBO:
6021 case ISD::SMULO:
6022 case ISD::SADDO_CARRY:
6023 case ISD::SSUBO_CARRY:
6024 case ISD::UADDO:
6025 case ISD::USUBO:
6026 case ISD::UMULO:
6027 case ISD::UADDO_CARRY:
6028 case ISD::USUBO_CARRY:
6029 // No poison on result or overflow flags.
6030 return false;
6031
6032 case ISD::SELECT_CC:
6033 case ISD::SETCC: {
6034 // Integer setcc cannot create undef or poison.
6035 if (Op.getOperand(0).getValueType().isInteger())
6036 return false;
6037
6038 // FP compares are more complicated. They can create poison for nan/infinity
6039 // based on options and flags. The options and flags also cause special
6040 // nonan condition codes to be used. Those condition codes may be preserved
6041 // even if the nonan flag is dropped somewhere.
6042 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6043 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6044 return (unsigned)CCCode & 0x10U;
6045 }
6046
6047 case ISD::OR:
6048 case ISD::ZERO_EXTEND:
6049 case ISD::SELECT:
6050 case ISD::VSELECT:
6051 case ISD::ADD:
6052 case ISD::SUB:
6053 case ISD::MUL:
6054 case ISD::FNEG:
6055 case ISD::FADD:
6056 case ISD::FSUB:
6057 case ISD::FMUL:
6058 case ISD::FDIV:
6059 case ISD::FREM:
6060 case ISD::FCOPYSIGN:
6061 case ISD::FMA:
6062 case ISD::FMAD:
6063 case ISD::FMULADD:
6064 case ISD::FP_EXTEND:
6065 case ISD::FMINNUM:
6066 case ISD::FMAXNUM:
6067 case ISD::FMINNUM_IEEE:
6068 case ISD::FMAXNUM_IEEE:
6069 case ISD::FMINIMUM:
6070 case ISD::FMAXIMUM:
6071 case ISD::FMINIMUMNUM:
6072 case ISD::FMAXIMUMNUM:
6078 // No poison except from flags (which is handled above)
6079 return false;
6080
6081 case ISD::SHL:
6082 case ISD::SRL:
6083 case ISD::SRA:
6084 // If the max shift amount isn't in range, then the shift can
6085 // create poison.
6086 return includesPoison(Kind) &&
6087 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6088
6091 // If the amount is zero then the result will be poison.
6092 // TODO: Add isKnownNeverZero DemandedElts handling.
6093 return includesPoison(Kind) &&
6094 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6095
6097 // Check if we demand any upper (undef) elements.
6098 return includesUndef(Kind) && DemandedElts.ugt(1);
6099
6102 // Ensure that the element index is in bounds.
6103 if (includesPoison(Kind)) {
6104 EVT VecVT = Op.getOperand(0).getValueType();
6105 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6106 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6107 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6108 }
6109 return false;
6110 }
6111
6112 case ISD::VECTOR_SHUFFLE: {
6113 // Check for any demanded shuffle element that is undef.
6114 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6115 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6116 if (Elt < 0 && DemandedElts[Idx])
6117 return true;
6118 return false;
6119 }
6120
6122 return false;
6123
6124 default:
6125 // Allow the target to implement this method for its nodes.
6126 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6127 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6128 return TLI->canCreateUndefOrPoisonForTargetNode(
6129 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6130 break;
6131 }
6132
6133 // Be conservative and return true.
6134 return true;
6135}
6136
6137bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6138 unsigned Opcode = Op.getOpcode();
6139 if (Opcode == ISD::OR)
6140 return Op->getFlags().hasDisjoint() ||
6141 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6142 if (Opcode == ISD::XOR)
6143 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6144 return false;
6145}
6146
6148 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6149 (Op.isAnyAdd() || isADDLike(Op));
6150}
6151
6153 FPClassTest InterestedClasses,
6154 unsigned Depth) const {
6155 APInt DemandedElts = getDemandAllEltsMask(Op);
6156 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6157}
6158
6160 const APInt &DemandedElts,
6161 FPClassTest InterestedClasses,
6162 unsigned Depth) const {
6164
6165 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6166 return KnownFPClass(CFP->getValueAPF());
6167
6168 if (Depth >= MaxRecursionDepth)
6169 return Known;
6170
6171 if (Op.getOpcode() == ISD::UNDEF)
6172 return Known;
6173
6174 EVT VT = Op.getValueType();
6175 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6176 assert((!VT.isFixedLengthVector() ||
6177 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6178 "Unexpected vector size");
6179
6180 if (!DemandedElts)
6181 return Known;
6182
6183 unsigned Opcode = Op.getOpcode();
6184 switch (Opcode) {
6185 case ISD::POISON: {
6186 Known.KnownFPClasses = fcNone;
6187 Known.SignBit = false;
6188 break;
6189 }
6190 case ISD::FNEG: {
6191 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6192 InterestedClasses, Depth + 1);
6193 Known.fneg();
6194 break;
6195 }
6196 case ISD::BUILD_VECTOR: {
6197 assert(!VT.isScalableVector());
6198 bool First = true;
6199 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6200 if (!DemandedElts[I])
6201 continue;
6202
6203 if (First) {
6204 Known =
6205 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6206 First = false;
6207 } else {
6208 Known |=
6209 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6210 }
6211
6212 if (Known.isUnknown())
6213 break;
6214 }
6215 break;
6216 }
6218 SDValue Src = Op.getOperand(0);
6219 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6220 EVT SrcVT = Src.getValueType();
6221 if (SrcVT.isFixedLengthVector() && CIdx) {
6222 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6223 APInt DemandedSrcElts = APInt::getOneBitSet(
6224 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6225 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6226 Depth + 1);
6227 } else {
6228 // Out of bounds index is poison.
6229 Known.KnownFPClasses = fcNone;
6230 }
6231 } else {
6232 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6233 }
6234 break;
6235 }
6236 case ISD::SPLAT_VECTOR: {
6237 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6238 break;
6239 }
6240 case ISD::BITCAST: {
6241 // FIXME: It should not be necessary to check for an elementwise bitcast.
6242 // If a bitcast is not elementwise between vector / scalar types,
6243 // computeKnownBits already splices the known bits of the source elements
6244 // appropriately so as to line up with the bits of the result's demanded
6245 // elements.
6246 EVT SrcVT = Op.getOperand(0).getValueType();
6247 if (VT.isScalableVector() || SrcVT.isScalableVector())
6248 break;
6249 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6250 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6251 if (VTNumElts != SrcVTNumElts)
6252 break;
6253
6254 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6256 break;
6257 }
6258 case ISD::FABS: {
6259 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6260 InterestedClasses, Depth + 1);
6261 Known.fabs();
6262 break;
6263 }
6264 case ISD::FCOPYSIGN: {
6265 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6266 InterestedClasses, Depth + 1);
6267 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6268 InterestedClasses, Depth + 1);
6269 Known.copysign(KnownSign);
6270 break;
6271 }
6272 case ISD::AssertNoFPClass: {
6273 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6274 InterestedClasses, Depth + 1);
6275 FPClassTest AssertedClasses =
6276 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6277 Known.KnownFPClasses &= ~AssertedClasses;
6278 break;
6279 }
6281 SDValue Src = Op.getOperand(0);
6282 EVT SrcVT = Src.getValueType();
6283 if (SrcVT.isFixedLengthVector()) {
6284 unsigned Idx = Op.getConstantOperandVal(1);
6285 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6286
6287 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6288 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6289 Depth + 1);
6290 } else {
6291 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6292 }
6293 break;
6294 }
6295 case ISD::INSERT_SUBVECTOR: {
6296 SDValue BaseVector = Op.getOperand(0);
6297 SDValue SubVector = Op.getOperand(1);
6298 EVT BaseVT = BaseVector.getValueType();
6299 if (BaseVT.isFixedLengthVector()) {
6300 unsigned Idx = Op.getConstantOperandVal(2);
6301 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6302 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6303
6304 APInt DemandedMask =
6305 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6306 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6307 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6308
6309 if (!DemandedSrcElts.isZero())
6310 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6311 InterestedClasses, Depth + 1);
6312 if (!DemandedSubElts.isZero()) {
6314 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6315 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6316 }
6317 } else {
6318 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6319 if (!Known.isUnknown())
6320 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6321 }
6322 break;
6323 }
6324 case ISD::SELECT:
6325 case ISD::VSELECT: {
6326 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6327 // IR-level ValueTracking.
6328 KnownFPClass KnownFalseClass = computeKnownFPClass(
6329 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6330 if (KnownFalseClass.isUnknown())
6331 break;
6332 KnownFPClass KnownTrueClass = computeKnownFPClass(
6333 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6334 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6335 break;
6336 }
6337 default:
6338 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6339 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6340 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6341 Depth);
6342 }
6343 break;
6344 }
6345
6346 return Known;
6347}
6348
6350 unsigned Depth) const {
6351 APInt DemandedElts = getDemandAllEltsMask(Op);
6352 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6353}
6354
6356 bool SNaN, unsigned Depth) const {
6357 assert(!DemandedElts.isZero() && "No demanded elements");
6358
6359 // If we're told that NaNs won't happen, assume they won't.
6360 if (Op->getFlags().hasNoNaNs())
6361 return true;
6362
6363 if (Depth >= MaxRecursionDepth)
6364 return false; // Limit search depth.
6365
6366 unsigned Opcode = Op.getOpcode();
6367 switch (Opcode) {
6368 case ISD::FADD:
6369 case ISD::FSUB:
6370 case ISD::FMUL:
6371 case ISD::FDIV:
6372 case ISD::FREM:
6373 case ISD::FSIN:
6374 case ISD::FCOS:
6375 case ISD::FTAN:
6376 case ISD::FASIN:
6377 case ISD::FACOS:
6378 case ISD::FATAN:
6379 case ISD::FATAN2:
6380 case ISD::FSINH:
6381 case ISD::FCOSH:
6382 case ISD::FTANH:
6383 case ISD::FMA:
6384 case ISD::FMULADD:
6385 case ISD::FMAD: {
6386 if (SNaN)
6387 return true;
6388 // TODO: Need isKnownNeverInfinity
6389 return false;
6390 }
6391 case ISD::FCANONICALIZE:
6392 case ISD::FEXP:
6393 case ISD::FEXP2:
6394 case ISD::FEXP10:
6395 case ISD::FTRUNC:
6396 case ISD::FFLOOR:
6397 case ISD::FCEIL:
6398 case ISD::FROUND:
6399 case ISD::FROUNDEVEN:
6400 case ISD::LROUND:
6401 case ISD::LLROUND:
6402 case ISD::FRINT:
6403 case ISD::LRINT:
6404 case ISD::LLRINT:
6405 case ISD::FNEARBYINT:
6406 case ISD::FLDEXP: {
6407 if (SNaN)
6408 return true;
6409 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6410 }
6411 case ISD::FABS:
6412 case ISD::FNEG:
6413 case ISD::FCOPYSIGN: {
6414 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6415 }
6416 case ISD::SELECT:
6417 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6418 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6419 case ISD::FP_EXTEND:
6420 case ISD::FP_ROUND: {
6421 if (SNaN)
6422 return true;
6423 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6424 }
6425 case ISD::SINT_TO_FP:
6426 case ISD::UINT_TO_FP:
6427 return true;
6428 case ISD::FSQRT: // Need is known positive
6429 case ISD::FLOG:
6430 case ISD::FLOG2:
6431 case ISD::FLOG10:
6432 case ISD::FPOWI:
6433 case ISD::FPOW: {
6434 if (SNaN)
6435 return true;
6436 // TODO: Refine on operand
6437 return false;
6438 }
6439 case ISD::FMINNUM:
6440 case ISD::FMAXNUM:
6441 case ISD::FMINIMUMNUM:
6442 case ISD::FMAXIMUMNUM: {
6443 // Only one needs to be known not-nan, since it will be returned if the
6444 // other ends up being one.
6445 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6446 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6447 }
6448 case ISD::FMINNUM_IEEE:
6449 case ISD::FMAXNUM_IEEE: {
6450 if (SNaN)
6451 return true;
6452 // This can return a NaN if either operand is an sNaN, or if both operands
6453 // are NaN.
6454 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6455 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6456 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6457 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6458 }
6459 case ISD::FMINIMUM:
6460 case ISD::FMAXIMUM: {
6461 // TODO: Does this quiet or return the origina NaN as-is?
6462 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6463 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6464 }
6466 SDValue Src = Op.getOperand(0);
6467 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6468 EVT SrcVT = Src.getValueType();
6469 if (SrcVT.isFixedLengthVector() && Idx &&
6470 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6471 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6472 Idx->getZExtValue());
6473 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6474 }
6475 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6476 }
6478 SDValue Src = Op.getOperand(0);
6479 if (Src.getValueType().isFixedLengthVector()) {
6480 unsigned Idx = Op.getConstantOperandVal(1);
6481 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6482 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6483 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6484 }
6485 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6486 }
6487 case ISD::INSERT_SUBVECTOR: {
6488 SDValue BaseVector = Op.getOperand(0);
6489 SDValue SubVector = Op.getOperand(1);
6490 EVT BaseVectorVT = BaseVector.getValueType();
6491 if (BaseVectorVT.isFixedLengthVector()) {
6492 unsigned Idx = Op.getConstantOperandVal(2);
6493 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6494 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6495
6496 // Clear/Extract the bits at the position where the subvector will be
6497 // inserted.
6498 APInt DemandedMask =
6499 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6500 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6501 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6502
6503 bool NeverNaN = true;
6504 if (!DemandedSrcElts.isZero())
6505 NeverNaN &=
6506 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6507 if (NeverNaN && !DemandedSubElts.isZero())
6508 NeverNaN &=
6509 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6510 return NeverNaN;
6511 }
6512 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6513 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6514 }
6515 case ISD::BUILD_VECTOR: {
6516 unsigned NumElts = Op.getNumOperands();
6517 for (unsigned I = 0; I != NumElts; ++I)
6518 if (DemandedElts[I] &&
6519 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6520 return false;
6521 return true;
6522 }
6523 case ISD::SPLAT_VECTOR:
6524 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6525 case ISD::AssertNoFPClass: {
6526 FPClassTest NoFPClass =
6527 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6528 if ((NoFPClass & fcNan) == fcNan)
6529 return true;
6530 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6531 return true;
6532 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6533 }
6534 default:
6535 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6536 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6537 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6538 Depth);
6539 }
6540 break;
6541 }
6542
6543 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6544 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6545 return Known.isKnownNever(NanMask);
6546}
6547
6549 APInt DemandedElts = getDemandAllEltsMask(Op);
6550 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6551}
6552
6554 const APInt &DemandedElts,
6555 unsigned Depth) const {
6556 assert(!DemandedElts.isZero() && "No demanded elements");
6557 EVT VT = Op.getValueType();
6559 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6560 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6561}
6562
6564 APInt DemandedElts = getDemandAllEltsMask(Op);
6565 return isKnownNeverZero(Op, DemandedElts, Depth);
6566}
6567
6569 unsigned Depth) const {
6570 if (Depth >= MaxRecursionDepth)
6571 return false; // Limit search depth.
6572
6573 EVT OpVT = Op.getValueType();
6574 unsigned BitWidth = OpVT.getScalarSizeInBits();
6575
6576 assert(!Op.getValueType().isFloatingPoint() &&
6577 "Floating point types unsupported - use isKnownNeverLogicalZero");
6578
6579 // If the value is a constant, we can obviously see if it is a zero or not.
6580 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6581 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6582 return !V.isZero();
6583 };
6584
6585 if (ISD::matchUnaryPredicate(Op, IsNeverZero))
6586 return true;
6587
6588 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6589 // some degree.
6590 switch (Op.getOpcode()) {
6591 default:
6592 break;
6593
6594 case ISD::BUILD_VECTOR:
6595 // Are all operands of a build vector constant non-zero?
6596 if (all_of(enumerate(Op->ops()), [&](auto P) {
6597 auto *C = dyn_cast<ConstantSDNode>(P.value());
6598 return !DemandedElts[P.index()] || (C && IsNeverZero(C));
6599 }))
6600 return true;
6601 break;
6602
6603 case ISD::SPLAT_VECTOR:
6604 // Is the operand of a splat vector a constant non-zero?
6605 if (auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(0)))
6606 if (IsNeverZero(C))
6607 return true;
6608 break;
6609
6611 SDValue InVec = Op.getOperand(0);
6612 SDValue EltNo = Op.getOperand(1);
6613 EVT VecVT = InVec.getValueType();
6614
6615 // Skip scalable vectors or implicit extensions.
6616 if (VecVT.isScalableVector() ||
6617 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6618 break;
6619
6620 // If we know the element index, just demand that vector element, else for
6621 // an unknown element index, ignore DemandedElts and demand them all.
6622 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6623 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6624 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6625 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6626 DemandedSrcElts =
6627 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6628
6629 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6630 }
6631
6632 case ISD::OR:
6633 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6634 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6635
6636 case ISD::VSELECT:
6637 case ISD::SELECT:
6638 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6639 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6640
6641 case ISD::SHL: {
6642 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6643 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6644 KnownBits ValKnown =
6645 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6646 // 1 << X is never zero.
6647 if (ValKnown.One[0])
6648 return true;
6649 // If max shift cnt of known ones is non-zero, result is non-zero.
6650 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6651 .getMaxValue();
6652 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6653 !ValKnown.One.shl(MaxCnt).isZero())
6654 return true;
6655 break;
6656 }
6657
6658 case ISD::VECTOR_SHUFFLE: {
6659 if (Op.getValueType().isScalableVector())
6660 return false;
6661
6662 unsigned NumElts = DemandedElts.getBitWidth();
6663
6664 // All demanded elements from LHS and RHS must be known non-zero.
6665 // Demanded elements with undef shuffle mask elements are unknown.
6666
6667 APInt DemandedLHS, DemandedRHS;
6668 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6669 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6670 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6671 DemandedLHS, DemandedRHS))
6672 return false;
6673
6674 return (!DemandedLHS ||
6675 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6676 (!DemandedRHS ||
6677 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6678 }
6679
6680 case ISD::UADDSAT:
6681 case ISD::UMAX:
6682 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6683 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6684
6685 case ISD::UMIN:
6686 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6687 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6688
6689 // For smin/smax: If either operand is known negative/positive
6690 // respectively we don't need the other to be known at all.
6691 case ISD::SMAX: {
6692 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6693 if (Op1.isStrictlyPositive())
6694 return true;
6695
6696 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6697 if (Op0.isStrictlyPositive())
6698 return true;
6699
6700 if (Op1.isNonZero() && Op0.isNonZero())
6701 return true;
6702
6703 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6704 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6705 }
6706 case ISD::SMIN: {
6707 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6708 if (Op1.isNegative())
6709 return true;
6710
6711 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6712 if (Op0.isNegative())
6713 return true;
6714
6715 if (Op1.isNonZero() && Op0.isNonZero())
6716 return true;
6717
6718 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6719 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6720 }
6721
6722 case ISD::ROTL:
6723 case ISD::ROTR:
6724 case ISD::BITREVERSE:
6725 case ISD::BSWAP:
6726 case ISD::CTPOP:
6727 case ISD::ABS:
6729 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6730
6731 case ISD::SRA:
6732 case ISD::SRL: {
6733 if (Op->getFlags().hasExact())
6734 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6735 KnownBits ValKnown =
6736 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6737 if (ValKnown.isNegative())
6738 return true;
6739 // If max shift cnt of known ones is non-zero, result is non-zero.
6740 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6741 .getMaxValue();
6742 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6743 !ValKnown.One.lshr(MaxCnt).isZero())
6744 return true;
6745 break;
6746 }
6747 case ISD::UDIV:
6748 case ISD::SDIV:
6749 // div exact can only produce a zero if the dividend is zero.
6750 // TODO: For udiv this is also true if Op1 u<= Op0
6751 if (Op->getFlags().hasExact())
6752 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6753 break;
6754
6755 case ISD::ADD:
6756 if (Op->getFlags().hasNoUnsignedWrap())
6757 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6758 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6759 return true;
6760 // TODO: There are a lot more cases we can prove for add.
6761 break;
6762
6763 case ISD::SUB: {
6764 if (isNullConstant(Op.getOperand(0)))
6765 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6766
6767 std::optional<bool> ne = KnownBits::ne(
6768 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6769 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6770 return ne && *ne;
6771 }
6772
6773 case ISD::MUL:
6774 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6775 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6776 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6777 return true;
6778 break;
6779
6780 case ISD::ZERO_EXTEND:
6781 case ISD::SIGN_EXTEND:
6782 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6783 case ISD::VSCALE: {
6785 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6786 ConstantRange CR =
6787 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6788 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6789 return true;
6790 break;
6791 }
6792 }
6793
6794 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6795}
6796
6798 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6799 return !C1->isNegative();
6800
6801 switch (Op.getOpcode()) {
6802 case ISD::FABS:
6803 case ISD::FEXP:
6804 case ISD::FEXP2:
6805 case ISD::FEXP10:
6806 return true;
6807 default:
6808 return false;
6809 }
6810
6811 llvm_unreachable("covered opcode switch");
6812}
6813
6815 assert(Use.getValueType().isFloatingPoint());
6816 const SDNode *User = Use.getUser();
6817 if (User->getFlags().hasNoSignedZeros())
6818 return true;
6819
6820 unsigned OperandNo = Use.getOperandNo();
6821 // Check if this use is insensitive to the sign of zero
6822 switch (User->getOpcode()) {
6823 case ISD::SETCC:
6824 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6825 case ISD::FABS:
6826 // fabs always produces +0.0.
6827 return true;
6828 case ISD::FCOPYSIGN:
6829 // copysign overwrites the sign bit of the first operand.
6830 return OperandNo == 0;
6831 case ISD::FADD:
6832 case ISD::FSUB: {
6833 // Arithmetic with non-zero constants fixes the uncertainty around the
6834 // sign bit.
6835 SDValue Other = User->getOperand(1 - OperandNo);
6837 }
6838 case ISD::FP_TO_SINT:
6839 case ISD::FP_TO_UINT:
6840 // fp-to-int conversions normalize signed zeros.
6841 return true;
6842 default:
6843 return false;
6844 }
6845}
6846
6848 if (Op->getFlags().hasNoSignedZeros())
6849 return true;
6850 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6851 // regression. Ideally, this should be implemented as a demanded-bits
6852 // optimization that stems from the users.
6853 if (Op->use_size() > 2)
6854 return false;
6855 return all_of(Op->uses(),
6856 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6857}
6858
6860 // Check the obvious case.
6861 if (A == B) return true;
6862
6863 // For negative and positive zero.
6866 if (CA->isZero() && CB->isZero()) return true;
6867
6868 // Otherwise they may not be equal.
6869 return false;
6870}
6871
6872// Only bits set in Mask must be negated, other bits may be arbitrary.
6874 if (isBitwiseNot(V, AllowUndefs))
6875 return V.getOperand(0);
6876
6877 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6878 // bits in the non-extended part.
6879 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6880 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6881 return SDValue();
6882 SDValue ExtArg = V.getOperand(0);
6883 if (ExtArg.getScalarValueSizeInBits() >=
6884 MaskC->getAPIntValue().getActiveBits() &&
6885 isBitwiseNot(ExtArg, AllowUndefs) &&
6886 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6887 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6888 return ExtArg.getOperand(0).getOperand(0);
6889 return SDValue();
6890}
6891
6893 // Match masked merge pattern (X & ~M) op (Y & M)
6894 // Including degenerate case (X & ~M) op M
6895 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6896 SDValue Other) {
6897 if (SDValue NotOperand =
6898 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6899 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6900 NotOperand->getOpcode() == ISD::TRUNCATE)
6901 NotOperand = NotOperand->getOperand(0);
6902
6903 if (Other == NotOperand)
6904 return true;
6905 if (Other->getOpcode() == ISD::AND)
6906 return NotOperand == Other->getOperand(0) ||
6907 NotOperand == Other->getOperand(1);
6908 }
6909 return false;
6910 };
6911
6912 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6913 A = A->getOperand(0);
6914
6915 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6916 B = B->getOperand(0);
6917
6918 if (A->getOpcode() == ISD::AND)
6919 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6920 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6921 return false;
6922}
6923
6924// FIXME: unify with llvm::haveNoCommonBitsSet.
6926 assert(A.getValueType() == B.getValueType() &&
6927 "Values must have the same type");
6930 return true;
6933}
6934
6935static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6936 SelectionDAG &DAG) {
6937 if (cast<ConstantSDNode>(Step)->isZero())
6938 return DAG.getConstant(0, DL, VT);
6939
6940 return SDValue();
6941}
6942
6945 SelectionDAG &DAG) {
6946 int NumOps = Ops.size();
6947 assert(NumOps != 0 && "Can't build an empty vector!");
6948 assert(!VT.isScalableVector() &&
6949 "BUILD_VECTOR cannot be used with scalable types");
6950 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6951 "Incorrect element count in BUILD_VECTOR!");
6952
6953 // BUILD_VECTOR of UNDEFs is UNDEF.
6954 bool AllPoison = true;
6955 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6956 AllPoison &= Op.getOpcode() == ISD::POISON;
6957 return Op.isUndef();
6958 }))
6959 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6960
6961 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6962 SDValue IdentitySrc;
6963 bool IsIdentity = true;
6964 for (int i = 0; i != NumOps; ++i) {
6965 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6966 Ops[i].getOperand(0).getValueType() != VT ||
6967 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6968 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6969 Ops[i].getConstantOperandAPInt(1) != i) {
6970 IsIdentity = false;
6971 break;
6972 }
6973 IdentitySrc = Ops[i].getOperand(0);
6974 }
6975 if (IsIdentity)
6976 return IdentitySrc;
6977
6978 return SDValue();
6979}
6980
6981/// Try to simplify vector concatenation to an input value, undef, or build
6982/// vector.
6985 SelectionDAG &DAG) {
6986 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6988 [Ops](SDValue Op) {
6989 return Ops[0].getValueType() == Op.getValueType();
6990 }) &&
6991 "Concatenation of vectors with inconsistent value types!");
6992 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6993 VT.getVectorElementCount() &&
6994 "Incorrect element count in vector concatenation!");
6995
6996 if (Ops.size() == 1)
6997 return Ops[0];
6998
6999 // Concat of UNDEFs is UNDEF.
7000 bool AllPoison = true;
7001 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7002 AllPoison &= Op.getOpcode() == ISD::POISON;
7003 return Op.isUndef();
7004 }))
7005 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7006
7007 // Scan the operands and look for extract operations from a single source
7008 // that correspond to insertion at the same location via this concatenation:
7009 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7010 SDValue IdentitySrc;
7011 bool IsIdentity = true;
7012 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7013 SDValue Op = Ops[i];
7014 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7015 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7016 Op.getOperand(0).getValueType() != VT ||
7017 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7018 Op.getConstantOperandVal(1) != IdentityIndex) {
7019 IsIdentity = false;
7020 break;
7021 }
7022 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7023 "Unexpected identity source vector for concat of extracts");
7024 IdentitySrc = Op.getOperand(0);
7025 }
7026 if (IsIdentity) {
7027 assert(IdentitySrc && "Failed to set source vector of extracts");
7028 return IdentitySrc;
7029 }
7030
7031 // The code below this point is only designed to work for fixed width
7032 // vectors, so we bail out for now.
7033 if (VT.isScalableVector())
7034 return SDValue();
7035
7036 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7037 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7038 // BUILD_VECTOR.
7039 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7040 EVT SVT = VT.getScalarType();
7042 for (SDValue Op : Ops) {
7043 EVT OpVT = Op.getValueType();
7044 if (Op.getOpcode() == ISD::POISON)
7045 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7046 else if (Op.getOpcode() == ISD::UNDEF)
7047 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7048 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7049 Elts.append(Op->op_begin(), Op->op_end());
7050 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7051 OpVT.getVectorNumElements() == 1 &&
7052 isNullConstant(Op.getOperand(2)))
7053 Elts.push_back(Op.getOperand(1));
7054 else
7055 return SDValue();
7056 }
7057
7058 // BUILD_VECTOR requires all inputs to be of the same type, find the
7059 // maximum type and extend them all.
7060 for (SDValue Op : Elts)
7061 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7062
7063 if (SVT.bitsGT(VT.getScalarType())) {
7064 for (SDValue &Op : Elts) {
7065 if (Op.getOpcode() == ISD::POISON)
7066 Op = DAG.getPOISON(SVT);
7067 else if (Op.getOpcode() == ISD::UNDEF)
7068 Op = DAG.getUNDEF(SVT);
7069 else
7070 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7071 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7072 : DAG.getSExtOrTrunc(Op, DL, SVT);
7073 }
7074 }
7075
7076 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7077 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7078 return V;
7079}
7080
7081/// Gets or creates the specified node.
7082SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7083 SDVTList VTs = getVTList(VT);
7085 AddNodeIDNode(ID, Opcode, VTs, {});
7086 void *IP = nullptr;
7087 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7088 return SDValue(E, 0);
7089
7090 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7091 CSEMap.InsertNode(N, IP);
7092
7093 InsertNode(N);
7094 SDValue V = SDValue(N, 0);
7095 NewSDValueDbgMsg(V, "Creating new node: ", this);
7096 return V;
7097}
7098
7099SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7100 SDValue N1) {
7101 SDNodeFlags Flags;
7102 if (Inserter)
7103 Flags = Inserter->getFlags();
7104 return getNode(Opcode, DL, VT, N1, Flags);
7105}
7106
7107SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7108 SDValue N1, const SDNodeFlags Flags) {
7109 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7110
7111 // Constant fold unary operations with a vector integer or float operand.
7112 switch (Opcode) {
7113 default:
7114 // FIXME: Entirely reasonable to perform folding of other unary
7115 // operations here as the need arises.
7116 break;
7117 case ISD::FNEG:
7118 case ISD::FABS:
7119 case ISD::FCEIL:
7120 case ISD::FTRUNC:
7121 case ISD::FFLOOR:
7122 case ISD::FP_EXTEND:
7123 case ISD::FP_TO_SINT:
7124 case ISD::FP_TO_UINT:
7125 case ISD::FP_TO_FP16:
7126 case ISD::FP_TO_BF16:
7127 case ISD::TRUNCATE:
7128 case ISD::ANY_EXTEND:
7129 case ISD::ZERO_EXTEND:
7130 case ISD::SIGN_EXTEND:
7131 case ISD::UINT_TO_FP:
7132 case ISD::SINT_TO_FP:
7133 case ISD::FP16_TO_FP:
7134 case ISD::BF16_TO_FP:
7135 case ISD::BITCAST:
7136 case ISD::ABS:
7138 case ISD::BITREVERSE:
7139 case ISD::BSWAP:
7140 case ISD::CTLZ:
7142 case ISD::CTTZ:
7144 case ISD::CTPOP:
7145 case ISD::CTLS:
7146 case ISD::VECREDUCE_ADD:
7151 case ISD::VECREDUCE_MUL:
7152 case ISD::VECREDUCE_AND:
7153 case ISD::VECREDUCE_OR:
7154 case ISD::VECREDUCE_XOR:
7155 case ISD::STEP_VECTOR: {
7156 SDValue Ops = {N1};
7157 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7158 return Fold;
7159 }
7160 }
7161
7162 unsigned OpOpcode = N1.getNode()->getOpcode();
7163 switch (Opcode) {
7164 case ISD::STEP_VECTOR:
7165 assert(VT.isScalableVector() &&
7166 "STEP_VECTOR can only be used with scalable types");
7167 assert(OpOpcode == ISD::TargetConstant &&
7168 VT.getVectorElementType() == N1.getValueType() &&
7169 "Unexpected step operand");
7170 break;
7171 case ISD::FREEZE:
7172 assert(VT == N1.getValueType() && "Unexpected VT!");
7174 return N1;
7175 break;
7176 case ISD::TokenFactor:
7177 case ISD::MERGE_VALUES:
7179 return N1; // Factor, merge or concat of one node? No need.
7180 case ISD::BUILD_VECTOR: {
7181 // Attempt to simplify BUILD_VECTOR.
7182 SDValue Ops[] = {N1};
7183 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7184 return V;
7185 break;
7186 }
7187 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7188 case ISD::FP_EXTEND:
7190 "Invalid FP cast!");
7191 if (N1.getValueType() == VT) return N1; // noop conversion.
7192 assert((!VT.isVector() || VT.getVectorElementCount() ==
7194 "Vector element count mismatch!");
7195 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7196 if (N1.isUndef())
7197 return getUNDEF(VT);
7198 break;
7199 case ISD::FP_TO_SINT:
7200 case ISD::FP_TO_UINT:
7201 if (N1.isUndef())
7202 return getUNDEF(VT);
7203 break;
7204 case ISD::SINT_TO_FP:
7205 case ISD::UINT_TO_FP:
7206 // [us]itofp(undef) = 0, because the result value is bounded.
7207 if (N1.isUndef())
7208 return getConstantFP(0.0, DL, VT);
7209 break;
7210 case ISD::SIGN_EXTEND:
7211 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7212 "Invalid SIGN_EXTEND!");
7213 assert(VT.isVector() == N1.getValueType().isVector() &&
7214 "SIGN_EXTEND result type type should be vector iff the operand "
7215 "type is vector!");
7216 if (N1.getValueType() == VT) return N1; // noop extension
7217 assert((!VT.isVector() || VT.getVectorElementCount() ==
7219 "Vector element count mismatch!");
7220 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7221 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7222 SDNodeFlags Flags;
7223 if (OpOpcode == ISD::ZERO_EXTEND)
7224 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7225 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7226 transferDbgValues(N1, NewVal);
7227 return NewVal;
7228 }
7229
7230 if (OpOpcode == ISD::POISON)
7231 return getPOISON(VT);
7232
7233 if (N1.isUndef())
7234 // sext(undef) = 0, because the top bits will all be the same.
7235 return getConstant(0, DL, VT);
7236
7237 // Skip unnecessary sext_inreg pattern:
7238 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7239 if (OpOpcode == ISD::TRUNCATE) {
7240 SDValue OpOp = N1.getOperand(0);
7241 if (OpOp.getValueType() == VT) {
7242 unsigned NumSignExtBits =
7244 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7245 transferDbgValues(N1, OpOp);
7246 return OpOp;
7247 }
7248 }
7249 }
7250 break;
7251 case ISD::ZERO_EXTEND:
7252 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7253 "Invalid ZERO_EXTEND!");
7254 assert(VT.isVector() == N1.getValueType().isVector() &&
7255 "ZERO_EXTEND result type type should be vector iff the operand "
7256 "type is vector!");
7257 if (N1.getValueType() == VT) return N1; // noop extension
7258 assert((!VT.isVector() || VT.getVectorElementCount() ==
7260 "Vector element count mismatch!");
7261 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7262 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7263 SDNodeFlags Flags;
7264 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7265 SDValue NewVal =
7266 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7267 transferDbgValues(N1, NewVal);
7268 return NewVal;
7269 }
7270
7271 if (OpOpcode == ISD::POISON)
7272 return getPOISON(VT);
7273
7274 if (N1.isUndef())
7275 // zext(undef) = 0, because the top bits will be zero.
7276 return getConstant(0, DL, VT);
7277
7278 // Skip unnecessary zext_inreg pattern:
7279 // (zext (trunc x)) -> x iff the upper bits are known zero.
7280 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7281 // use to recognise zext_inreg patterns.
7282 if (OpOpcode == ISD::TRUNCATE) {
7283 SDValue OpOp = N1.getOperand(0);
7284 if (OpOp.getValueType() == VT) {
7285 if (OpOp.getOpcode() != ISD::AND) {
7288 if (MaskedValueIsZero(OpOp, HiBits)) {
7289 transferDbgValues(N1, OpOp);
7290 return OpOp;
7291 }
7292 }
7293 }
7294 }
7295 break;
7296 case ISD::ANY_EXTEND:
7297 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7298 "Invalid ANY_EXTEND!");
7299 assert(VT.isVector() == N1.getValueType().isVector() &&
7300 "ANY_EXTEND result type type should be vector iff the operand "
7301 "type is vector!");
7302 if (N1.getValueType() == VT) return N1; // noop extension
7303 assert((!VT.isVector() || VT.getVectorElementCount() ==
7305 "Vector element count mismatch!");
7306 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7307
7308 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7309 OpOpcode == ISD::ANY_EXTEND) {
7310 SDNodeFlags Flags;
7311 if (OpOpcode == ISD::ZERO_EXTEND)
7312 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7313 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7314 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7315 }
7316 if (N1.isUndef())
7317 return getUNDEF(VT);
7318
7319 // (ext (trunc x)) -> x
7320 if (OpOpcode == ISD::TRUNCATE) {
7321 SDValue OpOp = N1.getOperand(0);
7322 if (OpOp.getValueType() == VT) {
7323 transferDbgValues(N1, OpOp);
7324 return OpOp;
7325 }
7326 }
7327 break;
7328 case ISD::TRUNCATE:
7329 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7330 "Invalid TRUNCATE!");
7331 assert(VT.isVector() == N1.getValueType().isVector() &&
7332 "TRUNCATE result type type should be vector iff the operand "
7333 "type is vector!");
7334 if (N1.getValueType() == VT) return N1; // noop truncate
7335 assert((!VT.isVector() || VT.getVectorElementCount() ==
7337 "Vector element count mismatch!");
7338 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7339 if (OpOpcode == ISD::TRUNCATE)
7340 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7341 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7342 OpOpcode == ISD::ANY_EXTEND) {
7343 // If the source is smaller than the dest, we still need an extend.
7345 VT.getScalarType())) {
7346 SDNodeFlags Flags;
7347 if (OpOpcode == ISD::ZERO_EXTEND)
7348 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7349 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7350 }
7351 if (N1.getOperand(0).getValueType().bitsGT(VT))
7352 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7353 return N1.getOperand(0);
7354 }
7355 if (N1.isUndef())
7356 return getUNDEF(VT);
7357 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7358 return getVScale(DL, VT,
7360 break;
7364 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7365 assert(N1.getValueType().bitsLE(VT) &&
7366 "The input must be the same size or smaller than the result.");
7369 "The destination vector type must have fewer lanes than the input.");
7370 break;
7371 case ISD::ABS:
7372 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7373 if (N1.isUndef())
7374 return getConstant(0, DL, VT);
7375 break;
7377 assert(VT.isInteger() && VT == N1.getValueType() &&
7378 "Invalid ABS_MIN_POISON!");
7379 if (N1.isUndef())
7380 return getConstant(0, DL, VT);
7381 break;
7382 case ISD::BSWAP:
7383 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7384 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7385 "BSWAP types must be a multiple of 16 bits!");
7386 if (N1.isUndef())
7387 return getUNDEF(VT);
7388 // bswap(bswap(X)) -> X.
7389 if (OpOpcode == ISD::BSWAP)
7390 return N1.getOperand(0);
7391 break;
7392 case ISD::BITREVERSE:
7393 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7394 if (N1.isUndef())
7395 return getUNDEF(VT);
7396 break;
7397 case ISD::BITCAST:
7399 "Cannot BITCAST between types of different sizes!");
7400 if (VT == N1.getValueType()) return N1; // noop conversion.
7401 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7402 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7403 if (N1.isUndef())
7404 return getUNDEF(VT);
7405 break;
7407 assert(VT.isVector() && !N1.getValueType().isVector() &&
7408 (VT.getVectorElementType() == N1.getValueType() ||
7410 N1.getValueType().isInteger() &&
7412 "Illegal SCALAR_TO_VECTOR node!");
7413 if (N1.isUndef())
7414 return getUNDEF(VT);
7415 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7416 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7418 N1.getConstantOperandVal(1) == 0 &&
7419 N1.getOperand(0).getValueType() == VT)
7420 return N1.getOperand(0);
7421 break;
7422 case ISD::FNEG:
7423 // Negation of an unknown bag of bits is still completely undefined.
7424 if (N1.isUndef())
7425 return getUNDEF(VT);
7426
7427 if (OpOpcode == ISD::FNEG) // --X -> X
7428 return N1.getOperand(0);
7429 break;
7430 case ISD::FABS:
7431 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7432 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7433 break;
7434 case ISD::VSCALE:
7435 assert(VT == N1.getValueType() && "Unexpected VT!");
7436 break;
7437 case ISD::CTPOP:
7438 if (N1.getValueType().getScalarType() == MVT::i1)
7439 return N1;
7440 break;
7441 case ISD::CTLZ:
7442 case ISD::CTTZ:
7443 if (N1.getValueType().getScalarType() == MVT::i1)
7444 return getNOT(DL, N1, N1.getValueType());
7445 break;
7446 case ISD::CTLS:
7447 if (N1.getValueType().getScalarType() == MVT::i1)
7448 return getConstant(0, DL, VT);
7449 break;
7450 case ISD::VECREDUCE_ADD:
7451 if (N1.getValueType().getScalarType() == MVT::i1)
7452 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7453 break;
7456 if (N1.getValueType().getScalarType() == MVT::i1)
7457 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7458 break;
7461 if (N1.getValueType().getScalarType() == MVT::i1)
7462 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7463 break;
7464 case ISD::SPLAT_VECTOR:
7465 assert(VT.isVector() && "Wrong return type!");
7466 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7467 // that for now.
7469 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7471 N1.getValueType().isInteger() &&
7473 "Wrong operand type!");
7474 break;
7475 }
7476
7477 SDNode *N;
7478 SDVTList VTs = getVTList(VT);
7479 SDValue Ops[] = {N1};
7480 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7482 AddNodeIDNode(ID, Opcode, VTs, Ops);
7483 void *IP = nullptr;
7484 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7485 E->intersectFlagsWith(Flags);
7486 return SDValue(E, 0);
7487 }
7488
7489 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7490 N->setFlags(Flags);
7491 createOperands(N, Ops);
7492 CSEMap.InsertNode(N, IP);
7493 } else {
7494 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7495 createOperands(N, Ops);
7496 }
7497
7498 InsertNode(N);
7499 SDValue V = SDValue(N, 0);
7500 NewSDValueDbgMsg(V, "Creating new node: ", this);
7501 return V;
7502}
7503
7504static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7505 switch (Opcode) {
7506 default:
7507 llvm_unreachable("Unexpected integer identity opcode");
7508 case ISD::ADD:
7509 case ISD::OR:
7510 case ISD::XOR:
7511 case ISD::UMAX:
7512 return APInt::getZero(BitWidth);
7513 case ISD::MUL:
7514 return APInt(BitWidth, 1);
7515 case ISD::AND:
7516 case ISD::UMIN:
7518 case ISD::SMAX:
7520 case ISD::SMIN:
7522 }
7523}
7524
7525static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7526 const APInt &C2) {
7527 switch (Opcode) {
7528 case ISD::ADD: return C1 + C2;
7529 case ISD::SUB: return C1 - C2;
7530 case ISD::MUL: return C1 * C2;
7531 case ISD::AND: return C1 & C2;
7532 case ISD::OR: return C1 | C2;
7533 case ISD::XOR: return C1 ^ C2;
7534 case ISD::SHL: return C1 << C2;
7535 case ISD::SRL: return C1.lshr(C2);
7536 case ISD::SRA: return C1.ashr(C2);
7537 case ISD::ROTL: return C1.rotl(C2);
7538 case ISD::ROTR: return C1.rotr(C2);
7539 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7540 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7541 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7542 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7543 case ISD::SADDSAT: return C1.sadd_sat(C2);
7544 case ISD::UADDSAT: return C1.uadd_sat(C2);
7545 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7546 case ISD::USUBSAT: return C1.usub_sat(C2);
7547 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7548 case ISD::USHLSAT: return C1.ushl_sat(C2);
7549 case ISD::UDIV:
7550 if (!C2.getBoolValue())
7551 break;
7552 return C1.udiv(C2);
7553 case ISD::UREM:
7554 if (!C2.getBoolValue())
7555 break;
7556 return C1.urem(C2);
7557 case ISD::SDIV:
7558 if (!C2.getBoolValue())
7559 break;
7560 return C1.sdiv(C2);
7561 case ISD::SREM:
7562 if (!C2.getBoolValue())
7563 break;
7564 return C1.srem(C2);
7565 case ISD::AVGFLOORS:
7566 return APIntOps::avgFloorS(C1, C2);
7567 case ISD::AVGFLOORU:
7568 return APIntOps::avgFloorU(C1, C2);
7569 case ISD::AVGCEILS:
7570 return APIntOps::avgCeilS(C1, C2);
7571 case ISD::AVGCEILU:
7572 return APIntOps::avgCeilU(C1, C2);
7573 case ISD::ABDS:
7574 return APIntOps::abds(C1, C2);
7575 case ISD::ABDU:
7576 return APIntOps::abdu(C1, C2);
7577 case ISD::MULHS:
7578 return APIntOps::mulhs(C1, C2);
7579 case ISD::MULHU:
7580 return APIntOps::mulhu(C1, C2);
7581 case ISD::CLMUL:
7582 return APIntOps::clmul(C1, C2);
7583 case ISD::CLMULR:
7584 return APIntOps::clmulr(C1, C2);
7585 case ISD::CLMULH:
7586 return APIntOps::clmulh(C1, C2);
7587 case ISD::PEXT:
7588 return APIntOps::pext(C1, C2);
7589 case ISD::PDEP:
7590 return APIntOps::pdep(C1, C2);
7591 }
7592 return std::nullopt;
7593}
7594// Handle constant folding with UNDEF.
7595// TODO: Handle more cases.
7596static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7597 bool IsUndef1, const APInt &C2,
7598 bool IsUndef2) {
7599 if (!(IsUndef1 || IsUndef2))
7600 return FoldValue(Opcode, C1, C2);
7601
7602 // Fold and(x, undef) -> 0
7603 // Fold mul(x, undef) -> 0
7604 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7605 return APInt::getZero(C1.getBitWidth());
7606
7607 return std::nullopt;
7608}
7609
7611 const GlobalAddressSDNode *GA,
7612 const SDNode *N2) {
7613 if (GA->getOpcode() != ISD::GlobalAddress)
7614 return SDValue();
7615 if (!TLI->isOffsetFoldingLegal(GA))
7616 return SDValue();
7617 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7618 if (!C2)
7619 return SDValue();
7620 int64_t Offset = C2->getSExtValue();
7621 switch (Opcode) {
7622 case ISD::ADD:
7623 case ISD::PTRADD:
7624 break;
7625 case ISD::SUB: Offset = -uint64_t(Offset); break;
7626 default: return SDValue();
7627 }
7628 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7629 GA->getOffset() + uint64_t(Offset));
7630}
7631
7633 switch (Opcode) {
7634 case ISD::SDIV:
7635 case ISD::UDIV:
7636 case ISD::SREM:
7637 case ISD::UREM: {
7638 // If a divisor is zero/undef or any element of a divisor vector is
7639 // zero/undef, the whole op is undef.
7640 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7641 SDValue Divisor = Ops[1];
7642 if (Divisor.isUndef() || isNullConstant(Divisor))
7643 return true;
7644
7645 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7646 llvm::any_of(Divisor->op_values(),
7647 [](SDValue V) { return V.isUndef() ||
7648 isNullConstant(V); });
7649 // TODO: Handle signed overflow.
7650 }
7651 // TODO: Handle oversized shifts.
7652 default:
7653 return false;
7654 }
7655}
7656
7659 SDNodeFlags Flags) {
7660 // If the opcode is a target-specific ISD node, there's nothing we can
7661 // do here and the operand rules may not line up with the below, so
7662 // bail early.
7663 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7664 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7665 // foldCONCAT_VECTORS in getNode before this is called.
7666 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7667 return SDValue();
7668
7669 unsigned NumOps = Ops.size();
7670 if (NumOps == 0)
7671 return SDValue();
7672
7673 if (isUndef(Opcode, Ops))
7674 return getUNDEF(VT);
7675
7676 // Handle unary special cases.
7677 if (NumOps == 1) {
7678 SDValue N1 = Ops[0];
7679
7680 // Constant fold unary operations with an integer constant operand. Even
7681 // opaque constant will be folded, because the folding of unary operations
7682 // doesn't create new constants with different values. Nevertheless, the
7683 // opaque flag is preserved during folding to prevent future folding with
7684 // other constants.
7685 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7686 const APInt &Val = C->getAPIntValue();
7687 switch (Opcode) {
7688 case ISD::SIGN_EXTEND:
7689 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7690 C->isTargetOpcode(), C->isOpaque());
7691 case ISD::TRUNCATE:
7692 if (C->isOpaque())
7693 break;
7694 [[fallthrough]];
7695 case ISD::ZERO_EXTEND:
7696 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7697 C->isTargetOpcode(), C->isOpaque());
7698 case ISD::ANY_EXTEND:
7699 // Some targets like RISCV prefer to sign extend some types.
7700 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7701 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7702 C->isTargetOpcode(), C->isOpaque());
7703 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7704 C->isTargetOpcode(), C->isOpaque());
7705 case ISD::ABS:
7706 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7707 C->isOpaque());
7709 if (Val.isMinSignedValue())
7710 return getPOISON(VT);
7711 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7712 C->isOpaque());
7713 case ISD::BITREVERSE:
7714 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7715 C->isOpaque());
7716 case ISD::BSWAP:
7717 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7718 C->isOpaque());
7719 case ISD::CTPOP:
7720 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7721 C->isOpaque());
7722 case ISD::CTLZ:
7724 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7725 C->isOpaque());
7726 case ISD::CTTZ:
7728 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7729 C->isOpaque());
7730 case ISD::CTLS:
7731 // CTLS returns the number of extra sign bits so subtract one.
7732 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7733 C->isTargetOpcode(), C->isOpaque());
7734 case ISD::UINT_TO_FP:
7735 case ISD::SINT_TO_FP: {
7737 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7739 return getConstantFP(FPV, DL, VT);
7740 }
7741 case ISD::FP16_TO_FP:
7742 case ISD::BF16_TO_FP: {
7743 bool Ignored;
7744 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7745 : APFloat::BFloat(),
7746 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7747
7748 // This can return overflow, underflow, or inexact; we don't care.
7749 // FIXME need to be more flexible about rounding mode.
7751 &Ignored);
7752 return getConstantFP(FPV, DL, VT);
7753 }
7754 case ISD::STEP_VECTOR:
7755 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7756 return V;
7757 break;
7758 case ISD::BITCAST:
7759 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7760 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7761 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7762 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7763 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7764 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7765 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7766 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7767 break;
7768 }
7769 }
7770
7771 // Constant fold unary operations with a floating point constant operand.
7772 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7773 APFloat V = C->getValueAPF(); // make copy
7774 switch (Opcode) {
7775 case ISD::FNEG:
7776 V.changeSign();
7777 return getConstantFP(V, DL, VT);
7778 case ISD::FABS:
7779 V.clearSign();
7780 return getConstantFP(V, DL, VT);
7781 case ISD::FCEIL: {
7782 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7784 return getConstantFP(V, DL, VT);
7785 return SDValue();
7786 }
7787 case ISD::FTRUNC: {
7788 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7790 return getConstantFP(V, DL, VT);
7791 return SDValue();
7792 }
7793 case ISD::FFLOOR: {
7794 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7796 return getConstantFP(V, DL, VT);
7797 return SDValue();
7798 }
7799 case ISD::FP_EXTEND: {
7800 bool ignored;
7801 // This can return overflow, underflow, or inexact; we don't care.
7802 // FIXME need to be more flexible about rounding mode.
7803 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7804 &ignored);
7805 return getConstantFP(V, DL, VT);
7806 }
7807 case ISD::FP_TO_SINT:
7808 case ISD::FP_TO_UINT: {
7809 bool ignored;
7810 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7811 // FIXME need to be more flexible about rounding mode.
7813 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7814 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7815 break;
7816 return getConstant(IntVal, DL, VT);
7817 }
7818 case ISD::FP_TO_FP16:
7819 case ISD::FP_TO_BF16: {
7820 bool Ignored;
7821 // This can return overflow, underflow, or inexact; we don't care.
7822 // FIXME need to be more flexible about rounding mode.
7823 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7824 : APFloat::BFloat(),
7826 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7827 }
7828 case ISD::BITCAST:
7829 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7830 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7831 VT);
7832 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7833 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7834 VT);
7835 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7836 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7837 VT);
7838 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7839 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7840 break;
7841 }
7842 }
7843
7844 // Early-out if we failed to constant fold a bitcast.
7845 if (Opcode == ISD::BITCAST)
7846 return SDValue();
7847
7848 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7849 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7850 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7851 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7852 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7853 Opcode == ISD::VECREDUCE_AND) &&
7855 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7856 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7857 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7858 for (SDValue Elt : N1->op_values()) {
7859 if (Elt.getOpcode() == ISD::POISON)
7860 return getPOISON(VT);
7861 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7862 return SDValue();
7863 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7864 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7865 assert(Folded &&
7866 "Expected vector reduction base opcode to be foldable");
7867 Acc = *Folded;
7868 }
7869 EVT EltVT = N1.getValueType().getScalarType();
7870 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7871 }
7872 }
7873
7874 // Handle binops special cases.
7875 if (NumOps == 2) {
7876 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7877 return CFP;
7878
7879 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7880 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7881 if (C1->isOpaque() || C2->isOpaque())
7882 return SDValue();
7883
7884 std::optional<APInt> FoldAttempt =
7885 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7886 if (!FoldAttempt)
7887 return SDValue();
7888
7889 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7890 assert((!Folded || !VT.isVector()) &&
7891 "Can't fold vectors ops with scalar operands");
7892 return Folded;
7893 }
7894 }
7895
7896 // fold (add Sym, c) -> Sym+c
7898 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7899 if (TLI->isCommutativeBinOp(Opcode))
7901 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7902
7903 // fold (sext_in_reg c1) -> c2
7904 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7905 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7906
7907 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7908 unsigned FromBits = EVT.getScalarSizeInBits();
7909 Val <<= Val.getBitWidth() - FromBits;
7910 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7911 return getConstant(Val, DL, ConstantVT);
7912 };
7913
7914 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7915 const APInt &Val = C1->getAPIntValue();
7916 return SignExtendInReg(Val, VT);
7917 }
7918
7920 SmallVector<SDValue, 8> ScalarOps;
7921 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7922 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7923 SDValue Op = Ops[0].getOperand(I);
7924 if (Op.isUndef()) {
7925 ScalarOps.push_back(getUNDEF(OpVT));
7926 continue;
7927 }
7928 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7929 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7930 }
7931 return getBuildVector(VT, DL, ScalarOps);
7932 }
7933
7934 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7935 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7936 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7937 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7938 Ops[0].getOperand(0).getValueType()));
7939 }
7940 }
7941
7942 // Handle fshl/fshr special cases.
7943 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7944 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7945 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7946 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7947
7948 if (C1 && C2 && C3) {
7949 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7950 return SDValue();
7951 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7952 &V3 = C3->getAPIntValue();
7953
7954 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7955 : APIntOps::fshr(V1, V2, V3);
7956 return getConstant(FoldedVal, DL, VT);
7957 }
7958 }
7959
7960 // Handle fma/fmad special cases.
7961 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7962 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7963 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7964 Ops[2].getValueType() == VT && "FMA types must match!");
7968 if (C1 && C2 && C3) {
7969 APFloat V1 = C1->getValueAPF();
7970 const APFloat &V2 = C2->getValueAPF();
7971 const APFloat &V3 = C3->getValueAPF();
7972 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7973 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7975 } else
7976 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7977 return getConstantFP(V1, DL, VT);
7978 }
7979 }
7980
7981 // This is for vector folding only from here on.
7982 if (!VT.isVector())
7983 return SDValue();
7984
7985 // Constant fold integer partial reductions with constant BUILD_VECTOR
7986 // operands. The reduction order is deliberately unspecified. Use the same
7987 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
7988 // lane I contributes to accumulator lane I % NumAccElts.
7989 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
7990 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
7991 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
7992 // These nodes have no scalar form, so unsupported cases must not fall
7993 // through to generic per-lane vector folding.
7994 if (!llvm::all_of(Ops, [](SDValue Op) {
7995 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
7996 }))
7997 return SDValue();
7998
7999 unsigned AccEltBits = VT.getScalarSizeInBits();
8000 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8001 unsigned NumAccElts = VT.getVectorNumElements();
8002 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8003 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8004 BitVector PoisonElts(NumAccElts);
8005
8006 for (unsigned I = 0; I != NumAccElts; ++I) {
8007 SDValue Elt = Ops[0].getOperand(I);
8008 if (Elt.getOpcode() == ISD::POISON) {
8009 PoisonElts.set(I);
8010 continue;
8011 }
8012 auto *C = dyn_cast<ConstantSDNode>(Elt);
8013 if (!C || C->isOpaque())
8014 return SDValue();
8015 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8016 }
8017
8018 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8019 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8020 for (unsigned I = 0; I != NumInputElts; ++I) {
8021 const unsigned AccIdx = I % NumAccElts;
8022 SDValue LHSElt = Ops[1].getOperand(I);
8023 SDValue RHSElt = Ops[2].getOperand(I);
8024 if (LHSElt.getOpcode() == ISD::POISON ||
8025 RHSElt.getOpcode() == ISD::POISON) {
8026 PoisonElts.set(AccIdx);
8027 continue;
8028 }
8029
8030 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8031 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8032 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8033 return SDValue();
8034
8035 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8036 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8037 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8038 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8039 Results[AccIdx] += LHSVal * RHSVal;
8040 }
8041
8042 // After type legalization the vector element type may not be a legal
8043 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8044 // promoted legal scalar type instead, matching the generic per-lane path
8045 // below. Bail out if legalization would narrow the type, since the lane
8046 // value would not fit.
8047 EVT AccEltVT = VT.getVectorElementType();
8048 EVT LegalSVT = AccEltVT;
8049 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8050 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8051 if (LegalSVT.bitsLT(AccEltVT))
8052 return SDValue();
8053 }
8054
8055 SmallVector<SDValue, 8> ResultOps;
8056 for (unsigned I = 0; I != NumAccElts; ++I)
8057 ResultOps.push_back(
8058 PoisonElts[I] ? getPOISON(LegalSVT)
8059 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8060 DL, LegalSVT));
8061 return getBuildVector(VT, DL, ResultOps);
8062 }
8063
8064 ElementCount NumElts = VT.getVectorElementCount();
8065
8066 // See if we can fold through any bitcasted integer ops.
8067 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8068 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8069 (Ops[0].getOpcode() == ISD::BITCAST ||
8070 Ops[1].getOpcode() == ISD::BITCAST)) {
8073 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8074 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8075 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8076 N2.getValueType().isInteger()) {
8077 bool IsLE = getDataLayout().isLittleEndian();
8078 unsigned EltBits = VT.getScalarSizeInBits();
8079 SmallVector<APInt> RawBits1, RawBits2;
8080 BitVector UndefElts1, UndefElts2;
8081 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8082 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8083 SmallVector<APInt> RawBits;
8084 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8085 std::optional<APInt> Fold = FoldValueWithUndef(
8086 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8087 if (!Fold)
8088 break;
8089 RawBits.push_back(*Fold);
8090 }
8091 if (RawBits.size() == NumElts.getFixedValue()) {
8092 // We have constant folded, but we might need to cast this again back
8093 // to the original (possibly legalized) type.
8094 EVT BVVT, BVEltVT;
8095 if (N1.getValueType() == VT) {
8096 BVVT = N1.getValueType();
8097 BVEltVT = BV1->getOperand(0).getValueType();
8098 } else {
8099 BVVT = N2.getValueType();
8100 BVEltVT = BV2->getOperand(0).getValueType();
8101 }
8102 unsigned BVEltBits = BVEltVT.getSizeInBits();
8103 SmallVector<APInt> DstBits;
8104 BitVector DstUndefs;
8106 DstBits, RawBits, DstUndefs,
8107 BitVector(RawBits.size(), false));
8108 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8109 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8110 if (DstUndefs[I])
8111 continue;
8112 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8113 }
8114 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8115 }
8116 }
8117 }
8118 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8119 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8120 isa<ConstantSDNode>(N2)) {
8121 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8122 {N1, N2}, Flags))
8123 return getBitcast(VT, Res);
8124 }
8125 }
8126
8127 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8128 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8129 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8130 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8131 APInt RHSVal;
8132 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8133 APInt NewStep = Opcode == ISD::MUL
8134 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8135 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8136 return getStepVector(DL, VT, NewStep);
8137 }
8138 }
8139
8140 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8141 return !Op.getValueType().isVector() ||
8142 Op.getValueType().getVectorElementCount() == NumElts;
8143 };
8144
8145 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8146 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8147 Op.getOpcode() == ISD::BUILD_VECTOR ||
8148 Op.getOpcode() == ISD::SPLAT_VECTOR;
8149 };
8150
8151 // All operands must be vector types with the same number of elements as
8152 // the result type and must be either UNDEF or a build/splat vector
8153 // or UNDEF scalars.
8154 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8155 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8156 return SDValue();
8157
8158 // If we are comparing vectors, then the result needs to be a i1 boolean that
8159 // is then extended back to the legal result type depending on how booleans
8160 // are represented.
8161 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8162 ISD::NodeType ExtendCode =
8163 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8164 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8166
8167 // Find legal integer scalar type for constant promotion and
8168 // ensure that its scalar size is at least as large as source.
8169 EVT LegalSVT = VT.getScalarType();
8170 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8171 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8172 if (LegalSVT.bitsLT(VT.getScalarType()))
8173 return SDValue();
8174 }
8175
8176 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8177 // only have one operand to check. For fixed-length vector types we may have
8178 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8179 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8180
8181 // Constant fold each scalar lane separately.
8182 SmallVector<SDValue, 4> ScalarResults;
8183 for (unsigned I = 0; I != NumVectorElts; I++) {
8184 SmallVector<SDValue, 4> ScalarOps;
8185 for (SDValue Op : Ops) {
8186 EVT InSVT = Op.getValueType().getScalarType();
8187 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8188 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8189 if (Op.isUndef())
8190 ScalarOps.push_back(getUNDEF(InSVT));
8191 else
8192 ScalarOps.push_back(Op);
8193 continue;
8194 }
8195
8196 SDValue ScalarOp =
8197 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8198 EVT ScalarVT = ScalarOp.getValueType();
8199
8200 // Build vector (integer) scalar operands may need implicit
8201 // truncation - do this before constant folding.
8202 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8203 // Don't create illegally-typed nodes unless they're constants or undef
8204 // - if we fail to constant fold we can't guarantee the (dead) nodes
8205 // we're creating will be cleaned up before being visited for
8206 // legalization.
8207 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8208 !isa<ConstantSDNode>(ScalarOp) &&
8209 TLI->getTypeAction(*getContext(), InSVT) !=
8211 return SDValue();
8212 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8213 }
8214
8215 ScalarOps.push_back(ScalarOp);
8216 }
8217
8218 // Constant fold the scalar operands.
8219 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8220
8221 // Scalar folding only succeeded if the result is a constant or UNDEF.
8222 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8223 ScalarResult.getOpcode() != ISD::ConstantFP)
8224 return SDValue();
8225
8226 // Legalize the (integer) scalar constant if necessary. We only do
8227 // this once we know the folding succeeded, since otherwise we would
8228 // get a node with illegal type which has a user.
8229 if (LegalSVT != SVT)
8230 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8231
8232 ScalarResults.push_back(ScalarResult);
8233 }
8234
8235 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8236 : getBuildVector(VT, DL, ScalarResults);
8237 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8238 return V;
8239}
8240
8243 // TODO: Add support for unary/ternary fp opcodes.
8244 if (Ops.size() != 2)
8245 return SDValue();
8246
8247 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8248 // should. That will require dealing with a potentially non-default
8249 // rounding mode, checking the "opStatus" return value from the APFloat
8250 // math calculations, and possibly other variations.
8251 SDValue N1 = Ops[0];
8252 SDValue N2 = Ops[1];
8253 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8254 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8255 if (N1CFP && N2CFP) {
8256 APFloat C1 = N1CFP->getValueAPF(); // make copy
8257 const APFloat &C2 = N2CFP->getValueAPF();
8258 switch (Opcode) {
8259 case ISD::FADD:
8261 return getConstantFP(C1, DL, VT);
8262 case ISD::FSUB:
8264 return getConstantFP(C1, DL, VT);
8265 case ISD::FMUL:
8267 return getConstantFP(C1, DL, VT);
8268 case ISD::FDIV:
8270 return getConstantFP(C1, DL, VT);
8271 case ISD::FREM:
8272 C1.mod(C2);
8273 return getConstantFP(C1, DL, VT);
8274 case ISD::FCOPYSIGN:
8275 C1.copySign(C2);
8276 return getConstantFP(C1, DL, VT);
8277 case ISD::FMINNUM:
8278 return getConstantFP(minnum(C1, C2), DL, VT);
8279 case ISD::FMAXNUM:
8280 return getConstantFP(maxnum(C1, C2), DL, VT);
8281 case ISD::FMINIMUM:
8282 return getConstantFP(minimum(C1, C2), DL, VT);
8283 case ISD::FMAXIMUM:
8284 return getConstantFP(maximum(C1, C2), DL, VT);
8285 case ISD::FMINIMUMNUM:
8286 return getConstantFP(minimumnum(C1, C2), DL, VT);
8287 case ISD::FMAXIMUMNUM:
8288 return getConstantFP(maximumnum(C1, C2), DL, VT);
8289 default: break;
8290 }
8291 }
8292 if (N1CFP && Opcode == ISD::FP_ROUND) {
8293 APFloat C1 = N1CFP->getValueAPF(); // make copy
8294 bool Unused;
8295 // This can return overflow, underflow, or inexact; we don't care.
8296 // FIXME need to be more flexible about rounding mode.
8298 &Unused);
8299 return getConstantFP(C1, DL, VT);
8300 }
8301
8302 switch (Opcode) {
8303 case ISD::FSUB:
8304 // -0.0 - undef --> undef (consistent with "fneg undef")
8305 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8306 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8307 return getUNDEF(VT);
8308 [[fallthrough]];
8309
8310 case ISD::FADD:
8311 case ISD::FMUL:
8312 case ISD::FDIV:
8313 case ISD::FREM:
8314 // If both operands are undef, the result is undef. If 1 operand is undef,
8315 // the result is NaN. This should match the behavior of the IR optimizer.
8316 if (N1.isUndef() && N2.isUndef())
8317 return getUNDEF(VT);
8318 if (N1.isUndef() || N2.isUndef())
8320 }
8321 return SDValue();
8322}
8323
8325 const SDLoc &DL, EVT DstEltVT) {
8326 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8327
8328 // If this is already the right type, we're done.
8329 if (SrcEltVT == DstEltVT)
8330 return SDValue(BV, 0);
8331
8332 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8333 unsigned DstBitSize = DstEltVT.getSizeInBits();
8334
8335 // If this is a conversion of N elements of one type to N elements of another
8336 // type, convert each element. This handles FP<->INT cases.
8337 if (SrcBitSize == DstBitSize) {
8339 for (SDValue Op : BV->op_values()) {
8340 // If the vector element type is not legal, the BUILD_VECTOR operands
8341 // are promoted and implicitly truncated. Make that explicit here.
8342 if (Op.getValueType() != SrcEltVT)
8343 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8344 Ops.push_back(getBitcast(DstEltVT, Op));
8345 }
8346 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8348 return getBuildVector(VT, DL, Ops);
8349 }
8350
8351 // Otherwise, we're growing or shrinking the elements. To avoid having to
8352 // handle annoying details of growing/shrinking FP values, we convert them to
8353 // int first.
8354 if (SrcEltVT.isFloatingPoint()) {
8355 // Convert the input float vector to a int vector where the elements are the
8356 // same sizes.
8357 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8358 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8360 DstEltVT);
8361 return SDValue();
8362 }
8363
8364 // Now we know the input is an integer vector. If the output is a FP type,
8365 // convert to integer first, then to FP of the right size.
8366 if (DstEltVT.isFloatingPoint()) {
8367 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8368 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8370 DstEltVT);
8371 return SDValue();
8372 }
8373
8374 // Okay, we know the src/dst types are both integers of differing types.
8375 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8376
8377 // Extract the constant raw bit data.
8378 BitVector UndefElements;
8379 SmallVector<APInt> RawBits;
8380 bool IsLE = getDataLayout().isLittleEndian();
8381 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8382 return SDValue();
8383
8385 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8386 if (UndefElements[I])
8387 Ops.push_back(getUNDEF(DstEltVT));
8388 else
8389 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8390 }
8391
8392 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8393 return getBuildVector(VT, DL, Ops);
8394}
8395
8397 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8398
8399 // There's no need to assert on a byte-aligned pointer. All pointers are at
8400 // least byte aligned.
8401 if (A == Align(1))
8402 return Val;
8403
8404 SDVTList VTs = getVTList(Val.getValueType());
8406 AddNodeIDNode(ID, ISD::AssertAlign, VTs, {Val});
8407 ID.AddInteger(A.value());
8408
8409 void *IP = nullptr;
8410 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8411 return SDValue(E, 0);
8412
8413 auto *N =
8414 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8415 createOperands(N, {Val});
8416
8417 CSEMap.InsertNode(N, IP);
8418 InsertNode(N);
8419
8420 SDValue V(N, 0);
8421 NewSDValueDbgMsg(V, "Creating new node: ", this);
8422 return V;
8423}
8424
8425SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8426 SDValue N1, SDValue N2) {
8427 SDNodeFlags Flags;
8428 if (Inserter)
8429 Flags = Inserter->getFlags();
8430 return getNode(Opcode, DL, VT, N1, N2, Flags);
8431}
8432
8434 SDValue &N2) const {
8435 if (!TLI->isCommutativeBinOp(Opcode))
8436 return;
8437
8438 // Canonicalize:
8439 // binop(const, nonconst) -> binop(nonconst, const)
8442 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8443 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8444 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8445 std::swap(N1, N2);
8446
8447 // Canonicalize:
8448 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8449 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8451 std::swap(N1, N2);
8452}
8453
8454SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8455 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8457 N2.getOpcode() != ISD::DELETED_NODE &&
8458 "Operand is DELETED_NODE!");
8459
8460 canonicalizeCommutativeBinop(Opcode, N1, N2);
8461
8462 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8463 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8464
8465 // Don't allow undefs in vector splats - we might be returning N2 when folding
8466 // to zero etc.
8467 ConstantSDNode *N2CV =
8468 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8469
8470 switch (Opcode) {
8471 default: break;
8472 case ISD::TokenFactor:
8473 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8474 N2.getValueType() == MVT::Other && "Invalid token factor!");
8475 // Fold trivial token factors.
8476 if (N1.getOpcode() == ISD::EntryToken) return N2;
8477 if (N2.getOpcode() == ISD::EntryToken) return N1;
8478 if (N1 == N2) return N1;
8479 break;
8480 case ISD::BUILD_VECTOR: {
8481 // Attempt to simplify BUILD_VECTOR.
8482 SDValue Ops[] = {N1, N2};
8483 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8484 return V;
8485 break;
8486 }
8487 case ISD::CONCAT_VECTORS: {
8488 SDValue Ops[] = {N1, N2};
8489 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8490 return V;
8491 break;
8492 }
8493 case ISD::AND:
8494 assert(VT.isInteger() && "This operator does not apply to FP types!");
8495 assert(N1.getValueType() == N2.getValueType() &&
8496 N1.getValueType() == VT && "Binary operator types must match!");
8497 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8498 // worth handling here.
8499 if (N2CV && N2CV->isZero())
8500 return N2;
8501 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8502 return N1;
8503 break;
8504 case ISD::OR:
8505 case ISD::XOR:
8506 case ISD::ADD:
8507 case ISD::PTRADD:
8508 case ISD::SUB:
8509 assert(VT.isInteger() && "This operator does not apply to FP types!");
8510 assert(N1.getValueType() == N2.getValueType() &&
8511 N1.getValueType() == VT && "Binary operator types must match!");
8512 // The equal operand types requirement is unnecessarily strong for PTRADD.
8513 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8514 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8515 // logic everywhere where PTRADDs may be folded or combined to properly
8516 // support them. If/when we introduce pointer types to the SDAG, we will
8517 // need to relax this constraint.
8518
8519 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8520 // it's worth handling here.
8521 if (N2CV && N2CV->isZero())
8522 return N1;
8523 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8524 VT.getScalarType() == MVT::i1)
8525 return getNode(ISD::XOR, DL, VT, N1, N2);
8526 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8527 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8528 N2.getOpcode() == ISD::VSCALE) {
8529 const APInt &C1 = N1->getConstantOperandAPInt(0);
8530 const APInt &C2 = N2->getConstantOperandAPInt(0);
8531 return getVScale(DL, VT, C1 + C2);
8532 }
8533 break;
8534 case ISD::MUL:
8535 assert(VT.isInteger() && "This operator does not apply to FP types!");
8536 assert(N1.getValueType() == N2.getValueType() &&
8537 N1.getValueType() == VT && "Binary operator types must match!");
8538 if (VT.getScalarType() == MVT::i1)
8539 return getNode(ISD::AND, DL, VT, N1, N2);
8540 if (N2CV && N2CV->isZero())
8541 return N2;
8542 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8543 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8544 const APInt &N2CImm = N2C->getAPIntValue();
8545 return getVScale(DL, VT, MulImm * N2CImm);
8546 }
8547 break;
8548 case ISD::UDIV:
8549 case ISD::UREM:
8550 case ISD::MULHU:
8551 case ISD::MULHS:
8552 case ISD::SDIV:
8553 case ISD::SREM:
8554 case ISD::SADDSAT:
8555 case ISD::SSUBSAT:
8556 case ISD::UADDSAT:
8557 case ISD::USUBSAT:
8558 assert(VT.isInteger() && "This operator does not apply to FP types!");
8559 assert(N1.getValueType() == N2.getValueType() &&
8560 N1.getValueType() == VT && "Binary operator types must match!");
8561 if (VT.getScalarType() == MVT::i1) {
8562 // fold (add_sat x, y) -> (or x, y) for bool types.
8563 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8564 return getNode(ISD::OR, DL, VT, N1, N2);
8565 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8566 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8567 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8568 }
8569 break;
8570 case ISD::SCMP:
8571 case ISD::UCMP:
8572 assert(N1.getValueType() == N2.getValueType() &&
8573 "Types of operands of UCMP/SCMP must match");
8574 assert(N1.getValueType().isVector() == VT.isVector() &&
8575 "Operands and return type of must both be scalars or vectors");
8576 if (VT.isVector())
8579 "Result and operands must have the same number of elements");
8580 break;
8581 case ISD::AVGFLOORS:
8582 case ISD::AVGFLOORU:
8583 case ISD::AVGCEILS:
8584 case ISD::AVGCEILU:
8585 assert(VT.isInteger() && "This operator does not apply to FP types!");
8586 assert(N1.getValueType() == N2.getValueType() &&
8587 N1.getValueType() == VT && "Binary operator types must match!");
8588 break;
8589 case ISD::ABDS:
8590 case ISD::ABDU:
8591 assert(VT.isInteger() && "This operator does not apply to FP types!");
8592 assert(N1.getValueType() == N2.getValueType() &&
8593 N1.getValueType() == VT && "Binary operator types must match!");
8594 if (VT.getScalarType() == MVT::i1)
8595 return getNode(ISD::XOR, DL, VT, N1, N2);
8596 break;
8597 case ISD::SMIN:
8598 case ISD::UMAX:
8599 assert(VT.isInteger() && "This operator does not apply to FP types!");
8600 assert(N1.getValueType() == N2.getValueType() &&
8601 N1.getValueType() == VT && "Binary operator types must match!");
8602 if (VT.getScalarType() == MVT::i1)
8603 return getNode(ISD::OR, DL, VT, N1, N2);
8604 break;
8605 case ISD::SMAX:
8606 case ISD::UMIN:
8607 assert(VT.isInteger() && "This operator does not apply to FP types!");
8608 assert(N1.getValueType() == N2.getValueType() &&
8609 N1.getValueType() == VT && "Binary operator types must match!");
8610 if (VT.getScalarType() == MVT::i1)
8611 return getNode(ISD::AND, DL, VT, N1, N2);
8612 break;
8613 case ISD::FADD:
8614 case ISD::FSUB:
8615 case ISD::FMUL:
8616 case ISD::FDIV:
8617 case ISD::FREM:
8618 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8619 assert(N1.getValueType() == N2.getValueType() &&
8620 N1.getValueType() == VT && "Binary operator types must match!");
8621 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8622 return V;
8623 break;
8624 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8625 assert(N1.getValueType() == VT &&
8628 "Invalid FCOPYSIGN!");
8629 break;
8630 case ISD::SHL:
8631 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8632 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8633 const APInt &ShiftImm = N2C->getAPIntValue();
8634 return getVScale(DL, VT, MulImm << ShiftImm);
8635 }
8636 [[fallthrough]];
8637 case ISD::SRA:
8638 case ISD::SRL:
8639 if (SDValue V = simplifyShift(N1, N2))
8640 return V;
8641 [[fallthrough]];
8642 case ISD::ROTL:
8643 case ISD::ROTR:
8644 case ISD::SSHLSAT:
8645 case ISD::USHLSAT:
8646 assert(VT == N1.getValueType() &&
8647 "Shift operators return type must be the same as their first arg");
8648 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8649 "Shifts only work on integers");
8650 assert((!VT.isVector() || VT == N2.getValueType()) &&
8651 "Vector shift amounts must be in the same as their first arg");
8652 // Verify that the shift amount VT is big enough to hold valid shift
8653 // amounts. This catches things like trying to shift an i1024 value by an
8654 // i8, which is easy to fall into in generic code that uses
8655 // TLI.getShiftAmount().
8658 "Invalid use of small shift amount with oversized value!");
8659
8660 // Always fold shifts of i1 values so the code generator doesn't need to
8661 // handle them. Since we know the size of the shift has to be less than the
8662 // size of the value, the shift/rotate count is guaranteed to be zero.
8663 if (VT == MVT::i1)
8664 return N1;
8665 if (N2CV && N2CV->isZero())
8666 return N1;
8667 break;
8668 case ISD::FP_ROUND:
8670 VT.bitsLE(N1.getValueType()) && N2C &&
8671 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8672 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8673 if (N1.getValueType() == VT) return N1; // noop conversion.
8674 break;
8675 case ISD::IS_FPCLASS: {
8677 "IS_FPCLASS is used for a non-floating type");
8678 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8679 // is.fpclass(poison, mask) -> poison
8680 if (N1.getOpcode() == ISD::POISON)
8681 return getPOISON(VT);
8682 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8683 // If all tests are made, it doesn't matter what the value is.
8684 if ((Mask & fcAllFlags) == fcAllFlags)
8685 return getBoolConstant(true, DL, VT, N1.getValueType());
8686 if ((Mask & fcAllFlags) == 0)
8687 return getBoolConstant(false, DL, VT, N1.getValueType());
8688 break;
8689 }
8690 case ISD::AssertNoFPClass: {
8692 "AssertNoFPClass is used for a non-floating type");
8693 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8694 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8695 assert(llvm::to_underlying(NoFPClass) <=
8697 "FPClassTest value too large");
8698 (void)NoFPClass;
8699 break;
8700 }
8701 case ISD::AssertSext:
8702 case ISD::AssertZext: {
8703 EVT EVT = cast<VTSDNode>(N2)->getVT();
8704 assert(VT == N1.getValueType() && "Not an inreg extend!");
8705 assert(VT.isInteger() && EVT.isInteger() &&
8706 "Cannot *_EXTEND_INREG FP types");
8707 assert(!EVT.isVector() &&
8708 "AssertSExt/AssertZExt type should be the vector element type "
8709 "rather than the vector type!");
8710 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8711 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8712 break;
8713 }
8715 EVT EVT = cast<VTSDNode>(N2)->getVT();
8716 assert(VT == N1.getValueType() && "Not an inreg extend!");
8717 assert(VT.isInteger() && EVT.isInteger() &&
8718 "Cannot *_EXTEND_INREG FP types");
8719 assert(EVT.isVector() == VT.isVector() &&
8720 "SIGN_EXTEND_INREG type should be vector iff the operand "
8721 "type is vector!");
8722 assert((!EVT.isVector() ||
8724 "Vector element counts must match in SIGN_EXTEND_INREG");
8725 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8726 if (EVT == VT) return N1; // Not actually extending
8727 break;
8728 }
8730 case ISD::FP_TO_UINT_SAT: {
8731 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8732 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8733 assert(N1.getValueType().isVector() == VT.isVector() &&
8734 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8735 "vector!");
8736 assert((!VT.isVector() || VT.getVectorElementCount() ==
8738 "Vector element counts must match in FP_TO_*INT_SAT");
8739 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8740 "Type to saturate to must be a scalar.");
8741 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8742 "Not extending!");
8743 break;
8744 }
8747 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8748 element type of the vector.");
8749
8750 // Extract from an undefined value or using an undefined index is undefined.
8751 if (N1.isUndef() || N2.isUndef())
8752 return getUNDEF(VT);
8753
8754 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8755 // vectors. For scalable vectors we will provide appropriate support for
8756 // dealing with arbitrary indices.
8757 if (N2C && N1.getValueType().isFixedLengthVector() &&
8758 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8759 return getPOISON(VT);
8760
8761 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8762 // expanding copies of large vectors from registers. This only works for
8763 // fixed length vectors, since we need to know the exact number of
8764 // elements.
8765 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8767 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8768 return getExtractVectorElt(DL, VT,
8769 N1.getOperand(N2C->getZExtValue() / Factor),
8770 N2C->getZExtValue() % Factor);
8771 }
8772
8773 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8774 // lowering is expanding large vector constants.
8775 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8776 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8779 "BUILD_VECTOR used for scalable vectors");
8780 unsigned Index =
8781 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8782 SDValue Elt = N1.getOperand(Index);
8783
8784 if (VT != Elt.getValueType())
8785 // If the vector element type is not legal, the BUILD_VECTOR operands
8786 // are promoted and implicitly truncated, and the result implicitly
8787 // extended. Make that explicit here.
8788 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8789
8790 return Elt;
8791 }
8792
8793 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8794 // operations are lowered to scalars.
8795 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8796 // If the indices are the same, return the inserted element else
8797 // if the indices are known different, extract the element from
8798 // the original vector.
8799 SDValue N1Op2 = N1.getOperand(2);
8801
8802 if (N1Op2C && N2C) {
8803 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8804 if (VT == N1.getOperand(1).getValueType())
8805 return N1.getOperand(1);
8806 if (VT.isFloatingPoint()) {
8808 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8809 }
8810 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8811 }
8812 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8813 }
8814 }
8815
8816 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8817 // when vector types are scalarized and v1iX is legal.
8818 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8819 // Here we are completely ignoring the extract element index (N2),
8820 // which is fine for fixed width vectors, since any index other than 0
8821 // is undefined anyway. However, this cannot be ignored for scalable
8822 // vectors - in theory we could support this, but we don't want to do this
8823 // without a profitability check.
8824 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8826 N1.getValueType().getVectorNumElements() == 1) {
8827 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8828 N1.getOperand(1));
8829 }
8830 break;
8832 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8833 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8834 (N1.getValueType().isInteger() == VT.isInteger()) &&
8835 N1.getValueType() != VT &&
8836 "Wrong types for EXTRACT_ELEMENT!");
8837
8838 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8839 // 64-bit integers into 32-bit parts. Instead of building the extract of
8840 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8841 if (N1.getOpcode() == ISD::BUILD_PAIR)
8842 return N1.getOperand(N2C->getZExtValue());
8843
8844 // EXTRACT_ELEMENT of a constant int is also very common.
8845 if (N1C) {
8846 unsigned ElementSize = VT.getSizeInBits();
8847 unsigned Shift = ElementSize * N2C->getZExtValue();
8848 const APInt &Val = N1C->getAPIntValue();
8849 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8850 }
8851 break;
8853 EVT N1VT = N1.getValueType();
8854 assert(VT.isVector() && N1VT.isVector() &&
8855 "Extract subvector VTs must be vectors!");
8857 "Extract subvector VTs must have the same element type!");
8858 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8859 "Cannot extract a scalable vector from a fixed length vector!");
8860 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8862 "Extract subvector must be from larger vector to smaller vector!");
8863 assert(N2C && "Extract subvector index must be a constant");
8864 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8865 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8866 N1VT.getVectorMinNumElements()) &&
8867 "Extract subvector overflow!");
8868 assert(N2C->getAPIntValue().getBitWidth() ==
8869 TLI->getVectorIdxWidth(getDataLayout()) &&
8870 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8871 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8872 "Extract index is not a multiple of the output vector length");
8873
8874 // Trivial extraction.
8875 if (VT == N1VT)
8876 return N1;
8877
8878 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8879 if (N1.isUndef())
8880 return getUNDEF(VT);
8881
8882 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8883 // the concat have the same type as the extract.
8884 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8885 VT == N1.getOperand(0).getValueType()) {
8886 unsigned Factor = VT.getVectorMinNumElements();
8887 return N1.getOperand(N2C->getZExtValue() / Factor);
8888 }
8889
8890 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8891 // during shuffle legalization.
8892 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8893 VT == N1.getOperand(1).getValueType())
8894 return N1.getOperand(1);
8895 break;
8896 }
8897 }
8898
8899 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8900 switch (Opcode) {
8901 case ISD::XOR:
8902 case ISD::ADD:
8903 case ISD::PTRADD:
8904 case ISD::SUB:
8906 case ISD::UDIV:
8907 case ISD::SDIV:
8908 case ISD::UREM:
8909 case ISD::SREM:
8910 case ISD::MUL:
8911 case ISD::AND:
8912 case ISD::SSUBSAT:
8913 case ISD::USUBSAT:
8914 case ISD::UMIN:
8915 case ISD::OR:
8916 case ISD::SADDSAT:
8917 case ISD::UADDSAT:
8918 case ISD::UMAX:
8919 case ISD::SMAX:
8920 case ISD::SMIN:
8921 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8922 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8923 }
8924 }
8925
8926 // Canonicalize an UNDEF to the RHS, even over a constant.
8927 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8928 if (TLI->isCommutativeBinOp(Opcode)) {
8929 std::swap(N1, N2);
8930 } else {
8931 switch (Opcode) {
8932 case ISD::PTRADD:
8933 case ISD::SUB:
8934 // fold op(undef, non_undef_arg2) -> undef.
8935 return N1;
8937 case ISD::UDIV:
8938 case ISD::SDIV:
8939 case ISD::UREM:
8940 case ISD::SREM:
8941 case ISD::SSUBSAT:
8942 case ISD::USUBSAT:
8943 // fold op(undef, non_undef_arg2) -> 0.
8944 return getConstant(0, DL, VT);
8945 }
8946 }
8947 }
8948
8949 // Fold a bunch of operators when the RHS is undef.
8950 if (N2.getOpcode() == ISD::UNDEF) {
8951 switch (Opcode) {
8952 case ISD::XOR:
8953 if (N1.getOpcode() == ISD::UNDEF)
8954 // Handle undef ^ undef -> 0 special case. This is a common
8955 // idiom (misuse).
8956 return getConstant(0, DL, VT);
8957 [[fallthrough]];
8958 case ISD::ADD:
8959 case ISD::PTRADD:
8960 case ISD::SUB:
8961 // fold op(arg1, undef) -> undef.
8962 return N2;
8963 case ISD::UDIV:
8964 case ISD::SDIV:
8965 case ISD::UREM:
8966 case ISD::SREM:
8967 // fold op(arg1, undef) -> poison.
8968 return getPOISON(VT);
8969 case ISD::MUL:
8970 case ISD::AND:
8971 case ISD::SSUBSAT:
8972 case ISD::USUBSAT:
8973 case ISD::UMIN:
8974 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8975 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8976 case ISD::OR:
8977 case ISD::SADDSAT:
8978 case ISD::UADDSAT:
8979 case ISD::UMAX:
8980 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8981 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8982 case ISD::SMAX:
8983 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8984 return N1.getOpcode() == ISD::UNDEF
8985 ? N2
8986 : getConstant(
8988 VT);
8989 case ISD::SMIN:
8990 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8991 return N1.getOpcode() == ISD::UNDEF
8992 ? N2
8993 : getConstant(
8995 VT);
8996 }
8997 }
8998
8999 // Perform trivial constant folding.
9000 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9001 return SV;
9002
9003 // Memoize this node if possible.
9004 SDNode *N;
9005 SDVTList VTs = getVTList(VT);
9006 SDValue Ops[] = {N1, N2};
9007 if (VT != MVT::Glue) {
9009 AddNodeIDNode(ID, Opcode, VTs, Ops);
9010 void *IP = nullptr;
9011 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9012 E->intersectFlagsWith(Flags);
9013 return SDValue(E, 0);
9014 }
9015
9016 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9017 N->setFlags(Flags);
9018 createOperands(N, Ops);
9019 CSEMap.InsertNode(N, IP);
9020 } else {
9021 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9022 createOperands(N, Ops);
9023 }
9024
9025 InsertNode(N);
9026 SDValue V = SDValue(N, 0);
9027 NewSDValueDbgMsg(V, "Creating new node: ", this);
9028 return V;
9029}
9030
9031SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9032 SDValue N1, SDValue N2, SDValue N3) {
9033 SDNodeFlags Flags;
9034 if (Inserter)
9035 Flags = Inserter->getFlags();
9036 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9037}
9038
9039SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9040 SDValue N1, SDValue N2, SDValue N3,
9041 const SDNodeFlags Flags) {
9043 N2.getOpcode() != ISD::DELETED_NODE &&
9044 N3.getOpcode() != ISD::DELETED_NODE &&
9045 "Operand is DELETED_NODE!");
9046 // Perform various simplifications.
9047 switch (Opcode) {
9048 case ISD::BUILD_VECTOR: {
9049 // Attempt to simplify BUILD_VECTOR.
9050 SDValue Ops[] = {N1, N2, N3};
9051 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9052 return V;
9053 break;
9054 }
9055 case ISD::CONCAT_VECTORS: {
9056 SDValue Ops[] = {N1, N2, N3};
9057 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9058 return V;
9059 break;
9060 }
9061 case ISD::SETCC: {
9062 assert(VT.isInteger() && "SETCC result type must be an integer!");
9063 assert(N1.getValueType() == N2.getValueType() &&
9064 "SETCC operands must have the same type!");
9065 assert(VT.isVector() == N1.getValueType().isVector() &&
9066 "SETCC type should be vector iff the operand type is vector!");
9067 assert((!VT.isVector() || VT.getVectorElementCount() ==
9069 "SETCC vector element counts must match!");
9070 // Use FoldSetCC to simplify SETCC's.
9071 if (SDValue V =
9072 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9073 return V;
9074 break;
9075 }
9076 case ISD::SELECT:
9077 case ISD::VSELECT:
9078 if (SDValue V = simplifySelect(N1, N2, N3))
9079 return V;
9080 break;
9082 llvm_unreachable("should use getVectorShuffle constructor!");
9084 if (isNullConstant(N3))
9085 return N1;
9086 break;
9088 if (isNullConstant(N3))
9089 return N2;
9090 break;
9092 assert(VT.isVector() && VT == N1.getValueType() &&
9093 "INSERT_VECTOR_ELT vector type mismatch");
9095 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9096 assert((!VT.isFloatingPoint() ||
9097 VT.getVectorElementType() == N2.getValueType()) &&
9098 "INSERT_VECTOR_ELT fp scalar type mismatch");
9099 assert((!VT.isInteger() ||
9101 "INSERT_VECTOR_ELT int scalar size mismatch");
9102
9103 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9104 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9105 // for scalable vectors where we will generate appropriate code to
9106 // deal with out-of-bounds cases correctly.
9107 if (N3C && VT.isFixedLengthVector() &&
9108 N3C->getZExtValue() >= VT.getVectorNumElements())
9109 return getUNDEF(VT);
9110
9111 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9112 if (N3.isUndef())
9113 return getUNDEF(VT);
9114
9115 // If inserting poison, just use the input vector.
9116 if (N2.getOpcode() == ISD::POISON)
9117 return N1;
9118
9119 // Inserting undef into undef/poison is still undef.
9120 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9121 return getUNDEF(VT);
9122
9123 // If the inserted element is an UNDEF, just use the input vector.
9124 // But not if skipping the insert could make the result more poisonous.
9125 if (N2.isUndef()) {
9126 if (N3C && VT.isFixedLengthVector()) {
9127 APInt EltMask =
9128 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9129 if (isGuaranteedNotToBePoison(N1, EltMask))
9130 return N1;
9131 } else if (isGuaranteedNotToBePoison(N1))
9132 return N1;
9133 }
9134 break;
9135 }
9136 case ISD::INSERT_SUBVECTOR: {
9137 // If inserting poison, just use the input vector,
9138 if (N2.getOpcode() == ISD::POISON)
9139 return N1;
9140
9141 // Inserting undef into undef/poison is still undef.
9142 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9143 return getUNDEF(VT);
9144
9145 EVT N2VT = N2.getValueType();
9146 assert(VT == N1.getValueType() &&
9147 "Dest and insert subvector source types must match!");
9148 assert(VT.isVector() && N2VT.isVector() &&
9149 "Insert subvector VTs must be vectors!");
9151 "Insert subvector VTs must have the same element type!");
9152 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9153 "Cannot insert a scalable vector into a fixed length vector!");
9154 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9156 "Insert subvector must be from smaller vector to larger vector!");
9158 "Insert subvector index must be constant");
9159 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9160 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9162 "Insert subvector overflow!");
9164 TLI->getVectorIdxWidth(getDataLayout()) &&
9165 "Constant index for INSERT_SUBVECTOR has an invalid size");
9166
9167 // Trivial insertion.
9168 if (VT == N2VT)
9169 return N2;
9170
9171 // If this is an insert of an extracted vector into an undef/poison vector,
9172 // we can just use the input to the extract. But not if skipping the
9173 // extract+insert could make the result more poisonous.
9174 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9175 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9176 if (N1.getOpcode() == ISD::POISON)
9177 return N2.getOperand(0);
9178 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9179 unsigned LoBit = N3->getAsZExtVal();
9180 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9181 APInt EltMask =
9182 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9183 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9184 return N2.getOperand(0);
9185 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9186 return N2.getOperand(0);
9187 }
9188
9189 // If the inserted subvector is UNDEF, just use the input vector.
9190 // But not if skipping the insert could make the result more poisonous.
9191 if (N2.isUndef()) {
9192 if (VT.isFixedLengthVector()) {
9193 unsigned LoBit = N3->getAsZExtVal();
9194 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9195 APInt EltMask =
9196 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9197 if (isGuaranteedNotToBePoison(N1, EltMask))
9198 return N1;
9199 } else if (isGuaranteedNotToBePoison(N1))
9200 return N1;
9201 }
9202 break;
9203 }
9204 case ISD::BITCAST:
9205 // Fold bit_convert nodes from a type to themselves.
9206 if (N1.getValueType() == VT)
9207 return N1;
9208 break;
9209 case ISD::VP_TRUNCATE:
9210 case ISD::VP_SIGN_EXTEND:
9211 case ISD::VP_ZERO_EXTEND:
9212 // Don't create noop casts.
9213 if (N1.getValueType() == VT)
9214 return N1;
9215 break;
9216 case ISD::VECTOR_COMPRESS: {
9217 [[maybe_unused]] EVT VecVT = N1.getValueType();
9218 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9219 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9220 assert(VT == VecVT && "Vector and result type don't match.");
9221 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9222 "All inputs must be vectors.");
9223 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9225 "Vector and mask must have same number of elements.");
9226
9227 if (N1.isUndef() || N2.isUndef())
9228 return N3;
9229
9230 break;
9231 }
9236 [[maybe_unused]] EVT AccVT = N1.getValueType();
9237 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9238 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9239 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9240 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9241 "node to have the same type!");
9242 assert(VT.isVector() && VT == AccVT &&
9243 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9244 "the same type as its result!");
9246 AccVT.getVectorElementCount()) &&
9247 "Expected the element count of the second and third operands of the "
9248 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9249 "element count of the first operand and the result!");
9251 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9252 "node to have an element type which is the same as or smaller than "
9253 "the element type of the first operand and result!");
9254 break;
9255 }
9256 }
9257
9258 // Perform trivial constant folding for arithmetic operators.
9259 switch (Opcode) {
9263 case ISD::FMA:
9264 case ISD::FMAD:
9265 case ISD::SETCC:
9266 case ISD::FSHL:
9267 case ISD::FSHR:
9268 if (SDValue SV =
9269 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9270 return SV;
9271 break;
9272 }
9273
9274 // Memoize node if it doesn't produce a glue result.
9275 SDNode *N;
9276 SDVTList VTs = getVTList(VT);
9277 SDValue Ops[] = {N1, N2, N3};
9278 if (VT != MVT::Glue) {
9280 AddNodeIDNode(ID, Opcode, VTs, Ops);
9281 void *IP = nullptr;
9282 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9283 E->intersectFlagsWith(Flags);
9284 return SDValue(E, 0);
9285 }
9286
9287 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9288 N->setFlags(Flags);
9289 createOperands(N, Ops);
9290 CSEMap.InsertNode(N, IP);
9291 } else {
9292 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9293 createOperands(N, Ops);
9294 }
9295
9296 InsertNode(N);
9297 SDValue V = SDValue(N, 0);
9298 NewSDValueDbgMsg(V, "Creating new node: ", this);
9299 return V;
9300}
9301
9302SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9303 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9304 const SDNodeFlags Flags) {
9305 SDValue Ops[] = { N1, N2, N3, N4 };
9306 return getNode(Opcode, DL, VT, Ops, Flags);
9307}
9308
9309SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9310 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9311 SDNodeFlags Flags;
9312 if (Inserter)
9313 Flags = Inserter->getFlags();
9314 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9315}
9316
9317SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9318 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9319 SDValue N5, const SDNodeFlags Flags) {
9320 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9321 return getNode(Opcode, DL, VT, Ops, Flags);
9322}
9323
9324SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9325 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9326 SDValue N5) {
9327 SDNodeFlags Flags;
9328 if (Inserter)
9329 Flags = Inserter->getFlags();
9330 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9331}
9332
9333/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9334/// the incoming stack arguments to be loaded from the stack.
9336 SmallVector<SDValue, 8> ArgChains;
9337
9338 // Include the original chain at the beginning of the list. When this is
9339 // used by target LowerCall hooks, this helps legalize find the
9340 // CALLSEQ_BEGIN node.
9341 ArgChains.push_back(Chain);
9342
9343 // Add a chain value for each stack argument.
9344 for (SDNode *U : getEntryNode().getNode()->users())
9345 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9346 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9347 if (FI->getIndex() < 0)
9348 ArgChains.push_back(SDValue(L, 1));
9349
9350 // Build a tokenfactor for all the chains.
9351 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9352}
9353
9354/// getMemsetValue - Vectorized representation of the memset value
9355/// operand.
9357 const SDLoc &dl) {
9358 assert(!Value.isUndef());
9359
9360 unsigned NumBits = VT.getScalarSizeInBits();
9362 assert(C->getAPIntValue().getBitWidth() == 8);
9363 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9364 if (VT.isInteger()) {
9365 bool IsOpaque = VT.getSizeInBits() > 64 ||
9366 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9367 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9368 }
9369 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9370 }
9371
9372 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9373 EVT IntVT = VT.getScalarType();
9374 if (!IntVT.isInteger())
9375 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9376
9377 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9378 if (NumBits > 8) {
9379 // Use a multiplication with 0x010101... to extend the input to the
9380 // required length.
9381 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9382 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9383 DAG.getConstant(Magic, dl, IntVT));
9384 }
9385
9386 if (VT != Value.getValueType() && !VT.isInteger())
9387 Value = DAG.getBitcast(VT.getScalarType(), Value);
9388 if (VT != Value.getValueType())
9389 Value = DAG.getSplatBuildVector(VT, dl, Value);
9390
9391 return Value;
9392}
9393
9394/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9395/// used when a memcpy is turned into a memset when the source is a constant
9396/// string ptr.
9398 const TargetLowering &TLI,
9399 const ConstantDataArraySlice &Slice) {
9400 // Handle vector with all elements zero.
9401 if (Slice.Array == nullptr) {
9402 if (VT.isInteger())
9403 return DAG.getConstant(0, dl, VT);
9404 return DAG.getNode(ISD::BITCAST, dl, VT,
9405 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9406 }
9407
9408 assert(!VT.isVector() && "Can't handle vector type here!");
9409 unsigned NumVTBits = VT.getSizeInBits();
9410 unsigned NumVTBytes = NumVTBits / 8;
9411 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9412
9413 APInt Val(NumVTBits, 0);
9414 if (DAG.getDataLayout().isLittleEndian()) {
9415 for (unsigned i = 0; i != NumBytes; ++i)
9416 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9417 } else {
9418 for (unsigned i = 0; i != NumBytes; ++i)
9419 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9420 }
9421
9422 // If the "cost" of materializing the integer immediate is less than the cost
9423 // of a load, then it is cost effective to turn the load into the immediate.
9424 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9425 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9426 return DAG.getConstant(Val, dl, VT);
9427 return SDValue();
9428}
9429
9431 const SDLoc &DL,
9432 const SDNodeFlags Flags) {
9433 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9434 return getMemBasePlusOffset(Base, Index, DL, Flags);
9435}
9436
9438 const SDLoc &DL,
9439 const SDNodeFlags Flags) {
9440 assert(Offset.getValueType().isInteger());
9441 EVT BasePtrVT = Ptr.getValueType();
9442 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9443 BasePtrVT))
9444 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9445 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9446 SDNodeFlags AddFlags = Flags;
9447 AddFlags.setInBounds(false);
9448 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9449}
9450
9451/// Returns true if memcpy source is constant data.
9453 uint64_t SrcDelta = 0;
9454 GlobalAddressSDNode *G = nullptr;
9455 if (Src.getOpcode() == ISD::GlobalAddress)
9457 else if (Src->isAnyAdd() &&
9458 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9459 Src.getOperand(1).getOpcode() == ISD::Constant) {
9460 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9461 SrcDelta = Src.getConstantOperandVal(1);
9462 }
9463 if (!G)
9464 return false;
9465
9466 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9467 SrcDelta + G->getOffset());
9468}
9469
9471 SelectionDAG &DAG) {
9472 // On Darwin, -Os means optimize for size without hurting performance, so
9473 // only really optimize for size when -Oz (MinSize) is used.
9475 return MF.getFunction().hasMinSize();
9476 return DAG.shouldOptForSize();
9477}
9478
9480 SmallVector<SDValue, 32> &OutChains, unsigned From,
9481 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9482 SmallVector<SDValue, 16> &OutStoreChains) {
9483 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9484 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9485 SmallVector<SDValue, 16> GluedLoadChains;
9486 for (unsigned i = From; i < To; ++i) {
9487 OutChains.push_back(OutLoadChains[i]);
9488 GluedLoadChains.push_back(OutLoadChains[i]);
9489 }
9490
9491 // Chain for all loads.
9492 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9493 GluedLoadChains);
9494
9495 for (unsigned i = From; i < To; ++i) {
9496 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9497 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9498 ST->getBasePtr(), ST->getMemoryVT(),
9499 ST->getMemOperand());
9500 OutChains.push_back(NewStore);
9501 }
9502}
9503
9504static SDValue
9506 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9507 Align SrcAlign, bool isVol, bool AlwaysInline,
9508 MachinePointerInfo DstPtrInfo,
9509 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9510 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9511 const MDNode *SrcMemCacheHint) {
9512 // Turn a memcpy of undef to nop.
9513 // FIXME: We need to honor volatile even is Src is undef.
9514 if (Src.isUndef())
9515 return Chain;
9516
9517 // Expand memcpy to a series of load and store ops if the size operand falls
9518 // below a certain threshold.
9519 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9520 // rather than maybe a humongous number of loads and stores.
9521 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9522 const DataLayout &DL = DAG.getDataLayout();
9523 LLVMContext &C = *DAG.getContext();
9524 std::vector<EVT> MemOps;
9525 bool DstAlignCanChange = false;
9527 MachineFrameInfo &MFI = MF.getFrameInfo();
9528 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9530 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9531 DstAlignCanChange = true;
9532 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9534 // If marked as volatile, perform a copy even when marked as constant.
9535 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9536 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9537 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9538 const MemOp Op = isZeroConstant
9539 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9540 /*IsZeroMemset*/ true, isVol)
9541 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9542 SrcAlign, isVol, CopyFromConstant);
9543 if (!TLI.findOptimalMemOpLowering(
9544 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9545 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9546 return SDValue();
9547
9548 if (DstAlignCanChange) {
9549 Type *Ty = MemOps[0].getTypeForEVT(C);
9550 Align NewDstAlign = DL.getABITypeAlign(Ty);
9551
9552 // Don't promote to an alignment that would require dynamic stack
9553 // realignment which may conflict with optimizations such as tail call
9554 // optimization.
9556 if (!TRI->hasStackRealignment(MF))
9557 if (MaybeAlign StackAlign = DL.getStackAlignment())
9558 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9559
9560 if (NewDstAlign > DstAlign) {
9561 // Give the stack frame object a larger alignment if needed.
9562 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9563 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9564 DstAlign = NewDstAlign;
9565 }
9566 }
9567
9568 // Prepare AAInfo for loads/stores after lowering this memcpy.
9569 AAMDNodes NewAAInfo = AAInfo;
9570 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9571
9572 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9573 bool isConstant =
9574 BatchAA && SrcVal &&
9575 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9576
9577 MachineMemOperand::Flags MMOFlags =
9579 SmallVector<SDValue, 16> OutLoadChains;
9580 SmallVector<SDValue, 16> OutStoreChains;
9581 SmallVector<SDValue, 32> OutChains;
9582 unsigned NumMemOps = MemOps.size();
9583 uint64_t SrcOff = 0, DstOff = 0;
9584 for (unsigned i = 0; i != NumMemOps; ++i) {
9585 EVT VT = MemOps[i];
9586 unsigned VTSize = VT.getSizeInBits() / 8;
9588
9589 if (VTSize > Size) {
9590 // Issuing an unaligned load / store pair that overlaps with the previous
9591 // pair. Adjust the offset accordingly.
9592 assert(i == NumMemOps-1 && i != 0);
9593 SrcOff -= VTSize - Size;
9594 DstOff -= VTSize - Size;
9595 }
9596
9597 if (CopyFromConstant &&
9598 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9599 // It's unlikely a store of a vector immediate can be done in a single
9600 // instruction. It would require a load from a constantpool first.
9601 // We only handle zero vectors here.
9602 // FIXME: Handle other cases where store of vector immediate is done in
9603 // a single instruction.
9604 ConstantDataArraySlice SubSlice;
9605 if (SrcOff < Slice.Length) {
9606 SubSlice = Slice;
9607 SubSlice.move(SrcOff);
9608 } else {
9609 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9610 SubSlice.Array = nullptr;
9611 SubSlice.Offset = 0;
9612 SubSlice.Length = VTSize;
9613 }
9614 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9615 if (Value.getNode()) {
9616 Store = DAG.getStore(
9617 Chain, dl, Value,
9618 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9619 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9620 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9621 OutChains.push_back(Store);
9622 }
9623 }
9624
9625 if (!Store.getNode()) {
9626 // The type might not be legal for the target. This should only happen
9627 // if the type is smaller than a legal type, as on PPC, so the right
9628 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9629 // to Load/Store if NVT==VT.
9630 // FIXME does the case above also need this?
9631 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9632 assert(NVT.bitsGE(VT));
9633
9634 bool isDereferenceable =
9635 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9636 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9637 if (isDereferenceable)
9639 if (isConstant)
9640 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9641
9642 Value = DAG.getExtLoad(
9643 ISD::EXTLOAD, dl, NVT, Chain,
9644 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9645 SrcPtrInfo.getWithOffset(SrcOff), VT,
9646 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9647 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9648 OutLoadChains.push_back(Value.getValue(1));
9649
9650 Store = DAG.getTruncStore(
9651 Chain, dl, Value,
9652 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9653 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9654 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9655 OutStoreChains.push_back(Store);
9656 }
9657 SrcOff += VTSize;
9658 DstOff += VTSize;
9659 Size -= VTSize;
9660 }
9661
9662 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9664 unsigned NumLdStInMemcpy = OutStoreChains.size();
9665
9666 if (NumLdStInMemcpy) {
9667 // It may be that memcpy might be converted to memset if it's memcpy
9668 // of constants. In such a case, we won't have loads and stores, but
9669 // just stores. In the absence of loads, there is nothing to gang up.
9670 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9671 // If target does not care, just leave as it.
9672 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9673 OutChains.push_back(OutLoadChains[i]);
9674 OutChains.push_back(OutStoreChains[i]);
9675 }
9676 } else {
9677 // Ld/St less than/equal limit set by target.
9678 if (NumLdStInMemcpy <= GluedLdStLimit) {
9679 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9680 NumLdStInMemcpy, OutLoadChains,
9681 OutStoreChains);
9682 } else {
9683 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9684 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9685 unsigned GlueIter = 0;
9686
9687 // Residual ld/st.
9688 if (RemainingLdStInMemcpy) {
9690 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9691 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9692 }
9693
9694 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9695 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9696 GlueIter - GluedLdStLimit;
9697 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9698 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9699 OutLoadChains, OutStoreChains);
9700 GlueIter += GluedLdStLimit;
9701 }
9702 }
9703 }
9704 }
9705 return DAG.getTokenFactor(dl, OutChains);
9706}
9707
9709 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9710 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9711 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9712 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9713 // Turn a memmove of undef to nop.
9714 // FIXME: We need to honor volatile even is Src is undef.
9715 if (Src.isUndef())
9716 return Chain;
9717
9718 // Expand memmove to a series of load and store ops if the size operand falls
9719 // below a certain threshold.
9720 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9721 const DataLayout &DL = DAG.getDataLayout();
9722 LLVMContext &C = *DAG.getContext();
9723 std::vector<EVT> MemOps;
9724 bool DstAlignCanChange = false;
9726 MachineFrameInfo &MFI = MF.getFrameInfo();
9727 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9729 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9730 DstAlignCanChange = true;
9731 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9732 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9733 if (!TLI.findOptimalMemOpLowering(
9734 C, MemOps, Limit,
9735 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9736 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9737 MF.getFunction().getAttributes(), nullptr))
9738 return SDValue();
9739
9740 if (DstAlignCanChange) {
9741 Type *Ty = MemOps[0].getTypeForEVT(C);
9742 Align NewDstAlign = DL.getABITypeAlign(Ty);
9743
9744 // Don't promote to an alignment that would require dynamic stack
9745 // realignment which may conflict with optimizations such as tail call
9746 // optimization.
9748 if (!TRI->hasStackRealignment(MF))
9749 if (MaybeAlign StackAlign = DL.getStackAlignment())
9750 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9751
9752 if (NewDstAlign > DstAlign) {
9753 // Give the stack frame object a larger alignment if needed.
9754 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9755 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9756 DstAlign = NewDstAlign;
9757 }
9758 }
9759
9760 // Prepare AAInfo for loads/stores after lowering this memmove.
9761 AAMDNodes NewAAInfo = AAInfo;
9762 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9763
9764 MachineMemOperand::Flags MMOFlags =
9766 uint64_t SrcOff = 0;
9767 SmallVector<SDValue, 8> LoadValues;
9768 SmallVector<SDValue, 8> LoadChains;
9769 SmallVector<SDValue, 8> OutChains;
9770 unsigned NumMemOps = MemOps.size();
9771 for (unsigned i = 0; i < NumMemOps; i++) {
9772 EVT VT = MemOps[i];
9773 unsigned VTSize = VT.getSizeInBits() / 8;
9774 SDValue Value;
9775 bool IsOverlapping = false;
9776
9777 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9778 // Issuing an unaligned load / store pair that overlaps with the previous
9779 // pair. Adjust the offset accordingly.
9780 SrcOff = Size - VTSize;
9781 IsOverlapping = true;
9782 }
9783
9784 // Calculate the actual alignment at the current offset. The alignment at
9785 // SrcOff may be lower than the base alignment, especially when using
9786 // overlapping loads.
9787 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9788 if (IsOverlapping) {
9789 // Verify that the target allows misaligned memory accesses at the
9790 // adjusted offset when using overlapping loads.
9791 unsigned Fast;
9792 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9793 SrcAlignAtOffset, MMOFlags,
9794 &Fast) ||
9795 !Fast) {
9796 // This should have been caught by findOptimalMemOpLowering, but verify
9797 // here for safety.
9798 return SDValue();
9799 }
9800 }
9801
9802 bool isDereferenceable =
9803 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9804 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9805 if (isDereferenceable)
9807 Value =
9808 DAG.getLoad(VT, dl, Chain,
9809 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9810 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9811 SrcMMOFlags, NewAAInfo);
9812 LoadValues.push_back(Value);
9813 LoadChains.push_back(Value.getValue(1));
9814 SrcOff += VTSize;
9815 }
9816 Chain = DAG.getTokenFactor(dl, LoadChains);
9817 OutChains.clear();
9818 uint64_t DstOff = 0;
9819 for (unsigned i = 0; i < NumMemOps; i++) {
9820 EVT VT = MemOps[i];
9821 unsigned VTSize = VT.getSizeInBits() / 8;
9822 SDValue Store;
9823 bool IsOverlapping = false;
9824
9825 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9826 // Issuing an unaligned load / store pair that overlaps with the previous
9827 // pair. Adjust the offset accordingly.
9828 DstOff = Size - VTSize;
9829 IsOverlapping = true;
9830 }
9831
9832 // Calculate the actual alignment at the current offset. The alignment at
9833 // DstOff may be lower than the base alignment, especially when using
9834 // overlapping stores.
9835 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9836 if (IsOverlapping) {
9837 // Verify that the target allows misaligned memory accesses at the
9838 // adjusted offset when using overlapping stores.
9839 unsigned Fast;
9840 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9841 DstAlignAtOffset, MMOFlags,
9842 &Fast) ||
9843 !Fast) {
9844 // This should have been caught by findOptimalMemOpLowering, but verify
9845 // here for safety.
9846 return SDValue();
9847 }
9848 }
9849 Store = DAG.getStore(
9850 Chain, dl, LoadValues[i],
9851 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9852 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9853 NewAAInfo);
9854 OutChains.push_back(Store);
9855 DstOff += VTSize;
9856 }
9857
9858 return DAG.getTokenFactor(dl, OutChains);
9859}
9860
9861/// Lower the call to 'memset' intrinsic function into a series of store
9862/// operations.
9863///
9864/// \param DAG Selection DAG where lowered code is placed.
9865/// \param dl Link to corresponding IR location.
9866/// \param Chain Control flow dependency.
9867/// \param Dst Pointer to destination memory location.
9868/// \param Src Value of byte to write into the memory.
9869/// \param Size Number of bytes to write.
9870/// \param Alignment Alignment of the destination in bytes.
9871/// \param isVol True if destination is volatile.
9872/// \param AlwaysInline Makes sure no function call is generated.
9873/// \param DstPtrInfo IR information on the memory pointer.
9874/// \returns New head in the control flow, if lowering was successful, empty
9875/// SDValue otherwise.
9876///
9877/// The function tries to replace 'llvm.memset' intrinsic with several store
9878/// operations and value calculation code. This is usually profitable for small
9879/// memory size or when the semantic requires inlining.
9881 SDValue Chain, SDValue Dst, SDValue Src,
9882 uint64_t Size, Align Alignment, bool isVol,
9883 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9884 const AAMDNodes &AAInfo) {
9885 // Turn a memset of undef to nop.
9886 // FIXME: We need to honor volatile even is Src is undef.
9887 if (Src.isUndef())
9888 return Chain;
9889
9890 // Expand memset to a series of load/store ops if the size operand
9891 // falls below a certain threshold.
9892 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9893 std::vector<EVT> MemOps;
9894 bool DstAlignCanChange = false;
9895 LLVMContext &C = *DAG.getContext();
9897 MachineFrameInfo &MFI = MF.getFrameInfo();
9898 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9900 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9901 DstAlignCanChange = true;
9902 bool IsZeroVal = isNullConstant(Src);
9903 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9904
9905 EVT LargestVT;
9906 if (!TLI.findOptimalMemOpLowering(
9907 C, MemOps, Limit,
9908 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9909 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
9910 &LargestVT))
9911 return SDValue();
9912
9913 if (DstAlignCanChange) {
9914 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9915 const DataLayout &DL = DAG.getDataLayout();
9916 Align NewAlign = DL.getABITypeAlign(Ty);
9917
9918 // Don't promote to an alignment that would require dynamic stack
9919 // realignment which may conflict with optimizations such as tail call
9920 // optimization.
9922 if (!TRI->hasStackRealignment(MF))
9923 if (MaybeAlign StackAlign = DL.getStackAlignment())
9924 NewAlign = std::min(NewAlign, *StackAlign);
9925
9926 if (NewAlign > Alignment) {
9927 // Give the stack frame object a larger alignment if needed.
9928 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9929 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9930 Alignment = NewAlign;
9931 }
9932 }
9933
9934 SmallVector<SDValue, 8> OutChains;
9935 uint64_t DstOff = 0;
9936 unsigned NumMemOps = MemOps.size();
9937
9938 // Find the largest store and generate the bit pattern for it.
9939 // If target didn't set LargestVT, compute it from MemOps.
9940 if (!LargestVT.isSimple()) {
9941 LargestVT = MemOps[0];
9942 for (unsigned i = 1; i < NumMemOps; i++)
9943 if (MemOps[i].bitsGT(LargestVT))
9944 LargestVT = MemOps[i];
9945 }
9946 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9947
9948 // Prepare AAInfo for loads/stores after lowering this memset.
9949 AAMDNodes NewAAInfo = AAInfo;
9950 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9951
9952 for (unsigned i = 0; i < NumMemOps; i++) {
9953 EVT VT = MemOps[i];
9954 unsigned VTSize = VT.getSizeInBits() / 8;
9955 // The target should specify store types that exactly cover the memset size
9956 // (with the last store potentially being oversized for overlapping stores).
9957 assert(Size > 0 && "Target specified more stores than needed in "
9958 "findOptimalMemOpLowering");
9959 if (VTSize > Size) {
9960 // Issuing an unaligned load / store pair that overlaps with the previous
9961 // pair. Adjust the offset accordingly.
9962 assert(i == NumMemOps-1 && i != 0);
9963 DstOff -= VTSize - Size;
9964 }
9965
9966 // If this store is smaller than the largest store see whether we can get
9967 // the smaller value for free with a truncate or extract vector element and
9968 // then store.
9969 SDValue Value = MemSetValue;
9970 if (VT.bitsLT(LargestVT)) {
9971 unsigned Index;
9972 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9973 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9974 if (!LargestVT.isVector() && !VT.isVector() &&
9975 TLI.isTruncateFree(LargestVT, VT))
9976 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9977 else if (LargestVT.isVector() && !VT.isVector() &&
9979 LargestVT.getTypeForEVT(*DAG.getContext()),
9980 VT.getSizeInBits(), Index) &&
9981 TLI.isTypeLegal(SVT) &&
9982 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9983 // Target which can combine store(extractelement VectorTy, Idx) can get
9984 // the smaller value for free.
9985 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9986 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9987 } else
9988 Value = getMemsetValue(Src, VT, DAG, dl);
9989 }
9990 assert(Value.getValueType() == VT && "Value with wrong type.");
9991 SDValue Store = DAG.getStore(
9992 Chain, dl, Value,
9993 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9994 DstPtrInfo.getWithOffset(DstOff), Alignment,
9996 NewAAInfo);
9997 OutChains.push_back(Store);
9998 DstOff += VT.getSizeInBits() / 8;
9999 // For oversized overlapping stores, only subtract the remaining bytes.
10000 // For normal stores, subtract the full store size.
10001 if (VTSize > Size) {
10002 Size = 0;
10003 } else {
10004 Size -= VTSize;
10005 }
10006 }
10007
10008 // After processing all stores, Size should be exactly 0. Any remaining bytes
10009 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10010 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10011 "stores that exactly cover the memset size");
10012
10013 return DAG.getTokenFactor(dl, OutChains);
10014}
10015
10017 unsigned AS) {
10018 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10019 // pointer operands can be losslessly bitcasted to pointers of address space 0
10020 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
10021 report_fatal_error("cannot lower memory intrinsic in address space " +
10022 Twine(AS));
10023 }
10024}
10025
10027 const SelectionDAG *SelDAG,
10028 bool AllowReturnsFirstArg) {
10029 if (!CI || !CI->isTailCall())
10030 return false;
10031 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10032 // helper symbol we lower to.
10033 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10034 AllowReturnsFirstArg &&
10036}
10037
10038static std::pair<SDValue, SDValue>
10041 const CallInst *CI, RTLIB::Libcall Call,
10042 SelectionDAG *DAG, const TargetLowering *TLI) {
10043 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10044
10045 if (LCImpl == RTLIB::Unsupported)
10046 return {};
10047
10049 bool IsTailCall =
10050 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10051 // Lowering doesn't support tail calling inside a function with
10052 // a swifterror argument yet.
10053 !DAG->hasSwiftErrorArg();
10054 SDValue Callee =
10055 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10056
10057 CLI.setDebugLoc(dl)
10058 .setChain(Chain)
10060 CI->getType(), Callee, std::move(Args))
10061 .setTailCall(IsTailCall);
10062
10063 return TLI->LowerCallTo(CLI);
10064}
10065
10066std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10067 const SDLoc &dl, SDValue S1,
10068 SDValue S2,
10069 const CallInst *CI) {
10071 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10072 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10073 RTLIB::STRCMP, this, TLI);
10074}
10075
10076std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10077 const SDLoc &dl, SDValue S1,
10078 SDValue S2,
10079 const CallInst *CI) {
10081 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10082 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10083 RTLIB::STRSTR, this, TLI);
10084}
10085
10086std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10087 const SDLoc &dl,
10088 SDValue Dst, SDValue Src,
10090 const CallInst *CI) {
10092
10094 {Dst, PT},
10095 {Src, PT},
10098 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10099 RTLIB::MEMCCPY, this, TLI);
10100}
10101
10102std::pair<SDValue, SDValue>
10104 SDValue Mem1, SDValue Size, const CallInst *CI) {
10107 {Mem0, PT},
10108 {Mem1, PT},
10110 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10111 RTLIB::MEMCMP, this, TLI);
10112}
10113
10114std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10115 const SDLoc &dl,
10116 SDValue Dst, SDValue Src,
10117 const CallInst *CI) {
10119 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10120 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10121 RTLIB::STRCPY, this, TLI);
10122}
10123
10124std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10125 const SDLoc &dl,
10126 SDValue Src,
10127 const CallInst *CI) {
10128 // Emit a library call.
10131 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10132 RTLIB::STRLEN, this, TLI);
10133}
10134
10136 return TLI->supportSwiftError() &&
10137 MF->getFunction().getAttributes().hasAttrSomewhere(
10138 Attribute::SwiftError);
10139}
10140
10142 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10143 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10144 const CallInst *CI, std::optional<bool> OverrideTailCall,
10145 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10146 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10147 // Check to see if we should lower the memcpy to loads and stores first.
10148 // For cases within the target-specified limits, this is the best choice.
10149 const MDNode *DstMemCacheHint =
10150 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10151 const MDNode *SrcMemCacheHint =
10152 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10153
10155 if (ConstantSize) {
10156 // Memcpy with size zero? Just return the original chain.
10157 if (ConstantSize->isZero())
10158 return Chain;
10159
10161 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10162 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10163 DstMemCacheHint, SrcMemCacheHint);
10164 if (Result.getNode())
10165 return Result;
10166 }
10167
10168 // Then check to see if we should lower the memcpy with target-specific
10169 // code. If the target chooses to do this, this is the next best.
10170 if (TSI) {
10171 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10172 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10173 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10174 if (Result.getNode())
10175 return Result;
10176 }
10177
10178 // If we really need inline code and the target declined to provide it,
10179 // use a (potentially long) sequence of loads and stores.
10180 if (AlwaysInline) {
10181 assert(ConstantSize && "AlwaysInline requires a constant size!");
10183 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10184 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10185 DstMemCacheHint, SrcMemCacheHint);
10186 }
10187
10190
10191 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10192 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10193 // respect volatile, so they may do things like read or write memory
10194 // beyond the given memory regions. But fixing this isn't easy, and most
10195 // people don't care.
10196
10197 // Emit a library call.
10200 Args.emplace_back(Dst, PtrTy);
10201 Args.emplace_back(Src, PtrTy);
10202 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10203 // FIXME: pass in SDLoc
10205 bool IsTailCall = false;
10206 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10207
10208 if (OverrideTailCall.has_value()) {
10209 IsTailCall = *OverrideTailCall;
10210 } else {
10211 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10212 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10213 }
10214 // Lowering doesn't support tail calling inside a function with a
10215 // swifterror argument yet.
10216 IsTailCall &= !hasSwiftErrorArg();
10217
10218 CLI.setDebugLoc(dl)
10219 .setChain(Chain)
10220 .setLibCallee(
10221 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10222 Dst.getValueType().getTypeForEVT(*getContext()),
10223 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10224 std::move(Args))
10226 .setTailCall(IsTailCall);
10227
10228 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10229 return CallResult.second;
10230}
10231
10233 SDValue Dst, SDValue Src, SDValue Size,
10234 Type *SizeTy, unsigned ElemSz,
10235 bool isTailCall,
10236 MachinePointerInfo DstPtrInfo,
10237 MachinePointerInfo SrcPtrInfo) {
10238 // Lowering doesn't support tail calling inside a function with a
10239 // swifterror argument yet.
10240 isTailCall &= !hasSwiftErrorArg();
10241
10242 // Emit a library call.
10245 Args.emplace_back(Dst, ArgTy);
10246 Args.emplace_back(Src, ArgTy);
10247 Args.emplace_back(Size, SizeTy);
10248
10249 RTLIB::Libcall LibraryCall =
10251 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10252 if (LibcallImpl == RTLIB::Unsupported)
10253 report_fatal_error("Unsupported element size");
10254
10256 CLI.setDebugLoc(dl)
10257 .setChain(Chain)
10258 .setLibCallee(
10259 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10261 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10262 std::move(Args))
10264 .setTailCall(isTailCall);
10265
10266 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10267 return CallResult.second;
10268}
10269
10271 SDValue Src, SDValue Size, Align DstAlign,
10272 Align SrcAlign, bool isVol, const CallInst *CI,
10273 std::optional<bool> OverrideTailCall,
10274 MachinePointerInfo DstPtrInfo,
10275 MachinePointerInfo SrcPtrInfo,
10276 const AAMDNodes &AAInfo,
10277 BatchAAResults *BatchAA) {
10278 // Check to see if we should lower the memmove to loads and stores first.
10279 // For cases within the target-specified limits, this is the best choice.
10281 if (ConstantSize) {
10282 // Memmove with size zero? Just return the original chain.
10283 if (ConstantSize->isZero())
10284 return Chain;
10285
10287 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10288 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10289 if (Result.getNode())
10290 return Result;
10291 }
10292
10293 // Then check to see if we should lower the memmove with target-specific
10294 // code. If the target chooses to do this, this is the next best.
10295 if (TSI) {
10296 SDValue Result = TSI->EmitTargetCodeForMemmove(
10297 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10298 SrcPtrInfo);
10299 if (Result.getNode())
10300 return Result;
10301 }
10302
10305
10306 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10307 // not be safe. See memcpy above for more details.
10308
10309 // Emit a library call.
10312 Args.emplace_back(Dst, PtrTy);
10313 Args.emplace_back(Src, PtrTy);
10314 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10315 // FIXME: pass in SDLoc
10317
10318 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10319
10320 bool IsTailCall = false;
10321 if (OverrideTailCall.has_value()) {
10322 IsTailCall = *OverrideTailCall;
10323 } else {
10324 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10325 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10326 }
10327 // Lowering doesn't support tail calling inside a function with a
10328 // swifterror argument yet.
10329 IsTailCall &= !hasSwiftErrorArg();
10330
10331 CLI.setDebugLoc(dl)
10332 .setChain(Chain)
10333 .setLibCallee(
10334 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10335 Dst.getValueType().getTypeForEVT(*getContext()),
10336 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10337 std::move(Args))
10339 .setTailCall(IsTailCall);
10340
10341 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10342 return CallResult.second;
10343}
10344
10346 SDValue Dst, SDValue Src, SDValue Size,
10347 Type *SizeTy, unsigned ElemSz,
10348 bool isTailCall,
10349 MachinePointerInfo DstPtrInfo,
10350 MachinePointerInfo SrcPtrInfo) {
10351 // Lowering doesn't support tail calling inside a function with a
10352 // swifterror argument yet.
10353 isTailCall &= !hasSwiftErrorArg();
10354
10355 // Emit a library call.
10358 Args.emplace_back(Dst, IntPtrTy);
10359 Args.emplace_back(Src, IntPtrTy);
10360 Args.emplace_back(Size, SizeTy);
10361
10362 RTLIB::Libcall LibraryCall =
10364 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10365 if (LibcallImpl == RTLIB::Unsupported)
10366 report_fatal_error("Unsupported element size");
10367
10369 CLI.setDebugLoc(dl)
10370 .setChain(Chain)
10371 .setLibCallee(
10372 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10374 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10375 std::move(Args))
10377 .setTailCall(isTailCall);
10378
10379 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10380 return CallResult.second;
10381}
10382
10384 SDValue Src, SDValue Size, Align Alignment,
10385 bool isVol, bool AlwaysInline,
10386 const CallInst *CI,
10387 MachinePointerInfo DstPtrInfo,
10388 const AAMDNodes &AAInfo) {
10389 // Check to see if we should lower the memset to stores first.
10390 // For cases within the target-specified limits, this is the best choice.
10392 if (ConstantSize) {
10393 // Memset with size zero? Just return the original chain.
10394 if (ConstantSize->isZero())
10395 return Chain;
10396
10397 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10398 ConstantSize->getZExtValue(), Alignment,
10399 isVol, false, DstPtrInfo, AAInfo);
10400
10401 if (Result.getNode())
10402 return Result;
10403 }
10404
10405 // Then check to see if we should lower the memset with target-specific
10406 // code. If the target chooses to do this, this is the next best.
10407 if (TSI) {
10408 SDValue Result = TSI->EmitTargetCodeForMemset(
10409 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10410 if (Result.getNode())
10411 return Result;
10412 }
10413
10414 // If we really need inline code and the target declined to provide it,
10415 // use a (potentially long) sequence of loads and stores.
10416 if (AlwaysInline) {
10417 assert(ConstantSize && "AlwaysInline requires a constant size!");
10418 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10419 ConstantSize->getZExtValue(), Alignment,
10420 isVol, true, DstPtrInfo, AAInfo);
10421 assert(Result &&
10422 "getMemsetStores must return a valid sequence when AlwaysInline");
10423 return Result;
10424 }
10425
10427
10428 // Emit a library call.
10429 auto &Ctx = *getContext();
10430 const auto& DL = getDataLayout();
10431
10433 // FIXME: pass in SDLoc
10434 CLI.setDebugLoc(dl).setChain(Chain);
10435
10436 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10437 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10438
10439 // If zeroing out and bzero is present, use it.
10440 if (UseBZero) {
10442 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10443 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10444 CLI.setLibCallee(
10445 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10446 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10447 } else {
10448 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10449
10451 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10452 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
10453 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10454 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10455 Dst.getValueType().getTypeForEVT(Ctx),
10456 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10457 std::move(Args));
10458 }
10459
10460 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10461 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10462
10463 // If we're going to use bzero, make sure not to tail call unless the
10464 // subsequent return doesn't need a value, as bzero doesn't return the first
10465 // arg unlike memset.
10466 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10467 bool IsTailCall = CI && CI->isTailCall() &&
10469 ReturnsFirstArg && LowersToMemset) &&
10470 // Lowering doesn't support tail calling inside a function
10471 // with a swifterror argument yet.
10473 CLI.setDiscardResult().setTailCall(IsTailCall);
10474
10475 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10476 return CallResult.second;
10477}
10478
10481 Type *SizeTy, unsigned ElemSz,
10482 bool isTailCall,
10483 MachinePointerInfo DstPtrInfo) {
10484 // Lowering doesn't support tail calling inside a function with a
10485 // swifterror argument yet.
10486 isTailCall &= !hasSwiftErrorArg();
10487
10488 // Emit a library call.
10490 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10491 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
10492 Args.emplace_back(Size, SizeTy);
10493
10494 RTLIB::Libcall LibraryCall =
10496 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10497 if (LibcallImpl == RTLIB::Unsupported)
10498 report_fatal_error("Unsupported element size");
10499
10501 CLI.setDebugLoc(dl)
10502 .setChain(Chain)
10503 .setLibCallee(
10504 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10506 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10507 std::move(Args))
10509 .setTailCall(isTailCall);
10510
10511 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10512 return CallResult.second;
10513}
10514
10515SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10517 MachineMemOperand *MMO,
10518 ISD::LoadExtType ExtType) {
10520 AddNodeIDNode(ID, Opcode, VTList, Ops);
10521 ID.AddInteger(MemVT.getRawBits());
10522 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10523 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10524 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10525 ID.AddInteger(MMO->getFlags());
10526 void* IP = nullptr;
10527 if (auto *E = cast_or_null<AtomicSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10528 E->refineAlignment(MMO);
10529 E->refineMMOMetadata(MMO);
10530 return SDValue(E, 0);
10531 }
10532
10533 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10534 VTList, MemVT, MMO, ExtType);
10535 createOperands(N, Ops);
10536
10537 CSEMap.InsertNode(N, IP);
10538 InsertNode(N);
10539 SDValue V(N, 0);
10540 NewSDValueDbgMsg(V, "Creating new node: ", this);
10541 return V;
10542}
10543
10545 EVT MemVT, SDVTList VTs, SDValue Chain,
10546 SDValue Ptr, SDValue Cmp, SDValue Swp,
10547 MachineMemOperand *MMO) {
10548 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10550 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10551
10552 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10553 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10554}
10555
10556SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10557 SDValue Chain, SDValue Ptr, SDValue Val,
10558 MachineMemOperand *MMO) {
10559 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10560 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10561 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10562 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10563 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10564 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10565 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10566 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10567 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10568 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10569 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10570 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10571 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10572 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10573 Opcode == ISD::ATOMIC_STORE) &&
10574 "Invalid Atomic Op");
10575
10576 EVT VT = Val.getValueType();
10577
10578 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10579 getVTList(VT, MVT::Other);
10580 SDValue Ops[] = {Chain, Ptr, Val};
10581 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10582}
10583
10585 EVT MemVT, EVT VT, SDValue Chain,
10586 SDValue Ptr, MachineMemOperand *MMO) {
10587 SDVTList VTs = getVTList(VT, MVT::Other);
10588 SDValue Ops[] = {Chain, Ptr};
10589 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10590}
10591
10592/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10594 if (Ops.size() == 1)
10595 return Ops[0];
10596
10598 VTs.reserve(Ops.size());
10599 for (const SDValue &Op : Ops)
10600 VTs.push_back(Op.getValueType());
10601 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10602}
10603
10605 SDValue Chain, const SDLoc &dl) {
10606 SmallVector<SDValue, 4> RetValues;
10607 RetValues.reserve(ResultTypes.size());
10608 for (EVT VT : ResultTypes)
10609 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10610 return getMergeValues(RetValues, dl);
10611}
10612
10614 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10615 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10617 const AAMDNodes &AAInfo) {
10618 if (Size.hasValue() && !Size.getValue())
10620
10622 MachineMemOperand *MMO =
10623 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10624
10625 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10626}
10627
10629 SDVTList VTList,
10630 ArrayRef<SDValue> Ops, EVT MemVT,
10631 MachineMemOperand *MMO) {
10632 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10633}
10634
10636 SDVTList VTList,
10637 ArrayRef<SDValue> Ops, EVT MemVT,
10639 assert(!MMOs.empty() && "Must have at least one MMO");
10640 assert(
10641 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10642 Opcode == ISD::PREFETCH ||
10643 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10644 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10645 "Opcode is not a memory-accessing opcode!");
10646
10648 if (MMOs.size() == 1) {
10649 MemRefs = MMOs[0];
10650 } else {
10651 // Allocate: [size_t count][MMO*][MMO*]...
10652 size_t AllocSize =
10653 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10654 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10655 size_t *CountPtr = static_cast<size_t *>(Buffer);
10656 *CountPtr = MMOs.size();
10657 MachineMemOperand **Array =
10658 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10659 llvm::copy(MMOs, Array);
10660 MemRefs = Array;
10661 }
10662
10663 // Memoize the node unless it returns a glue result.
10665 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10667 AddNodeIDNode(ID, Opcode, VTList, Ops);
10668 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10669 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10670 ID.AddInteger(MemVT.getRawBits());
10671 for (const MachineMemOperand *MMO : MMOs) {
10672 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10673 ID.AddInteger(MMO->getFlags());
10674 }
10675 void *IP = nullptr;
10676 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10677 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10678 return SDValue(E, 0);
10679 }
10680
10681 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10682 VTList, MemVT, MemRefs);
10683 createOperands(N, Ops);
10684 CSEMap.InsertNode(N, IP);
10685 } else {
10686 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10687 VTList, MemVT, MemRefs);
10688 createOperands(N, Ops);
10689 }
10690 InsertNode(N);
10691 SDValue V(N, 0);
10692 NewSDValueDbgMsg(V, "Creating new node: ", this);
10693 return V;
10694}
10695
10697 SDValue Chain, int FrameIndex) {
10698 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10699 const auto VTs = getVTList(MVT::Other);
10700 SDValue Ops[2] = {
10701 Chain,
10702 getFrameIndex(FrameIndex,
10703 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10704 true)};
10705
10707 AddNodeIDNode(ID, Opcode, VTs, Ops);
10708 ID.AddInteger(FrameIndex);
10709 void *IP = nullptr;
10710 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10711 return SDValue(E, 0);
10712
10713 LifetimeSDNode *N =
10714 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10715 createOperands(N, Ops);
10716 CSEMap.InsertNode(N, IP);
10717 InsertNode(N);
10718 SDValue V(N, 0);
10719 NewSDValueDbgMsg(V, "Creating new node: ", this);
10720 return V;
10721}
10722
10724 uint64_t Guid, uint64_t Index,
10725 uint32_t Attr) {
10726 const unsigned Opcode = ISD::PSEUDO_PROBE;
10727 const auto VTs = getVTList(MVT::Other);
10728 SDValue Ops[] = {Chain};
10730 AddNodeIDNode(ID, Opcode, VTs, Ops);
10731 ID.AddInteger(Guid);
10732 ID.AddInteger(Index);
10733 void *IP = nullptr;
10734 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
10735 return SDValue(E, 0);
10736
10737 auto *N = newSDNode<PseudoProbeSDNode>(
10738 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10739 createOperands(N, Ops);
10740 CSEMap.InsertNode(N, IP);
10741 InsertNode(N);
10742 SDValue V(N, 0);
10743 NewSDValueDbgMsg(V, "Creating new node: ", this);
10744 return V;
10745}
10746
10747/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10748/// MachinePointerInfo record from it. This is particularly useful because the
10749/// code generator has many cases where it doesn't bother passing in a
10750/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10752 SelectionDAG &DAG, SDValue Ptr,
10753 int64_t Offset = 0) {
10754 // If this is FI+Offset, we can model it.
10755 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10757 FI->getIndex(), Offset);
10758
10759 // If this is (FI+Offset1)+Offset2, we can model it.
10760 if (Ptr.getOpcode() != ISD::ADD ||
10763 return Info;
10764
10765 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10767 DAG.getMachineFunction(), FI,
10768 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10769}
10770
10771/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10772/// MachinePointerInfo record from it. This is particularly useful because the
10773/// code generator has many cases where it doesn't bother passing in a
10774/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10776 SelectionDAG &DAG, SDValue Ptr,
10777 SDValue OffsetOp) {
10778 // If the 'Offset' value isn't a constant, we can't handle this.
10780 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10781 if (OffsetOp.isUndef())
10782 return InferPointerInfo(Info, DAG, Ptr);
10783 return Info;
10784}
10785
10787 EVT VT, const SDLoc &dl, SDValue Chain,
10788 SDValue Ptr, SDValue Offset,
10789 MachinePointerInfo PtrInfo, EVT MemVT,
10790 Align Alignment,
10791 MachineMemOperand::Flags MMOFlags,
10792 const MMOMetadata &Metadata) {
10793 assert(Chain.getValueType() == MVT::Other &&
10794 "Invalid chain type");
10795
10796 MMOFlags |= MachineMemOperand::MOLoad;
10797 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10798 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10799 // clients.
10800 if (PtrInfo.V.isNull())
10801 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10802
10803 TypeSize Size = MemVT.getStoreSize();
10805 MachineMemOperand *MMO =
10806 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10807 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10808}
10809
10811 EVT VT, const SDLoc &dl, SDValue Chain,
10812 SDValue Ptr, SDValue Offset, EVT MemVT,
10813 MachineMemOperand *MMO) {
10814 if (VT == MemVT) {
10815 ExtType = ISD::NON_EXTLOAD;
10816 } else if (ExtType == ISD::NON_EXTLOAD) {
10817 assert(VT == MemVT && "Non-extending load from different memory type!");
10818 } else {
10819 // Extending load.
10820 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10821 "Should only be an extending load, not truncating!");
10822 assert(VT.isInteger() == MemVT.isInteger() &&
10823 "Cannot convert from FP to Int or Int -> FP!");
10824 assert(VT.isVector() == MemVT.isVector() &&
10825 "Cannot use an ext load to convert to or from a vector!");
10826 assert((!VT.isVector() ||
10828 "Cannot use an ext load to change the number of vector elements!");
10829 }
10830
10831 assert((!MMO->getRanges() ||
10833 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10834 MemVT.isInteger())) &&
10835 "Range metadata and load type must match!");
10836
10837 bool Indexed = AM != ISD::UNINDEXED;
10838 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10839 "Unindexed load with an offset!");
10840
10841 SDVTList VTs = Indexed ?
10842 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10843 SDValue Ops[] = { Chain, Ptr, Offset };
10845 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
10846 ID.AddInteger(MemVT.getRawBits());
10847 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
10848 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
10849 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10850 ID.AddInteger(MMO->getFlags());
10851 void *IP = nullptr;
10852 if (auto *E = cast_or_null<LoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10853 E->refineAlignment(MMO);
10854 E->refineMMOMetadata(MMO);
10855 return SDValue(E, 0);
10856 }
10857 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10858 ExtType, MemVT, MMO);
10859 createOperands(N, Ops);
10860
10861 CSEMap.InsertNode(N, IP);
10862 InsertNode(N);
10863 SDValue V(N, 0);
10864 NewSDValueDbgMsg(V, "Creating new node: ", this);
10865 return V;
10866}
10867
10869 SDValue Ptr, MachinePointerInfo PtrInfo,
10870 MaybeAlign Alignment,
10871 MachineMemOperand::Flags MMOFlags,
10872 const MMOMetadata &Metadata) {
10874 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10875 PtrInfo, VT, Alignment, MMOFlags, Metadata);
10876}
10877
10879 SDValue Ptr, MachineMemOperand *MMO) {
10881 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10882 VT, MMO);
10883}
10884
10886 EVT VT, SDValue Chain, SDValue Ptr,
10887 MachinePointerInfo PtrInfo, EVT MemVT,
10888 MaybeAlign Alignment,
10889 MachineMemOperand::Flags MMOFlags,
10890 const MMOMetadata &Metadata) {
10892 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
10893 MemVT, Alignment, MMOFlags, Metadata);
10894}
10895
10897 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
10898 MachineMemOperand *MMO) {
10900 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
10901 MemVT, MMO);
10902}
10903
10907 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
10908 assert(LD->getOffset().getOpcode() == ISD::POISON &&
10909 "Load is already a indexed load!");
10910 // Don't propagate the invariant or dereferenceable flags.
10911 auto MMOFlags =
10912 LD->getMemOperand()->getFlags() &
10914 return getLoad(
10915 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
10916 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
10917 MMOFlags,
10918 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
10919}
10920
10922 SDValue Ptr, MachinePointerInfo PtrInfo,
10923 Align Alignment,
10924 MachineMemOperand::Flags MMOFlags,
10925 const MMOMetadata &Metadata) {
10926 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10927
10928 MMOFlags |= MachineMemOperand::MOStore;
10929 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10930 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10931
10932 if (PtrInfo.V.isNull())
10933 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10934
10937 MachineMemOperand *MMO =
10938 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10939 return getStore(Chain, dl, Val, Ptr, MMO);
10940}
10941
10943 SDValue Ptr, MachineMemOperand *MMO) {
10945 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
10947}
10948
10950 SDValue Ptr, SDValue Offset, EVT SVT,
10952 bool IsTruncating) {
10953 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10954 EVT VT = Val.getValueType();
10955 if (VT == SVT) {
10956 IsTruncating = false;
10957 } else if (!IsTruncating) {
10958 assert(VT == SVT && "No-truncating store from different memory type!");
10959 } else {
10961 "Should only be a truncating store, not extending!");
10962 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10963 assert(VT.isVector() == SVT.isVector() &&
10964 "Cannot use trunc store to convert to or from a vector!");
10965 assert((!VT.isVector() ||
10967 "Cannot use trunc store to change the number of vector elements!");
10968 }
10969
10970 bool Indexed = AM != ISD::UNINDEXED;
10971 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10972 "Unindexed store with an offset!");
10973 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10974 : getVTList(MVT::Other);
10975 SDValue Ops[] = {Chain, Val, Ptr, Offset};
10977 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
10978 ID.AddInteger(SVT.getRawBits());
10979 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
10980 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
10981 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10982 ID.AddInteger(MMO->getFlags());
10983 void *IP = nullptr;
10984 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10985 cast<StoreSDNode>(E)->refineAlignment(MMO);
10986 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
10987 return SDValue(E, 0);
10988 }
10989 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10990 IsTruncating, SVT, MMO);
10991 createOperands(N, Ops);
10992
10993 CSEMap.InsertNode(N, IP);
10994 InsertNode(N);
10995 SDValue V(N, 0);
10996 NewSDValueDbgMsg(V, "Creating new node: ", this);
10997 return V;
10998}
10999
11001 SDValue Ptr, SDValue Offset,
11002 MachinePointerInfo PtrInfo, EVT SVT,
11003 Align Alignment,
11004 MachineMemOperand::Flags MMOFlags,
11005 const MMOMetadata &Metadata) {
11006 assert(Chain.getValueType() == MVT::Other &&
11007 "Invalid chain type");
11008
11009 MMOFlags |= MachineMemOperand::MOStore;
11010 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11011 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11012
11013 if (PtrInfo.V.isNull())
11014 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11015
11017 MachineMemOperand *MMO = MF.getMachineMemOperand(
11018 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11019 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11020}
11021
11023 SDValue Ptr, MachinePointerInfo PtrInfo,
11024 EVT SVT, Align Alignment,
11025 MachineMemOperand::Flags MMOFlags,
11026 const MMOMetadata &Metadata) {
11027 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11028 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11029}
11030
11032 SDValue Ptr, SDValue Offset, EVT SVT,
11033 MachineMemOperand *MMO) {
11034 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11035}
11036
11038 SDValue Ptr, EVT SVT,
11039 MachineMemOperand *MMO) {
11040 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11041 ISD::UNINDEXED, true);
11042}
11043
11047 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11048 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11049 "Store is already a indexed store!");
11050 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11051 ST->getMemoryVT(), ST->getMemOperand(), AM,
11052 ST->isTruncatingStore());
11053}
11054
11056 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11057 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11058 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11059 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11060 const MDNode *Ranges, bool IsExpanding) {
11061 MMOFlags |= MachineMemOperand::MOLoad;
11062 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11063 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11064 // clients.
11065 if (PtrInfo.V.isNull())
11066 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11067
11068 TypeSize Size = MemVT.getStoreSize();
11070 MachineMemOperand *MMO = MF.getMachineMemOperand(
11071 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11072 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11073 MMO, IsExpanding);
11074}
11075
11077 ISD::LoadExtType ExtType, EVT VT,
11078 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11079 SDValue Offset, SDValue Mask, SDValue EVL,
11080 EVT MemVT, MachineMemOperand *MMO,
11081 bool IsExpanding) {
11082 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11083 assert(Mask.getValueType().getVectorElementCount() ==
11084 VT.getVectorElementCount() &&
11085 "Vector width mismatch between mask and data");
11086
11087 bool Indexed = AM != ISD::UNINDEXED;
11088 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11089 "Unindexed load with an offset!");
11090
11091 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11092 : getVTList(VT, MVT::Other);
11093 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11095 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
11096 ID.AddInteger(MemVT.getRawBits());
11097 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11098 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11099 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11100 ID.AddInteger(MMO->getFlags());
11101 void *IP = nullptr;
11102 if (auto *E = cast_or_null<VPLoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
11103 E->refineAlignment(MMO);
11104 E->refineMMOMetadata(MMO);
11105 return SDValue(E, 0);
11106 }
11107 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11108 ExtType, IsExpanding, MemVT, MMO);
11109 createOperands(N, Ops);
11110
11111 CSEMap.InsertNode(N, IP);
11112 InsertNode(N);
11113 SDValue V(N, 0);
11114 NewSDValueDbgMsg(V, "Creating new node: ", this);
11115 return V;
11116}
11117
11119 SDValue Ptr, SDValue Mask, SDValue EVL,
11120 MachinePointerInfo PtrInfo,
11121 MaybeAlign Alignment,
11122 MachineMemOperand::Flags MMOFlags,
11123 const AAMDNodes &AAInfo, const MDNode *Ranges,
11124 bool IsExpanding) {
11126 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11127 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11128 IsExpanding);
11129}
11130
11132 SDValue Ptr, SDValue Mask, SDValue EVL,
11133 MachineMemOperand *MMO, bool IsExpanding) {
11135 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11136 Mask, EVL, VT, MMO, IsExpanding);
11137}
11138
11140 EVT VT, SDValue Chain, SDValue Ptr,
11141 SDValue Mask, SDValue EVL,
11142 MachinePointerInfo PtrInfo, EVT MemVT,
11143 MaybeAlign Alignment,
11144 MachineMemOperand::Flags MMOFlags,
11145 const AAMDNodes &AAInfo, bool IsExpanding) {
11147 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11148 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11149 IsExpanding);
11150}
11151
11153 EVT VT, SDValue Chain, SDValue Ptr,
11154 SDValue Mask, SDValue EVL, EVT MemVT,
11155 MachineMemOperand *MMO, bool IsExpanding) {
11157 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11158 EVL, MemVT, MMO, IsExpanding);
11159}
11160
11164 auto *LD = cast<VPLoadSDNode>(OrigLoad);
11165 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11166 "Load is already a indexed load!");
11167 // Don't propagate the invariant or dereferenceable flags.
11168 auto MMOFlags =
11169 LD->getMemOperand()->getFlags() &
11171 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
11172 LD->getChain(), Base, Offset, LD->getMask(),
11173 LD->getVectorLength(), LD->getPointerInfo(),
11174 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
11175 nullptr, LD->isExpandingLoad());
11176}
11177
11179 SDValue Ptr, SDValue Offset, SDValue Mask,
11180 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11181 ISD::MemIndexedMode AM, bool IsTruncating,
11182 bool IsCompressing) {
11183 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11184 assert(Mask.getValueType().getVectorElementCount() ==
11186 "Vector width mismatch between mask and data");
11187
11188 bool Indexed = AM != ISD::UNINDEXED;
11189 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11190 "Unindexed vp_store with an offset!");
11191 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11192 : getVTList(MVT::Other);
11193 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11195 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11196 ID.AddInteger(MemVT.getRawBits());
11197 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11198 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11199 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11200 ID.AddInteger(MMO->getFlags());
11201 void *IP = nullptr;
11202 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11203 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11204 return SDValue(E, 0);
11205 }
11206 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11207 IsTruncating, IsCompressing, MemVT, MMO);
11208 createOperands(N, Ops);
11209
11210 CSEMap.InsertNode(N, IP);
11211 InsertNode(N);
11212 SDValue V(N, 0);
11213 NewSDValueDbgMsg(V, "Creating new node: ", this);
11214 return V;
11215}
11216
11218 SDValue Val, SDValue Ptr, SDValue Mask,
11219 SDValue EVL, MachinePointerInfo PtrInfo,
11220 EVT SVT, Align Alignment,
11221 MachineMemOperand::Flags MMOFlags,
11222 const AAMDNodes &AAInfo,
11223 bool IsCompressing) {
11224 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11225
11226 MMOFlags |= MachineMemOperand::MOStore;
11227 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11228
11229 if (PtrInfo.V.isNull())
11230 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11231
11233 MachineMemOperand *MMO = MF.getMachineMemOperand(
11234 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11235 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11236 IsCompressing);
11237}
11238
11240 SDValue Val, SDValue Ptr, SDValue Mask,
11241 SDValue EVL, EVT SVT,
11242 MachineMemOperand *MMO,
11243 bool IsCompressing) {
11244 EVT VT = Val.getValueType();
11245
11246 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11247 if (VT == SVT)
11248 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11249 EVL, VT, MMO, ISD::UNINDEXED,
11250 /*IsTruncating*/ false, IsCompressing);
11251
11253 "Should only be a truncating store, not extending!");
11254 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11255 assert(VT.isVector() == SVT.isVector() &&
11256 "Cannot use trunc store to convert to or from a vector!");
11257 assert((!VT.isVector() ||
11259 "Cannot use trunc store to change the number of vector elements!");
11260
11261 SDVTList VTs = getVTList(MVT::Other);
11263 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11265 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11266 ID.AddInteger(SVT.getRawBits());
11267 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11268 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11269 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11270 ID.AddInteger(MMO->getFlags());
11271 void *IP = nullptr;
11272 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11273 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11274 return SDValue(E, 0);
11275 }
11276 auto *N =
11277 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11278 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11279 createOperands(N, Ops);
11280
11281 CSEMap.InsertNode(N, IP);
11282 InsertNode(N);
11283 SDValue V(N, 0);
11284 NewSDValueDbgMsg(V, "Creating new node: ", this);
11285 return V;
11286}
11287
11291 auto *ST = cast<VPStoreSDNode>(OrigStore);
11292 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11293 "Store is already an indexed store!");
11294 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
11295 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
11296 Offset, ST->getMask(), ST->getVectorLength()};
11298 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11299 ID.AddInteger(ST->getMemoryVT().getRawBits());
11300 ID.AddInteger(ST->getRawSubclassData());
11301 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
11302 ID.AddInteger(ST->getMemOperand()->getFlags());
11303 void *IP = nullptr;
11304 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11305 return SDValue(E, 0);
11306
11307 auto *N = newSDNode<VPStoreSDNode>(
11308 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
11309 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
11310 createOperands(N, Ops);
11311
11312 CSEMap.InsertNode(N, IP);
11313 InsertNode(N);
11314 SDValue V(N, 0);
11315 NewSDValueDbgMsg(V, "Creating new node: ", this);
11316 return V;
11317}
11318
11320 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11321 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11322 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11323 bool Indexed = AM != ISD::UNINDEXED;
11324 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11325 "Unindexed load with an offset!");
11326
11327 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11328 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11329 : getVTList(VT, MVT::Other);
11331 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11332 ID.AddInteger(VT.getRawBits());
11333 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11334 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11335 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11336
11337 void *IP = nullptr;
11338 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11339 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11340 return SDValue(E, 0);
11341 }
11342
11343 auto *N =
11344 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11345 ExtType, IsExpanding, MemVT, MMO);
11346 createOperands(N, Ops);
11347 CSEMap.InsertNode(N, IP);
11348 InsertNode(N);
11349 SDValue V(N, 0);
11350 NewSDValueDbgMsg(V, "Creating new node: ", this);
11351 return V;
11352}
11353
11355 SDValue Ptr, SDValue Stride,
11356 SDValue Mask, SDValue EVL,
11357 MachineMemOperand *MMO,
11358 bool IsExpanding) {
11360 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11361 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11362}
11363
11365 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11366 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11367 MachineMemOperand *MMO, bool IsExpanding) {
11369 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11370 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11371}
11372
11374 SDValue Val, SDValue Ptr,
11375 SDValue Offset, SDValue Stride,
11376 SDValue Mask, SDValue EVL, EVT MemVT,
11377 MachineMemOperand *MMO,
11379 bool IsTruncating, bool IsCompressing) {
11380 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11381 bool Indexed = AM != ISD::UNINDEXED;
11382 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11383 "Unindexed vp_store with an offset!");
11384 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11385 : getVTList(MVT::Other);
11386 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11388 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11389 ID.AddInteger(MemVT.getRawBits());
11390 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11391 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11392 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11393 void *IP = nullptr;
11394 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11395 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11396 return SDValue(E, 0);
11397 }
11398 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11399 VTs, AM, IsTruncating,
11400 IsCompressing, MemVT, MMO);
11401 createOperands(N, Ops);
11402
11403 CSEMap.InsertNode(N, IP);
11404 InsertNode(N);
11405 SDValue V(N, 0);
11406 NewSDValueDbgMsg(V, "Creating new node: ", this);
11407 return V;
11408}
11409
11411 SDValue Val, SDValue Ptr,
11412 SDValue Stride, SDValue Mask,
11413 SDValue EVL, EVT SVT,
11414 MachineMemOperand *MMO,
11415 bool IsCompressing) {
11416 EVT VT = Val.getValueType();
11417
11418 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11419 if (VT == SVT)
11420 return getStridedStoreVP(Chain, DL, Val, Ptr, getPOISON(Ptr.getValueType()),
11421 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
11422 /*IsTruncating*/ false, IsCompressing);
11423
11425 "Should only be a truncating store, not extending!");
11426 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11427 assert(VT.isVector() == SVT.isVector() &&
11428 "Cannot use trunc store to convert to or from a vector!");
11429 assert((!VT.isVector() ||
11431 "Cannot use trunc store to change the number of vector elements!");
11432
11433 SDVTList VTs = getVTList(MVT::Other);
11435 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
11437 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11438 ID.AddInteger(SVT.getRawBits());
11439 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11440 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11441 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11442 void *IP = nullptr;
11443 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11444 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11445 return SDValue(E, 0);
11446 }
11447 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11448 VTs, ISD::UNINDEXED, true,
11449 IsCompressing, SVT, MMO);
11450 createOperands(N, Ops);
11451
11452 CSEMap.InsertNode(N, IP);
11453 InsertNode(N);
11454 SDValue V(N, 0);
11455 NewSDValueDbgMsg(V, "Creating new node: ", this);
11456 return V;
11457}
11458
11461 ISD::MemIndexType IndexType) {
11462 assert(Ops.size() == 6 && "Incompatible number of operands");
11463
11465 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
11466 ID.AddInteger(VT.getRawBits());
11467 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11468 dl.getIROrder(), VTs, VT, MMO, IndexType));
11469 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11470 ID.AddInteger(MMO->getFlags());
11471 void *IP = nullptr;
11472 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11473 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11474 return SDValue(E, 0);
11475 }
11476
11477 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11478 VT, MMO, IndexType);
11479 createOperands(N, Ops);
11480
11481 assert(N->getMask().getValueType().getVectorElementCount() ==
11482 N->getValueType(0).getVectorElementCount() &&
11483 "Vector width mismatch between mask and data");
11484 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11485 N->getValueType(0).getVectorElementCount().isScalable() &&
11486 "Scalable flags of index and data do not match");
11488 N->getIndex().getValueType().getVectorElementCount(),
11489 N->getValueType(0).getVectorElementCount()) &&
11490 "Vector width mismatch between index and data");
11491 assert(isa<ConstantSDNode>(N->getScale()) &&
11492 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11493 "Scale should be a constant power of 2");
11494
11495 CSEMap.InsertNode(N, IP);
11496 InsertNode(N);
11497 SDValue V(N, 0);
11498 NewSDValueDbgMsg(V, "Creating new node: ", this);
11499 return V;
11500}
11501
11504 MachineMemOperand *MMO,
11505 ISD::MemIndexType IndexType) {
11506 assert(Ops.size() == 7 && "Incompatible number of operands");
11507
11509 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
11510 ID.AddInteger(VT.getRawBits());
11511 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11512 dl.getIROrder(), VTs, VT, MMO, IndexType));
11513 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11514 ID.AddInteger(MMO->getFlags());
11515 void *IP = nullptr;
11516 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11517 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11518 return SDValue(E, 0);
11519 }
11520 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11521 VT, MMO, IndexType);
11522 createOperands(N, Ops);
11523
11524 assert(N->getMask().getValueType().getVectorElementCount() ==
11525 N->getValue().getValueType().getVectorElementCount() &&
11526 "Vector width mismatch between mask and data");
11527 assert(
11528 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11529 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11530 "Scalable flags of index and data do not match");
11532 N->getIndex().getValueType().getVectorElementCount(),
11533 N->getValue().getValueType().getVectorElementCount()) &&
11534 "Vector width mismatch between index and data");
11535 assert(isa<ConstantSDNode>(N->getScale()) &&
11536 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11537 "Scale should be a constant power of 2");
11538
11539 CSEMap.InsertNode(N, IP);
11540 InsertNode(N);
11541 SDValue V(N, 0);
11542 NewSDValueDbgMsg(V, "Creating new node: ", this);
11543 return V;
11544}
11545
11548 SDValue PassThru, EVT MemVT,
11549 MachineMemOperand *MMO,
11551 ISD::LoadExtType ExtTy, bool isExpanding) {
11552 bool Indexed = AM != ISD::UNINDEXED;
11553 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11554 "Unindexed masked load with an offset!");
11555 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11556 : getVTList(VT, MVT::Other);
11557 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11559 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
11560 ID.AddInteger(MemVT.getRawBits());
11561 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11562 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11563 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11564 ID.AddInteger(MMO->getFlags());
11565 void *IP = nullptr;
11566 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11567 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11568 return SDValue(E, 0);
11569 }
11570 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11571 AM, ExtTy, isExpanding, MemVT, MMO);
11572 createOperands(N, Ops);
11573
11574 CSEMap.InsertNode(N, IP);
11575 InsertNode(N);
11576 SDValue V(N, 0);
11577 NewSDValueDbgMsg(V, "Creating new node: ", this);
11578 return V;
11579}
11580
11585 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11586 "Masked load is already a indexed load!");
11587 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11588 Offset, LD->getMask(), LD->getPassThru(),
11589 LD->getMemoryVT(), LD->getMemOperand(), AM,
11590 LD->getExtensionType(), LD->isExpandingLoad());
11591}
11592
11595 SDValue Mask, EVT MemVT,
11596 MachineMemOperand *MMO,
11597 ISD::MemIndexedMode AM, bool IsTruncating,
11598 bool IsCompressing) {
11599 assert(Chain.getValueType() == MVT::Other &&
11600 "Invalid chain type");
11601 bool Indexed = AM != ISD::UNINDEXED;
11602 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11603 "Unindexed masked store with an offset!");
11604 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11605 : getVTList(MVT::Other);
11606 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11608 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
11609 ID.AddInteger(MemVT.getRawBits());
11610 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11611 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11612 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11613 ID.AddInteger(MMO->getFlags());
11614 void *IP = nullptr;
11615 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11616 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11617 return SDValue(E, 0);
11618 }
11619 auto *N =
11620 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11621 IsTruncating, IsCompressing, MemVT, MMO);
11622 createOperands(N, Ops);
11623
11624 CSEMap.InsertNode(N, IP);
11625 InsertNode(N);
11626 SDValue V(N, 0);
11627 NewSDValueDbgMsg(V, "Creating new node: ", this);
11628 return V;
11629}
11630
11635 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11636 "Masked store is already a indexed store!");
11637 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11638 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11639 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11640}
11641
11644 MachineMemOperand *MMO,
11645 ISD::MemIndexType IndexType,
11646 ISD::LoadExtType ExtTy) {
11647 assert(Ops.size() == 6 && "Incompatible number of operands");
11648
11650 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
11651 ID.AddInteger(MemVT.getRawBits());
11652 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11653 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11654 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11655 ID.AddInteger(MMO->getFlags());
11656 void *IP = nullptr;
11657 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11658 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11659 return SDValue(E, 0);
11660 }
11661
11662 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11663 VTs, MemVT, MMO, IndexType, ExtTy);
11664 createOperands(N, Ops);
11665
11666 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11667 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11668 assert(N->getMask().getValueType().getVectorElementCount() ==
11669 N->getValueType(0).getVectorElementCount() &&
11670 "Vector width mismatch between mask and data");
11671 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11672 N->getValueType(0).getVectorElementCount().isScalable() &&
11673 "Scalable flags of index and data do not match");
11675 N->getIndex().getValueType().getVectorElementCount(),
11676 N->getValueType(0).getVectorElementCount()) &&
11677 "Vector width mismatch between index and data");
11678 assert(isa<ConstantSDNode>(N->getScale()) &&
11679 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11680 "Scale should be a constant power of 2");
11681
11682 CSEMap.InsertNode(N, IP);
11683 InsertNode(N);
11684 SDValue V(N, 0);
11685 NewSDValueDbgMsg(V, "Creating new node: ", this);
11686 return V;
11687}
11688
11691 MachineMemOperand *MMO,
11692 ISD::MemIndexType IndexType,
11693 bool IsTrunc) {
11694 assert(Ops.size() == 6 && "Incompatible number of operands");
11695
11697 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
11698 ID.AddInteger(MemVT.getRawBits());
11699 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11700 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11701 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11702 ID.AddInteger(MMO->getFlags());
11703 void *IP = nullptr;
11704 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11705 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11706 return SDValue(E, 0);
11707 }
11708
11709 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11710 VTs, MemVT, MMO, IndexType, IsTrunc);
11711 createOperands(N, Ops);
11712
11713 assert(N->getMask().getValueType().getVectorElementCount() ==
11714 N->getValue().getValueType().getVectorElementCount() &&
11715 "Vector width mismatch between mask and data");
11716 assert(
11717 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11718 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11719 "Scalable flags of index and data do not match");
11721 N->getIndex().getValueType().getVectorElementCount(),
11722 N->getValue().getValueType().getVectorElementCount()) &&
11723 "Vector width mismatch between index and data");
11724 assert(isa<ConstantSDNode>(N->getScale()) &&
11725 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11726 "Scale should be a constant power of 2");
11727
11728 CSEMap.InsertNode(N, IP);
11729 InsertNode(N);
11730 SDValue V(N, 0);
11731 NewSDValueDbgMsg(V, "Creating new node: ", this);
11732 return V;
11733}
11734
11736 const SDLoc &dl, ArrayRef<SDValue> Ops,
11737 MachineMemOperand *MMO,
11738 ISD::MemIndexType IndexType) {
11739 assert(Ops.size() == 7 && "Incompatible number of operands");
11740
11743 ID.AddInteger(MemVT.getRawBits());
11744 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11745 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11746 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11747 ID.AddInteger(MMO->getFlags());
11748 void *IP = nullptr;
11749 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11750 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11751 return SDValue(E, 0);
11752 }
11753
11754 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11755 VTs, MemVT, MMO, IndexType);
11756 createOperands(N, Ops);
11757
11758 assert(N->getMask().getValueType().getVectorElementCount() ==
11759 N->getIndex().getValueType().getVectorElementCount() &&
11760 "Vector width mismatch between mask and data");
11761 assert(isa<ConstantSDNode>(N->getScale()) &&
11762 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11763 "Scale should be a constant power of 2");
11764 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11765
11766 CSEMap.InsertNode(N, IP);
11767 InsertNode(N);
11768 SDValue V(N, 0);
11769 NewSDValueDbgMsg(V, "Creating new node: ", this);
11770 return V;
11771}
11772
11774 SDValue Ptr, SDValue Mask, SDValue EVL,
11775 MachineMemOperand *MMO) {
11776 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11777 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11779 AddNodeIDNode(ID, ISD::VP_LOAD_FF, VTs, Ops);
11780 ID.AddInteger(VT.getRawBits());
11781 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11782 VTs, VT, MMO));
11783 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11784 ID.AddInteger(MMO->getFlags());
11785 void *IP = nullptr;
11786 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11787 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11788 return SDValue(E, 0);
11789 }
11790 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11791 VT, MMO);
11792 createOperands(N, Ops);
11793
11794 CSEMap.InsertNode(N, IP);
11795 InsertNode(N);
11796 SDValue V(N, 0);
11797 NewSDValueDbgMsg(V, "Creating new node: ", this);
11798 return V;
11799}
11800
11802 EVT MemVT, MachineMemOperand *MMO) {
11803 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11804 SDVTList VTs = getVTList(MVT::Other);
11805 SDValue Ops[] = {Chain, Ptr};
11808 ID.AddInteger(MemVT.getRawBits());
11809 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11810 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11811 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11812 ID.AddInteger(MMO->getFlags());
11813 void *IP = nullptr;
11814 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11815 return SDValue(E, 0);
11816
11817 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11818 dl.getDebugLoc(), VTs, MemVT, MMO);
11819 createOperands(N, Ops);
11820
11821 CSEMap.InsertNode(N, IP);
11822 InsertNode(N);
11823 SDValue V(N, 0);
11824 NewSDValueDbgMsg(V, "Creating new node: ", this);
11825 return V;
11826}
11827
11829 EVT MemVT, MachineMemOperand *MMO) {
11830 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11831 SDVTList VTs = getVTList(MVT::Other);
11832 SDValue Ops[] = {Chain, Ptr};
11835 ID.AddInteger(MemVT.getRawBits());
11836 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11837 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11838 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11839 ID.AddInteger(MMO->getFlags());
11840 void *IP = nullptr;
11841 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11842 return SDValue(E, 0);
11843
11844 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11845 dl.getDebugLoc(), VTs, MemVT, MMO);
11846 createOperands(N, Ops);
11847
11848 CSEMap.InsertNode(N, IP);
11849 InsertNode(N);
11850 SDValue V(N, 0);
11851 NewSDValueDbgMsg(V, "Creating new node: ", this);
11852 return V;
11853}
11854
11856 // select undef, T, F --> T (if T is a constant), otherwise F
11857 // select, ?, undef, F --> F
11858 // select, ?, T, undef --> T
11859 if (Cond.isUndef())
11860 return isConstantValueOfAnyType(T) ? T : F;
11861 if (T.isUndef())
11863 if (F.isUndef())
11865
11866 // select true, T, F --> T
11867 // select false, T, F --> F
11868 if (auto C = isBoolConstant(Cond))
11869 return *C ? T : F;
11870
11871 // select ?, T, T --> T
11872 if (T == F)
11873 return T;
11874
11875 return SDValue();
11876}
11877
11879 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11880 if (X.isUndef())
11881 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11882 // shift X, undef --> undef (because it may shift by the bitwidth)
11883 if (Y.isUndef())
11884 return getUNDEF(X.getValueType());
11885
11886 // shift 0, Y --> 0
11887 // shift X, 0 --> X
11889 return X;
11890
11891 // shift X, C >= bitwidth(X) --> undef
11892 // All vector elements must be too big (or undef) to avoid partial undefs.
11893 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11894 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11895 };
11896 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11897 return getUNDEF(X.getValueType());
11898
11899 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11900 if (X.getValueType().getScalarType() == MVT::i1)
11901 return X;
11902
11903 return SDValue();
11904}
11905
11907 SDNodeFlags Flags) {
11908 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11909 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11910 // operation is poison. That result can be relaxed to undef.
11911 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11912 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11913 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11914 (YC && YC->getValueAPF().isNaN());
11915 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11916 (YC && YC->getValueAPF().isInfinity());
11917
11918 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11919 return getUNDEF(X.getValueType());
11920
11921 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11922 return getUNDEF(X.getValueType());
11923
11924 if (!YC)
11925 return SDValue();
11926
11927 // X + -0.0 --> X
11928 if (Opcode == ISD::FADD)
11929 if (YC->getValueAPF().isNegZero())
11930 return X;
11931
11932 // X - +0.0 --> X
11933 if (Opcode == ISD::FSUB)
11934 if (YC->getValueAPF().isPosZero())
11935 return X;
11936
11937 // X * 1.0 --> X
11938 // X / 1.0 --> X
11939 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11940 if (YC->getValueAPF().isOne())
11941 return X;
11942
11943 // X * 0.0 --> 0.0
11944 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11945 if (YC->getValueAPF().isZero())
11946 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11947
11948 return SDValue();
11949}
11950
11952 SDValue Ptr, SDValue SV, unsigned Align) {
11953 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11954 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11955}
11956
11957SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11959 switch (Ops.size()) {
11960 case 0: return getNode(Opcode, DL, VT);
11961 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
11962 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
11963 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
11964 default: break;
11965 }
11966
11967 // Copy from an SDUse array into an SDValue array for use with
11968 // the regular getNode logic.
11970 return getNode(Opcode, DL, VT, NewOps);
11971}
11972
11973SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11975 SDNodeFlags Flags;
11976 if (Inserter)
11977 Flags = Inserter->getFlags();
11978 return getNode(Opcode, DL, VT, Ops, Flags);
11979}
11980
11981SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11982 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11983 unsigned NumOps = Ops.size();
11984 switch (NumOps) {
11985 case 0: return getNode(Opcode, DL, VT);
11986 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
11987 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
11988 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
11989 default: break;
11990 }
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 default: break;
12000 case ISD::BUILD_VECTOR:
12001 // Attempt to simplify BUILD_VECTOR.
12002 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12003 return V;
12004 break;
12006 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12007 return V;
12008 break;
12009 case ISD::SELECT_CC:
12010 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12011 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12012 "LHS and RHS of condition must have same type!");
12013 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12014 "True and False arms of SelectCC must have same type!");
12015 assert(Ops[2].getValueType() == VT &&
12016 "select_cc node must be of same type as true and false value!");
12017 assert((!Ops[0].getValueType().isVector() ||
12018 Ops[0].getValueType().getVectorElementCount() ==
12019 VT.getVectorElementCount()) &&
12020 "Expected select_cc with vector result to have the same sized "
12021 "comparison type!");
12022 break;
12023 case ISD::BR_CC:
12024 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12025 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12026 "LHS/RHS of comparison should match types!");
12027 break;
12028 case ISD::VP_ADD:
12029 case ISD::VP_SUB:
12030 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
12031 if (VT.getScalarType() == MVT::i1)
12032 Opcode = ISD::VP_XOR;
12033 break;
12034 case ISD::VP_MUL:
12035 // If it is VP_MUL mask operation then turn it to VP_AND
12036 if (VT.getScalarType() == MVT::i1)
12037 Opcode = ISD::VP_AND;
12038 break;
12039 case ISD::VP_REDUCE_MUL:
12040 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12041 if (VT == MVT::i1)
12042 Opcode = ISD::VP_REDUCE_AND;
12043 break;
12044 case ISD::VP_REDUCE_ADD:
12045 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12046 if (VT == MVT::i1)
12047 Opcode = ISD::VP_REDUCE_XOR;
12048 break;
12049 case ISD::VP_REDUCE_SMAX:
12050 case ISD::VP_REDUCE_UMIN:
12051 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12052 // VP_REDUCE_AND.
12053 if (VT == MVT::i1)
12054 Opcode = ISD::VP_REDUCE_AND;
12055 break;
12056 case ISD::VP_REDUCE_SMIN:
12057 case ISD::VP_REDUCE_UMAX:
12058 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12059 // VP_REDUCE_OR.
12060 if (VT == MVT::i1)
12061 Opcode = ISD::VP_REDUCE_OR;
12062 break;
12063 }
12064
12065 // Memoize nodes.
12066 SDNode *N;
12067 SDVTList VTs = getVTList(VT);
12068
12069 if (VT != MVT::Glue) {
12071 AddNodeIDNode(ID, Opcode, VTs, Ops);
12072 void *IP = nullptr;
12073
12074 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12075 E->intersectFlagsWith(Flags);
12076 return SDValue(E, 0);
12077 }
12078
12079 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12080 createOperands(N, Ops);
12081
12082 CSEMap.InsertNode(N, IP);
12083 } else {
12084 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12085 createOperands(N, Ops);
12086 }
12087
12088 N->setFlags(Flags);
12089 InsertNode(N);
12090 SDValue V(N, 0);
12091 NewSDValueDbgMsg(V, "Creating new node: ", this);
12092 return V;
12093}
12094
12095SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12096 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12097 SDNodeFlags Flags;
12098 if (Inserter)
12099 Flags = Inserter->getFlags();
12100 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12101}
12102
12103SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12105 const SDNodeFlags Flags) {
12106 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12107}
12108
12109SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12111 SDNodeFlags Flags;
12112 if (Inserter)
12113 Flags = Inserter->getFlags();
12114 return getNode(Opcode, DL, VTList, Ops, Flags);
12115}
12116
12117SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12118 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12119 if (VTList.NumVTs == 1)
12120 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12121
12122#ifndef NDEBUG
12123 for (const auto &Op : Ops)
12124 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12125 "Operand is DELETED_NODE!");
12126#endif
12127
12128 switch (Opcode) {
12129 case ISD::SADDO:
12130 case ISD::UADDO:
12131 case ISD::SSUBO:
12132 case ISD::USUBO: {
12133 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12134 "Invalid add/sub overflow op!");
12135 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12136 Ops[0].getValueType() == Ops[1].getValueType() &&
12137 Ops[0].getValueType() == VTList.VTs[0] &&
12138 "Binary operator types must match!");
12139 SDValue N1 = Ops[0], N2 = Ops[1];
12140 canonicalizeCommutativeBinop(Opcode, N1, N2);
12141
12142 // (X +- 0) -> X with zero-overflow.
12143 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12144 /*AllowTruncation*/ true);
12145 if (N2CV && N2CV->isZero()) {
12146 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12147 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12148 }
12149
12150 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12151 VTList.VTs[1].getScalarType() == MVT::i1) {
12152 SDValue F1 = getFreeze(N1);
12153 SDValue F2 = getFreeze(N2);
12154 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12155 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12156 return getNode(ISD::MERGE_VALUES, DL, VTList,
12157 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12158 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12159 Flags);
12160 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12161 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12162 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12163 return getNode(ISD::MERGE_VALUES, DL, VTList,
12164 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12165 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12166 Flags);
12167 }
12168 }
12169 break;
12170 }
12171 case ISD::SADDO_CARRY:
12172 case ISD::UADDO_CARRY:
12173 case ISD::SSUBO_CARRY:
12174 case ISD::USUBO_CARRY:
12175 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12176 "Invalid add/sub overflow op!");
12177 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12178 Ops[0].getValueType() == Ops[1].getValueType() &&
12179 Ops[0].getValueType() == VTList.VTs[0] &&
12180 Ops[2].getValueType() == VTList.VTs[1] &&
12181 "Binary operator types must match!");
12182 break;
12183 case ISD::SMUL_LOHI:
12184 case ISD::UMUL_LOHI: {
12185 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12186 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12187 VTList.VTs[0] == Ops[0].getValueType() &&
12188 VTList.VTs[0] == Ops[1].getValueType() &&
12189 "Binary operator types must match!");
12190 // Constant fold.
12193 if (LHS && RHS) {
12194 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12195 unsigned OutWidth = Width * 2;
12196 APInt Val = LHS->getAPIntValue();
12197 APInt Mul = RHS->getAPIntValue();
12198 if (Opcode == ISD::SMUL_LOHI) {
12199 Val = Val.sext(OutWidth);
12200 Mul = Mul.sext(OutWidth);
12201 } else {
12202 Val = Val.zext(OutWidth);
12203 Mul = Mul.zext(OutWidth);
12204 }
12205 Val *= Mul;
12206
12207 SDValue Hi =
12208 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12209 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12210 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12211 }
12212 break;
12213 }
12214 case ISD::FFREXP: {
12215 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12216 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12217 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12218
12220 int FrexpExp;
12221 APFloat FrexpMant =
12222 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12223 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12224 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12225 DL, VTList.VTs[1]);
12226 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12227 }
12228
12229 break;
12230 }
12232 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12233 "Invalid STRICT_FP_EXTEND!");
12234 assert(VTList.VTs[0].isFloatingPoint() &&
12235 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12236 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12237 "STRICT_FP_EXTEND result type should be vector iff the operand "
12238 "type is vector!");
12239 assert((!VTList.VTs[0].isVector() ||
12240 VTList.VTs[0].getVectorElementCount() ==
12241 Ops[1].getValueType().getVectorElementCount()) &&
12242 "Vector element count mismatch!");
12243 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12244 "Invalid fpext node, dst <= src!");
12245 break;
12247 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12248 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12249 "STRICT_FP_ROUND result type should be vector iff the operand "
12250 "type is vector!");
12251 assert((!VTList.VTs[0].isVector() ||
12252 VTList.VTs[0].getVectorElementCount() ==
12253 Ops[1].getValueType().getVectorElementCount()) &&
12254 "Vector element count mismatch!");
12255 assert(VTList.VTs[0].isFloatingPoint() &&
12256 Ops[1].getValueType().isFloatingPoint() &&
12257 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12258 Ops[2].getOpcode() == ISD::TargetConstant &&
12259 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12260 "Invalid STRICT_FP_ROUND!");
12261 break;
12262 }
12263
12264 // Memoize the node unless it returns a glue result.
12265 SDNode *N;
12266 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12268 AddNodeIDNode(ID, Opcode, VTList, Ops);
12269 void *IP = nullptr;
12270 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12271 E->intersectFlagsWith(Flags);
12272 return SDValue(E, 0);
12273 }
12274
12275 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12276 createOperands(N, Ops);
12277 CSEMap.InsertNode(N, IP);
12278 } else {
12279 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12280 createOperands(N, Ops);
12281 }
12282
12283 N->setFlags(Flags);
12284 InsertNode(N);
12285 SDValue V(N, 0);
12286 NewSDValueDbgMsg(V, "Creating new node: ", this);
12287 return V;
12288}
12289
12290SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12291 SDVTList VTList) {
12292 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12293}
12294
12295SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12296 SDValue N1) {
12297 SDValue Ops[] = { N1 };
12298 return getNode(Opcode, DL, VTList, Ops);
12299}
12300
12301SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12302 SDValue N1, SDValue N2) {
12303 SDValue Ops[] = { N1, N2 };
12304 return getNode(Opcode, DL, VTList, Ops);
12305}
12306
12307SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12308 SDValue N1, SDValue N2, SDValue N3) {
12309 SDValue Ops[] = { N1, N2, N3 };
12310 return getNode(Opcode, DL, VTList, Ops);
12311}
12312
12313SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12314 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12315 SDValue Ops[] = { N1, N2, N3, N4 };
12316 return getNode(Opcode, DL, VTList, Ops);
12317}
12318
12319SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12320 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12321 SDValue N5) {
12322 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12323 return getNode(Opcode, DL, VTList, Ops);
12324}
12325
12327 if (!VT.isExtended())
12328 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12329
12330 return makeVTList(&(*EVTs.insert(VT).first), 1);
12331}
12332
12335 ID.AddInteger(2U);
12336 ID.AddInteger(VT1.getRawBits());
12337 ID.AddInteger(VT2.getRawBits());
12338
12339 void *IP = nullptr;
12340 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12341 if (!Result) {
12342 EVT *Array = Allocator.Allocate<EVT>(2);
12343 Array[0] = VT1;
12344 Array[1] = VT2;
12345 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
12346 VTListMap.InsertNode(Result, IP);
12347 }
12348 return Result->getSDVTList();
12349}
12350
12353 ID.AddInteger(3U);
12354 ID.AddInteger(VT1.getRawBits());
12355 ID.AddInteger(VT2.getRawBits());
12356 ID.AddInteger(VT3.getRawBits());
12357
12358 void *IP = nullptr;
12359 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12360 if (!Result) {
12361 EVT *Array = Allocator.Allocate<EVT>(3);
12362 Array[0] = VT1;
12363 Array[1] = VT2;
12364 Array[2] = VT3;
12365 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
12366 VTListMap.InsertNode(Result, IP);
12367 }
12368 return Result->getSDVTList();
12369}
12370
12373 ID.AddInteger(4U);
12374 ID.AddInteger(VT1.getRawBits());
12375 ID.AddInteger(VT2.getRawBits());
12376 ID.AddInteger(VT3.getRawBits());
12377 ID.AddInteger(VT4.getRawBits());
12378
12379 void *IP = nullptr;
12380 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12381 if (!Result) {
12382 EVT *Array = Allocator.Allocate<EVT>(4);
12383 Array[0] = VT1;
12384 Array[1] = VT2;
12385 Array[2] = VT3;
12386 Array[3] = VT4;
12387 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
12388 VTListMap.InsertNode(Result, IP);
12389 }
12390 return Result->getSDVTList();
12391}
12392
12394 unsigned NumVTs = VTs.size();
12396 ID.AddInteger(NumVTs);
12397 for (unsigned index = 0; index < NumVTs; index++) {
12398 ID.AddInteger(VTs[index].getRawBits());
12399 }
12400
12401 void *IP = nullptr;
12402 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12403 if (!Result) {
12404 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
12405 llvm::copy(VTs, Array);
12406 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
12407 VTListMap.InsertNode(Result, IP);
12408 }
12409 return Result->getSDVTList();
12410}
12411
12412
12413/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12414/// specified operands. If the resultant node already exists in the DAG,
12415/// this does not modify the specified node, instead it returns the node that
12416/// already exists. If the resultant node does not exist in the DAG, the
12417/// input node is returned. As a degenerate case, if you specify the same
12418/// input operands as the node already has, the input node is returned.
12420 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12421
12422 // Check to see if there is no change.
12423 if (Op == N->getOperand(0)) return N;
12424
12425 // See if the modified node already exists.
12426 void *InsertPos = nullptr;
12427 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
12428 return Existing;
12429
12430 // Nope it doesn't. Remove the node from its current place in the maps.
12431 if (InsertPos)
12432 if (!RemoveNodeFromCSEMaps(N))
12433 InsertPos = nullptr;
12434
12435 // Now we update the operands.
12436 N->OperandList[0].set(Op);
12437
12439 // If this gets put into a CSE map, add it.
12440 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12441 return N;
12442}
12443
12445 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12446
12447 // Check to see if there is no change.
12448 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12449 return N; // No operands changed, just return the input node.
12450
12451 // See if the modified node already exists.
12452 void *InsertPos = nullptr;
12453 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
12454 return Existing;
12455
12456 // Nope it doesn't. Remove the node from its current place in the maps.
12457 if (InsertPos)
12458 if (!RemoveNodeFromCSEMaps(N))
12459 InsertPos = nullptr;
12460
12461 // Now we update the operands.
12462 if (N->OperandList[0] != Op1)
12463 N->OperandList[0].set(Op1);
12464 if (N->OperandList[1] != Op2)
12465 N->OperandList[1].set(Op2);
12466
12468 // If this gets put into a CSE map, add it.
12469 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12470 return N;
12471}
12472
12475 SDValue Ops[] = { Op1, Op2, Op3 };
12476 return UpdateNodeOperands(N, Ops);
12477}
12478
12481 SDValue Op3, SDValue Op4) {
12482 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12483 return UpdateNodeOperands(N, Ops);
12484}
12485
12488 SDValue Op3, SDValue Op4, SDValue Op5) {
12489 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12490 return UpdateNodeOperands(N, Ops);
12491}
12492
12495 unsigned NumOps = Ops.size();
12496 assert(N->getNumOperands() == NumOps &&
12497 "Update with wrong number of operands");
12498
12499 // If no operands changed just return the input node.
12500 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12501 return N;
12502
12503 // See if the modified node already exists.
12504 void *InsertPos = nullptr;
12505 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
12506 return Existing;
12507
12508 // Nope it doesn't. Remove the node from its current place in the maps.
12509 if (InsertPos)
12510 if (!RemoveNodeFromCSEMaps(N))
12511 InsertPos = nullptr;
12512
12513 // Now we update the operands.
12514 for (unsigned i = 0; i != NumOps; ++i)
12515 if (N->OperandList[i] != Ops[i])
12516 N->OperandList[i].set(Ops[i]);
12517
12519 // If this gets put into a CSE map, add it.
12520 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12521 return N;
12522}
12523
12524/// DropOperands - Release the operands and set this node to have
12525/// zero operands.
12527 // Unlike the code in MorphNodeTo that does this, we don't need to
12528 // watch for dead nodes here.
12529 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12530 SDUse &Use = *I++;
12531 Use.set(SDValue());
12532 }
12533}
12534
12536 ArrayRef<MachineMemOperand *> NewMemRefs) {
12537 if (NewMemRefs.empty()) {
12538 N->clearMemRefs();
12539 return;
12540 }
12541
12542 // Check if we can avoid allocating by storing a single reference directly.
12543 if (NewMemRefs.size() == 1) {
12544 N->MemRefs = NewMemRefs[0];
12545 N->NumMemRefs = 1;
12546 return;
12547 }
12548
12549 MachineMemOperand **MemRefsBuffer =
12550 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12551 llvm::copy(NewMemRefs, MemRefsBuffer);
12552 N->MemRefs = MemRefsBuffer;
12553 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12554}
12555
12556/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12557/// machine opcode.
12558///
12560 EVT VT) {
12561 SDVTList VTs = getVTList(VT);
12562 return SelectNodeTo(N, MachineOpc, VTs, {});
12563}
12564
12566 EVT VT, SDValue Op1) {
12567 SDVTList VTs = getVTList(VT);
12568 SDValue Ops[] = { Op1 };
12569 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12570}
12571
12573 EVT VT, SDValue Op1,
12574 SDValue Op2) {
12575 SDVTList VTs = getVTList(VT);
12576 SDValue Ops[] = { Op1, Op2 };
12577 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12578}
12579
12581 EVT VT, SDValue Op1,
12582 SDValue Op2, SDValue Op3) {
12583 SDVTList VTs = getVTList(VT);
12584 SDValue Ops[] = { Op1, Op2, Op3 };
12585 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12586}
12587
12590 SDVTList VTs = getVTList(VT);
12591 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12592}
12593
12595 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12596 SDVTList VTs = getVTList(VT1, VT2);
12597 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12598}
12599
12601 EVT VT1, EVT VT2) {
12602 SDVTList VTs = getVTList(VT1, VT2);
12603 return SelectNodeTo(N, MachineOpc, VTs, {});
12604}
12605
12607 EVT VT1, EVT VT2, EVT VT3,
12609 SDVTList VTs = getVTList(VT1, VT2, VT3);
12610 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12611}
12612
12614 EVT VT1, EVT VT2,
12615 SDValue Op1, SDValue Op2) {
12616 SDVTList VTs = getVTList(VT1, VT2);
12617 SDValue Ops[] = { Op1, Op2 };
12618 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12619}
12620
12623 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12624 // Reset the NodeID to -1.
12625 New->setNodeId(-1);
12626 if (New != N) {
12627 ReplaceAllUsesWith(N, New);
12629 }
12630 return New;
12631}
12632
12633/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12634/// the line number information on the merged node since it is not possible to
12635/// preserve the information that operation is associated with multiple lines.
12636/// This will make the debugger working better at -O0, were there is a higher
12637/// probability having other instructions associated with that line.
12638///
12639/// For IROrder, we keep the smaller of the two
12640SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12641 DebugLoc NLoc = N->getDebugLoc();
12642 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12643 N->setDebugLoc(DebugLoc());
12644 }
12645 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12646 N->setIROrder(Order);
12647 return N;
12648}
12649
12650/// MorphNodeTo - This *mutates* the specified node to have the specified
12651/// return type, opcode, and operands.
12652///
12653/// Note that MorphNodeTo returns the resultant node. If there is already a
12654/// node of the specified opcode and operands, it returns that node instead of
12655/// the current one. Note that the SDLoc need not be the same.
12656///
12657/// Using MorphNodeTo is faster than creating a new node and swapping it in
12658/// with ReplaceAllUsesWith both because it often avoids allocating a new
12659/// node, and because it doesn't require CSE recalculation for any of
12660/// the node's users.
12661///
12662/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12663/// As a consequence it isn't appropriate to use from within the DAG combiner or
12664/// the legalizer which maintain worklists that would need to be updated when
12665/// deleting things.
12668 // If an identical node already exists, use it.
12669 void *IP = nullptr;
12670 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12672 AddNodeIDNode(ID, Opc, VTs, Ops);
12673 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
12674 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12675 }
12676
12677 if (!RemoveNodeFromCSEMaps(N))
12678 IP = nullptr;
12679
12680 // Start the morphing.
12681 N->NodeType = Opc;
12682 N->ValueList = VTs.VTs;
12683 N->NumValues = VTs.NumVTs;
12684
12685 // Clear the operands list, updating used nodes to remove this from their
12686 // use list. Keep track of any operands that become dead as a result.
12687 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12688 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12689 SDUse &Use = *I++;
12690 SDNode *Used = Use.getNode();
12691 Use.set(SDValue());
12692 if (Used->use_empty())
12693 DeadNodeSet.insert(Used);
12694 }
12695
12696 // For MachineNode, initialize the memory references information.
12698 MN->clearMemRefs();
12699
12700 // Swap for an appropriately sized array from the recycler.
12701 removeOperands(N);
12702 createOperands(N, Ops);
12703
12704 // Delete any nodes that are still dead after adding the uses for the
12705 // new operands.
12706 if (!DeadNodeSet.empty()) {
12707 SmallVector<SDNode *, 16> DeadNodes;
12708 for (SDNode *N : DeadNodeSet)
12709 if (N->use_empty())
12710 DeadNodes.push_back(N);
12711 RemoveDeadNodes(DeadNodes);
12712 }
12713
12714 if (IP)
12715 CSEMap.InsertNode(N, IP); // Memoize the new node.
12716 return N;
12717}
12718
12720 unsigned OrigOpc = Node->getOpcode();
12721 unsigned NewOpc;
12722 switch (OrigOpc) {
12723 default:
12724 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12725#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12726 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12727#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12728 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12729#include "llvm/IR/ConstrainedOps.def"
12730 }
12731
12732 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12733
12734 // We're taking this node out of the chain, so we need to re-link things.
12735 SDValue InputChain = Node->getOperand(0);
12736 SDValue OutputChain = SDValue(Node, 1);
12737 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12738
12740 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12741 Ops.push_back(Node->getOperand(i));
12742
12743 SDVTList VTs = getVTList(Node->getValueType(0));
12744 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12745
12746 // MorphNodeTo can operate in two ways: if an existing node with the
12747 // specified operands exists, it can just return it. Otherwise, it
12748 // updates the node in place to have the requested operands.
12749 if (Res == Node) {
12750 // If we updated the node in place, reset the node ID. To the isel,
12751 // this should be just like a newly allocated machine node.
12752 Res->setNodeId(-1);
12753 } else {
12756 }
12757
12758 return Res;
12759}
12760
12761/// getMachineNode - These are used for target selectors to create a new node
12762/// with specified return type(s), MachineInstr opcode, and operands.
12763///
12764/// Note that getMachineNode returns the resultant node. If there is already a
12765/// node of the specified opcode and operands, it returns that node instead of
12766/// the current one.
12768 EVT VT) {
12769 SDVTList VTs = getVTList(VT);
12770 return getMachineNode(Opcode, dl, VTs, {});
12771}
12772
12774 EVT VT, SDValue Op1) {
12775 SDVTList VTs = getVTList(VT);
12776 SDValue Ops[] = { Op1 };
12777 return getMachineNode(Opcode, dl, VTs, Ops);
12778}
12779
12781 EVT VT, SDValue Op1, SDValue Op2) {
12782 SDVTList VTs = getVTList(VT);
12783 SDValue Ops[] = { Op1, Op2 };
12784 return getMachineNode(Opcode, dl, VTs, Ops);
12785}
12786
12788 EVT VT, SDValue Op1, SDValue Op2,
12789 SDValue Op3) {
12790 SDVTList VTs = getVTList(VT);
12791 SDValue Ops[] = { Op1, Op2, Op3 };
12792 return getMachineNode(Opcode, dl, VTs, Ops);
12793}
12794
12797 SDVTList VTs = getVTList(VT);
12798 return getMachineNode(Opcode, dl, VTs, Ops);
12799}
12800
12802 EVT VT1, EVT VT2, SDValue Op1,
12803 SDValue Op2) {
12804 SDVTList VTs = getVTList(VT1, VT2);
12805 SDValue Ops[] = { Op1, Op2 };
12806 return getMachineNode(Opcode, dl, VTs, Ops);
12807}
12808
12810 EVT VT1, EVT VT2, SDValue Op1,
12811 SDValue Op2, SDValue Op3) {
12812 SDVTList VTs = getVTList(VT1, VT2);
12813 SDValue Ops[] = { Op1, Op2, Op3 };
12814 return getMachineNode(Opcode, dl, VTs, Ops);
12815}
12816
12818 EVT VT1, EVT VT2,
12820 SDVTList VTs = getVTList(VT1, VT2);
12821 return getMachineNode(Opcode, dl, VTs, Ops);
12822}
12823
12825 EVT VT1, EVT VT2, EVT VT3,
12826 SDValue Op1, SDValue Op2) {
12827 SDVTList VTs = getVTList(VT1, VT2, VT3);
12828 SDValue Ops[] = { Op1, Op2 };
12829 return getMachineNode(Opcode, dl, VTs, Ops);
12830}
12831
12833 EVT VT1, EVT VT2, EVT VT3,
12834 SDValue Op1, SDValue Op2,
12835 SDValue Op3) {
12836 SDVTList VTs = getVTList(VT1, VT2, VT3);
12837 SDValue Ops[] = { Op1, Op2, Op3 };
12838 return getMachineNode(Opcode, dl, VTs, Ops);
12839}
12840
12842 EVT VT1, EVT VT2, EVT VT3,
12844 SDVTList VTs = getVTList(VT1, VT2, VT3);
12845 return getMachineNode(Opcode, dl, VTs, Ops);
12846}
12847
12849 ArrayRef<EVT> ResultTys,
12851 SDVTList VTs = getVTList(ResultTys);
12852 return getMachineNode(Opcode, dl, VTs, Ops);
12853}
12854
12856 SDVTList VTs,
12858 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12860 void *IP = nullptr;
12861
12862 if (DoCSE) {
12864 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
12865 IP = nullptr;
12866 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12867 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12868 }
12869 }
12870
12871 // Allocate a new MachineSDNode.
12872 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12873 createOperands(N, Ops);
12874
12875 if (DoCSE)
12876 CSEMap.InsertNode(N, IP);
12877
12878 InsertNode(N);
12879 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12880 return N;
12881}
12882
12883/// getTargetExtractSubreg - A convenience function for creating
12884/// TargetOpcode::EXTRACT_SUBREG nodes.
12886 SDValue Operand) {
12887 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12888 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12889 VT, Operand, SRIdxVal);
12890 return SDValue(Subreg, 0);
12891}
12892
12893/// getTargetInsertSubreg - A convenience function for creating
12894/// TargetOpcode::INSERT_SUBREG nodes.
12896 SDValue Operand, SDValue Subreg) {
12897 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12898 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12899 VT, Operand, Subreg, SRIdxVal);
12900 return SDValue(Result, 0);
12901}
12902
12903/// getNodeIfExists - Get the specified node if it's already available, or
12904/// else return NULL.
12907 bool AllowCommute) {
12908 SDNodeFlags Flags;
12909 if (Inserter)
12910 Flags = Inserter->getFlags();
12911 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12912}
12913
12916 const SDNodeFlags Flags,
12917 bool AllowCommute) {
12918 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12919 return nullptr;
12920
12921 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12923 AddNodeIDNode(ID, Opcode, VTList, LookupOps);
12924 void *IP = nullptr;
12925 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) {
12926 E->intersectFlagsWith(Flags);
12927 return E;
12928 }
12929 return nullptr;
12930 };
12931
12932 if (SDNode *Existing = Lookup(Ops))
12933 return Existing;
12934
12935 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12936 return Lookup({Ops[1], Ops[0]});
12937
12938 return nullptr;
12939}
12940
12941/// doesNodeExist - Check if a node exists without modifying its flags.
12942bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12944 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12946 AddNodeIDNode(ID, Opcode, VTList, Ops);
12947 void *IP = nullptr;
12948 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
12949 return true;
12950 }
12951 return false;
12952}
12953
12954/// getDbgValue - Creates a SDDbgValue node.
12955///
12956/// SDNode
12958 SDNode *N, unsigned R, bool IsIndirect,
12959 const DebugLoc &DL, unsigned O) {
12960 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12961 "Expected inlined-at fields to agree");
12962 return new (DbgInfo->getAlloc())
12963 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12964 {}, IsIndirect, DL, O,
12965 /*IsVariadic=*/false);
12966}
12967
12968/// Constant
12970 DIExpression *Expr,
12971 const Value *C,
12972 const DebugLoc &DL, unsigned O) {
12973 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12974 "Expected inlined-at fields to agree");
12975 return new (DbgInfo->getAlloc())
12976 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12977 /*IsIndirect=*/false, DL, O,
12978 /*IsVariadic=*/false);
12979}
12980
12981/// FrameIndex
12983 DIExpression *Expr, unsigned FI,
12984 bool IsIndirect,
12985 const DebugLoc &DL,
12986 unsigned O) {
12987 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12988 "Expected inlined-at fields to agree");
12989 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12990}
12991
12992/// FrameIndex with dependencies
12994 DIExpression *Expr, unsigned FI,
12995 ArrayRef<SDNode *> Dependencies,
12996 bool IsIndirect,
12997 const DebugLoc &DL,
12998 unsigned O) {
12999 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13000 "Expected inlined-at fields to agree");
13001 return new (DbgInfo->getAlloc())
13002 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
13003 Dependencies, IsIndirect, DL, O,
13004 /*IsVariadic=*/false);
13005}
13006
13007/// VReg
13009 Register VReg, bool IsIndirect,
13010 const DebugLoc &DL, unsigned O) {
13011 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13012 "Expected inlined-at fields to agree");
13013 return new (DbgInfo->getAlloc())
13014 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
13015 {}, IsIndirect, DL, O,
13016 /*IsVariadic=*/false);
13017}
13018
13021 ArrayRef<SDNode *> Dependencies,
13022 bool IsIndirect, const DebugLoc &DL,
13023 unsigned O, bool IsVariadic) {
13024 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13025 "Expected inlined-at fields to agree");
13026 return new (DbgInfo->getAlloc())
13027 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13028 DL, O, IsVariadic);
13029}
13030
13032 unsigned OffsetInBits, unsigned SizeInBits,
13033 bool InvalidateDbg) {
13034 SDNode *FromNode = From.getNode();
13035 SDNode *ToNode = To.getNode();
13036 assert(FromNode && ToNode && "Can't modify dbg values");
13037
13038 // PR35338
13039 // TODO: assert(From != To && "Redundant dbg value transfer");
13040 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13041 if (From == To || FromNode == ToNode)
13042 return;
13043
13044 if (!FromNode->getHasDebugValue())
13045 return;
13046
13047 SDDbgOperand FromLocOp =
13048 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13050
13052 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13053 if (Dbg->isInvalidated())
13054 continue;
13055
13056 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13057
13058 // Create a new location ops vector that is equal to the old vector, but
13059 // with each instance of FromLocOp replaced with ToLocOp.
13060 bool Changed = false;
13061 auto NewLocOps = Dbg->copyLocationOps();
13062 std::replace_if(
13063 NewLocOps.begin(), NewLocOps.end(),
13064 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13065 bool Match = Op == FromLocOp;
13066 Changed |= Match;
13067 return Match;
13068 },
13069 ToLocOp);
13070 // Ignore this SDDbgValue if we didn't find a matching location.
13071 if (!Changed)
13072 continue;
13073
13074 DIVariable *Var = Dbg->getVariable();
13075 auto *Expr = Dbg->getExpression();
13076 // If a fragment is requested, update the expression.
13077 if (SizeInBits) {
13078 // When splitting a larger (e.g., sign-extended) value whose
13079 // lower bits are described with an SDDbgValue, do not attempt
13080 // to transfer the SDDbgValue to the upper bits.
13081 if (auto FI = Expr->getFragmentInfo())
13082 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13083 continue;
13084 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13085 SizeInBits);
13086 if (!Fragment)
13087 continue;
13088 Expr = *Fragment;
13089 }
13090
13091 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13092 // Clone the SDDbgValue and move it to To.
13093 SDDbgValue *Clone = getDbgValueList(
13094 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13095 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13096 Dbg->isVariadic());
13097 ClonedDVs.push_back(Clone);
13098
13099 if (InvalidateDbg) {
13100 // Invalidate value and indicate the SDDbgValue should not be emitted.
13101 Dbg->setIsInvalidated();
13102 Dbg->setIsEmitted();
13103 }
13104 }
13105
13106 for (SDDbgValue *Dbg : ClonedDVs) {
13107 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13108 "Transferred DbgValues should depend on the new SDNode");
13109 AddDbgValue(Dbg, false);
13110 }
13111}
13112
13114 if (!N.getHasDebugValue())
13115 return;
13116
13117 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13118 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13119 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13120 return SDDbgOperand::fromNode(Node, ResNo);
13121 };
13122
13124 for (auto *DV : GetDbgValues(&N)) {
13125 if (DV->isInvalidated())
13126 continue;
13127 switch (N.getOpcode()) {
13128 default:
13129 break;
13130 case ISD::ADD: {
13131 SDValue N0 = N.getOperand(0);
13132 SDValue N1 = N.getOperand(1);
13133 if (!isa<ConstantSDNode>(N0)) {
13134 bool RHSConstant = isa<ConstantSDNode>(N1);
13136 if (RHSConstant)
13137 Offset = N.getConstantOperandVal(1);
13138 // We are not allowed to turn indirect debug values variadic, so
13139 // don't salvage those.
13140 if (!RHSConstant && DV->isIndirect())
13141 continue;
13142
13143 // Rewrite an ADD constant node into a DIExpression. Since we are
13144 // performing arithmetic to compute the variable's *value* in the
13145 // DIExpression, we need to mark the expression with a
13146 // DW_OP_stack_value.
13147 auto *DIExpr = DV->getExpression();
13148 auto NewLocOps = DV->copyLocationOps();
13149 bool Changed = false;
13150 size_t OrigLocOpsSize = NewLocOps.size();
13151 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13152 // We're not given a ResNo to compare against because the whole
13153 // node is going away. We know that any ISD::ADD only has one
13154 // result, so we can assume any node match is using the result.
13155 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13156 NewLocOps[i].getSDNode() != &N)
13157 continue;
13158 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13159 if (RHSConstant) {
13162 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13163 } else {
13164 // Convert to a variadic expression (if not already).
13165 // convertToVariadicExpression() returns a const pointer, so we use
13166 // a temporary const variable here.
13167 const auto *TmpDIExpr =
13171 ExprOps.push_back(NewLocOps.size());
13172 ExprOps.push_back(dwarf::DW_OP_plus);
13173 SDDbgOperand RHS =
13175 NewLocOps.push_back(RHS);
13176 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13177 }
13178 Changed = true;
13179 }
13180 (void)Changed;
13181 assert(Changed && "Salvage target doesn't use N");
13182
13183 bool IsVariadic =
13184 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13185
13186 auto AdditionalDependencies = DV->getAdditionalDependencies();
13187 SDDbgValue *Clone = getDbgValueList(
13188 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13189 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13190 ClonedDVs.push_back(Clone);
13191 DV->setIsInvalidated();
13192 DV->setIsEmitted();
13193 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13194 N0.getNode()->dumprFull(this);
13195 dbgs() << " into " << *DIExpr << '\n');
13196 }
13197 break;
13198 }
13199 case ISD::TRUNCATE: {
13200 SDValue N0 = N.getOperand(0);
13201 TypeSize FromSize = N0.getValueSizeInBits();
13202 TypeSize ToSize = N.getValueSizeInBits(0);
13203
13204 DIExpression *DbgExpression = DV->getExpression();
13205 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13206 auto NewLocOps = DV->copyLocationOps();
13207 bool Changed = false;
13208 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13209 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13210 NewLocOps[i].getSDNode() != &N)
13211 continue;
13212
13213 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13214 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13215 Changed = true;
13216 }
13217 assert(Changed && "Salvage target doesn't use N");
13218 (void)Changed;
13219
13220 SDDbgValue *Clone =
13221 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13222 DV->getAdditionalDependencies(), DV->isIndirect(),
13223 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13224
13225 ClonedDVs.push_back(Clone);
13226 DV->setIsInvalidated();
13227 DV->setIsEmitted();
13228 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13229 dbgs() << " into " << *DbgExpression << '\n');
13230 break;
13231 }
13232 }
13233 }
13234
13235 for (SDDbgValue *Dbg : ClonedDVs) {
13236 assert((!Dbg->getSDNodes().empty() ||
13237 llvm::any_of(Dbg->getLocationOps(),
13238 [&](const SDDbgOperand &Op) {
13239 return Op.getKind() == SDDbgOperand::FRAMEIX;
13240 })) &&
13241 "Salvaged DbgValue should depend on a new SDNode");
13242 AddDbgValue(Dbg, false);
13243 }
13244}
13245
13246/// Creates a SDDbgLabel node.
13248 const DebugLoc &DL, unsigned O) {
13249 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13250 "Expected inlined-at fields to agree");
13251 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13252}
13253
13254namespace {
13255
13256/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13257/// pointed to by a use iterator is deleted, increment the use iterator
13258/// so that it doesn't dangle.
13259///
13260class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13263
13264 void NodeDeleted(SDNode *N, SDNode *E) override {
13265 // Increment the iterator as needed.
13266 while (UI != UE && N == UI->getUser())
13267 ++UI;
13268 }
13269
13270public:
13271 RAUWUpdateListener(SelectionDAG &d,
13274 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13275};
13276
13277} // end anonymous namespace
13278
13279/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13280/// This can cause recursive merging of nodes in the DAG.
13281///
13282/// This version assumes From has a single result value.
13283///
13285 SDNode *From = FromN.getNode();
13286 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13287 "Cannot replace with this method!");
13288 assert(From != To.getNode() && "Cannot replace uses of with self");
13289
13290 // Preserve Debug Values
13291 transferDbgValues(FromN, To);
13292 // Preserve extra info.
13293 copyExtraInfo(From, To.getNode());
13294
13295 // Iterate over all the existing uses of From. New uses will be added
13296 // to the beginning of the use list, which we avoid visiting.
13297 // This specifically avoids visiting uses of From that arise while the
13298 // replacement is happening, because any such uses would be the result
13299 // of CSE: If an existing node looks like From after one of its operands
13300 // is replaced by To, we don't want to replace of all its users with To
13301 // too. See PR3018 for more info.
13302 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13303 RAUWUpdateListener Listener(*this, UI, UE);
13304 while (UI != UE) {
13305 SDNode *User = UI->getUser();
13306
13307 // This node is about to morph, remove its old self from the CSE maps.
13308 RemoveNodeFromCSEMaps(User);
13309
13310 // A user can appear in a use list multiple times, and when this
13311 // happens the uses are usually next to each other in the list.
13312 // To help reduce the number of CSE recomputations, process all
13313 // the uses of this user that we can find this way.
13314 do {
13315 SDUse &Use = *UI;
13316 ++UI;
13317 Use.set(To);
13318 if (To->isDivergent() != From->isDivergent())
13320 } while (UI != UE && UI->getUser() == User);
13321 // Now that we have modified User, add it back to the CSE maps. If it
13322 // already exists there, recursively merge the results together.
13323 AddModifiedNodeToCSEMaps(User);
13324 }
13325
13326 // If we just RAUW'd the root, take note.
13327 if (FromN == getRoot())
13328 setRoot(To);
13329}
13330
13331/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13332/// This can cause recursive merging of nodes in the DAG.
13333///
13334/// This version assumes that for each value of From, there is a
13335/// corresponding value in To in the same position with the same type.
13336///
13338#ifndef NDEBUG
13339 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13340 assert((!From->hasAnyUseOfValue(i) ||
13341 From->getValueType(i) == To->getValueType(i)) &&
13342 "Cannot use this version of ReplaceAllUsesWith!");
13343#endif
13344
13345 // Handle the trivial case.
13346 if (From == To)
13347 return;
13348
13349 // Preserve Debug Info. Only do this if there's a use.
13350 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13351 if (From->hasAnyUseOfValue(i)) {
13352 assert((i < To->getNumValues()) && "Invalid To location");
13353 transferDbgValues(SDValue(From, i), SDValue(To, i));
13354 }
13355 // Preserve extra info.
13356 copyExtraInfo(From, To);
13357
13358 // Iterate over just the existing users of From. See the comments in
13359 // the ReplaceAllUsesWith above.
13360 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13361 RAUWUpdateListener Listener(*this, UI, UE);
13362 while (UI != UE) {
13363 SDNode *User = UI->getUser();
13364
13365 // This node is about to morph, remove its old self from the CSE maps.
13366 RemoveNodeFromCSEMaps(User);
13367
13368 // A user can appear in a use list multiple times, and when this
13369 // happens the uses are usually next to each other in the list.
13370 // To help reduce the number of CSE recomputations, process all
13371 // the uses of this user that we can find this way.
13372 do {
13373 SDUse &Use = *UI;
13374 ++UI;
13375 Use.setNode(To);
13376 if (To->isDivergent() != From->isDivergent())
13378 } while (UI != UE && UI->getUser() == User);
13379
13380 // Now that we have modified User, add it back to the CSE maps. If it
13381 // already exists there, recursively merge the results together.
13382 AddModifiedNodeToCSEMaps(User);
13383 }
13384
13385 // If we just RAUW'd the root, take note.
13386 if (From == getRoot().getNode())
13387 setRoot(SDValue(To, getRoot().getResNo()));
13388}
13389
13390/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13391/// This can cause recursive merging of nodes in the DAG.
13392///
13393/// This version can replace From with any result values. To must match the
13394/// number and types of values returned by From.
13396 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13397 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13398
13399 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13400 // Preserve Debug Info.
13401 transferDbgValues(SDValue(From, i), To[i]);
13402 // Preserve extra info.
13403 copyExtraInfo(From, To[i].getNode());
13404 }
13405
13406 // Iterate over just the existing users of From. See the comments in
13407 // the ReplaceAllUsesWith above.
13408 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13409 RAUWUpdateListener Listener(*this, UI, UE);
13410 while (UI != UE) {
13411 SDNode *User = UI->getUser();
13412
13413 // This node is about to morph, remove its old self from the CSE maps.
13414 RemoveNodeFromCSEMaps(User);
13415
13416 // A user can appear in a use list multiple times, and when this happens the
13417 // uses are usually next to each other in the list. To help reduce the
13418 // number of CSE and divergence recomputations, process all the uses of this
13419 // user that we can find this way.
13420 bool To_IsDivergent = false;
13421 do {
13422 SDUse &Use = *UI;
13423 const SDValue &ToOp = To[Use.getResNo()];
13424 ++UI;
13425 Use.set(ToOp);
13426 if (ToOp.getValueType() != MVT::Other)
13427 To_IsDivergent |= ToOp->isDivergent();
13428 } while (UI != UE && UI->getUser() == User);
13429
13430 if (To_IsDivergent != From->isDivergent())
13432
13433 // Now that we have modified User, add it back to the CSE maps. If it
13434 // already exists there, recursively merge the results together.
13435 AddModifiedNodeToCSEMaps(User);
13436 }
13437
13438 // If we just RAUW'd the root, take note.
13439 if (From == getRoot().getNode())
13440 setRoot(SDValue(To[getRoot().getResNo()]));
13441}
13442
13443/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13444/// uses of other values produced by From.getNode() alone. The Deleted
13445/// vector is handled the same way as for ReplaceAllUsesWith.
13447 // Handle the really simple, really trivial case efficiently.
13448 if (From == To) return;
13449
13450 // Handle the simple, trivial, case efficiently.
13451 if (From.getNode()->getNumValues() == 1) {
13452 ReplaceAllUsesWith(From, To);
13453 return;
13454 }
13455
13456 // Preserve Debug Info.
13457 transferDbgValues(From, To);
13458 copyExtraInfo(From.getNode(), To.getNode());
13459
13460 // Iterate over just the existing users of From. See the comments in
13461 // the ReplaceAllUsesWith above.
13462 SDNode::use_iterator UI = From.getNode()->use_begin(),
13463 UE = From.getNode()->use_end();
13464 RAUWUpdateListener Listener(*this, UI, UE);
13465 while (UI != UE) {
13466 SDNode *User = UI->getUser();
13467 bool UserRemovedFromCSEMaps = false;
13468
13469 // A user can appear in a use list multiple times, and when this
13470 // happens the uses are usually next to each other in the list.
13471 // To help reduce the number of CSE recomputations, process all
13472 // the uses of this user that we can find this way.
13473 do {
13474 SDUse &Use = *UI;
13475
13476 // Skip uses of different values from the same node.
13477 if (Use.getResNo() != From.getResNo()) {
13478 ++UI;
13479 continue;
13480 }
13481
13482 // If this node hasn't been modified yet, it's still in the CSE maps,
13483 // so remove its old self from the CSE maps.
13484 if (!UserRemovedFromCSEMaps) {
13485 RemoveNodeFromCSEMaps(User);
13486 UserRemovedFromCSEMaps = true;
13487 }
13488
13489 ++UI;
13490 Use.set(To);
13491 if (To->isDivergent() != From->isDivergent())
13493 } while (UI != UE && UI->getUser() == User);
13494 // We are iterating over all uses of the From node, so if a use
13495 // doesn't use the specific value, no changes are made.
13496 if (!UserRemovedFromCSEMaps)
13497 continue;
13498
13499 // Now that we have modified User, add it back to the CSE maps. If it
13500 // already exists there, recursively merge the results together.
13501 AddModifiedNodeToCSEMaps(User);
13502 }
13503
13504 // If we just RAUW'd the root, take note.
13505 if (From == getRoot())
13506 setRoot(To);
13507}
13508
13509namespace {
13510
13511/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13512/// to record information about a use.
13513struct UseMemo {
13514 SDNode *User;
13515 unsigned Index;
13516 SDUse *Use;
13517};
13518
13519/// operator< - Sort Memos by User.
13520bool operator<(const UseMemo &L, const UseMemo &R) {
13521 return (intptr_t)L.User < (intptr_t)R.User;
13522}
13523
13524/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13525/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13526/// the node already has been taken care of recursively.
13527class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13528 SmallVectorImpl<UseMemo> &Uses;
13529
13530 void NodeDeleted(SDNode *N, SDNode *E) override {
13531 for (UseMemo &Memo : Uses)
13532 if (Memo.User == N)
13533 Memo.User = nullptr;
13534 }
13535
13536public:
13537 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13538 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13539};
13540
13541} // end anonymous namespace
13542
13543/// Return true if a glue output should propagate divergence information.
13545 switch (Node->getOpcode()) {
13546 case ISD::CopyFromReg:
13547 case ISD::CopyToReg:
13548 return false;
13549 default:
13550 return true;
13551 }
13552
13553 llvm_unreachable("covered opcode switch");
13554}
13555
13557 if (TLI->isSDNodeAlwaysUniform(N)) {
13558 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13559 "Conflicting divergence information!");
13560 return false;
13561 }
13562 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13563 return true;
13564 for (const auto &Op : N->ops()) {
13565 EVT VT = Op.getValueType();
13566
13567 // Skip Chain. It does not carry divergence.
13568 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13569 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13570 return true;
13571 }
13572 return false;
13573}
13574
13576 SmallVector<SDNode *, 16> Worklist(1, N);
13577 do {
13578 N = Worklist.pop_back_val();
13579 bool IsDivergent = calculateDivergence(N);
13580 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13581 N->SDNodeBits.IsDivergent = IsDivergent;
13582 llvm::append_range(Worklist, N->users());
13583 }
13584 } while (!Worklist.empty());
13585}
13586
13587void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13589 Order.reserve(AllNodes.size());
13590 for (auto &N : allnodes()) {
13591 unsigned NOps = N.getNumOperands();
13592 Degree[&N] = NOps;
13593 if (0 == NOps)
13594 Order.push_back(&N);
13595 }
13596 for (size_t I = 0; I != Order.size(); ++I) {
13597 SDNode *N = Order[I];
13598 for (auto *U : N->users()) {
13599 unsigned &UnsortedOps = Degree[U];
13600 if (0 == --UnsortedOps)
13601 Order.push_back(U);
13602 }
13603 }
13604}
13605
13606#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13607void SelectionDAG::VerifyDAGDivergence() {
13608 std::vector<SDNode *> TopoOrder;
13609 CreateTopologicalOrder(TopoOrder);
13610 for (auto *N : TopoOrder) {
13611 assert(calculateDivergence(N) == N->isDivergent() &&
13612 "Divergence bit inconsistency detected");
13613 }
13614}
13615#endif
13616
13617/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13618/// uses of other values produced by From.getNode() alone. The same value
13619/// may appear in both the From and To list. The Deleted vector is
13620/// handled the same way as for ReplaceAllUsesWith.
13622 const SDValue *To,
13623 unsigned Num){
13624 // Handle the simple, trivial case efficiently.
13625 if (Num == 1)
13626 return ReplaceAllUsesOfValueWith(*From, *To);
13627
13628 transferDbgValues(*From, *To);
13629 copyExtraInfo(From->getNode(), To->getNode());
13630
13631 // Read up all the uses and make records of them. This helps
13632 // processing new uses that are introduced during the
13633 // replacement process.
13635 for (unsigned i = 0; i != Num; ++i) {
13636 unsigned FromResNo = From[i].getResNo();
13637 SDNode *FromNode = From[i].getNode();
13638 for (SDUse &Use : FromNode->uses()) {
13639 if (Use.getResNo() == FromResNo) {
13640 UseMemo Memo = {Use.getUser(), i, &Use};
13641 Uses.push_back(Memo);
13642 }
13643 }
13644 }
13645
13646 // Sort the uses, so that all the uses from a given User are together.
13648 RAUOVWUpdateListener Listener(*this, Uses);
13649
13650 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13651 UseIndex != UseIndexEnd; ) {
13652 // We know that this user uses some value of From. If it is the right
13653 // value, update it.
13654 SDNode *User = Uses[UseIndex].User;
13655 // If the node has been deleted by recursive CSE updates when updating
13656 // another node, then just skip this entry.
13657 if (User == nullptr) {
13658 ++UseIndex;
13659 continue;
13660 }
13661
13662 // This node is about to morph, remove its old self from the CSE maps.
13663 RemoveNodeFromCSEMaps(User);
13664
13665 // The Uses array is sorted, so all the uses for a given User
13666 // are next to each other in the list.
13667 // To help reduce the number of CSE recomputations, process all
13668 // the uses of this user that we can find this way.
13669 do {
13670 unsigned i = Uses[UseIndex].Index;
13671 SDUse &Use = *Uses[UseIndex].Use;
13672 ++UseIndex;
13673
13674 Use.set(To[i]);
13675 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13676
13677 // Now that we have modified User, add it back to the CSE maps. If it
13678 // already exists there, recursively merge the results together.
13679 AddModifiedNodeToCSEMaps(User);
13680 }
13681}
13682
13683/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13684/// based on their topological order. It returns the maximum id and a vector
13685/// of the SDNodes* in assigned order by reference.
13687 unsigned DAGSize = 0;
13688
13689 // SortedPos tracks the progress of the algorithm. Nodes before it are
13690 // sorted, nodes after it are unsorted. When the algorithm completes
13691 // it is at the end of the list.
13692 allnodes_iterator SortedPos = allnodes_begin();
13693
13694 // Visit all the nodes. Move nodes with no operands to the front of
13695 // the list immediately. Annotate nodes that do have operands with their
13696 // operand count. Before we do this, the Node Id fields of the nodes
13697 // may contain arbitrary values. After, the Node Id fields for nodes
13698 // before SortedPos will contain the topological sort index, and the
13699 // Node Id fields for nodes At SortedPos and after will contain the
13700 // count of outstanding operands.
13702 checkForCycles(&N, this);
13703 unsigned Degree = N.getNumOperands();
13704 if (Degree == 0) {
13705 // A node with no uses, add it to the result array immediately.
13706 N.setNodeId(DAGSize++);
13707 allnodes_iterator Q(&N);
13708 if (Q != SortedPos)
13709 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13710 assert(SortedPos != AllNodes.end() && "Overran node list");
13711 ++SortedPos;
13712 } else {
13713 // Temporarily use the Node Id as scratch space for the degree count.
13714 N.setNodeId(Degree);
13715 }
13716 }
13717
13718 // Visit all the nodes. As we iterate, move nodes into sorted order,
13719 // such that by the time the end is reached all nodes will be sorted.
13720 for (SDNode &Node : allnodes()) {
13721 SDNode *N = &Node;
13722 checkForCycles(N, this);
13723 // N is in sorted position, so all its uses have one less operand
13724 // that needs to be sorted.
13725 for (SDNode *P : N->users()) {
13726 unsigned Degree = P->getNodeId();
13727 assert(Degree != 0 && "Invalid node degree");
13728 --Degree;
13729 if (Degree == 0) {
13730 // All of P's operands are sorted, so P may sorted now.
13731 P->setNodeId(DAGSize++);
13732 if (P->getIterator() != SortedPos)
13733 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13734 assert(SortedPos != AllNodes.end() && "Overran node list");
13735 ++SortedPos;
13736 } else {
13737 // Update P's outstanding operand count.
13738 P->setNodeId(Degree);
13739 }
13740 }
13741 if (Node.getIterator() == SortedPos) {
13742#ifndef NDEBUG
13744 SDNode *S = &*++I;
13745 dbgs() << "Overran sorted position:\n";
13746 S->dumprFull(this); dbgs() << "\n";
13747 dbgs() << "Checking if this is due to cycles\n";
13748 checkForCycles(this, true);
13749#endif
13750 llvm_unreachable(nullptr);
13751 }
13752 }
13753
13754 assert(SortedPos == AllNodes.end() &&
13755 "Topological sort incomplete!");
13756 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13757 "First node in topological sort is not the entry token!");
13758 assert(AllNodes.front().getNodeId() == 0 &&
13759 "First node in topological sort has non-zero id!");
13760 assert(AllNodes.front().getNumOperands() == 0 &&
13761 "First node in topological sort has operands!");
13762 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13763 "Last node in topologic sort has unexpected id!");
13764 assert(AllNodes.back().use_empty() &&
13765 "Last node in topologic sort has users!");
13766 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13767 return DAGSize;
13768}
13769
13771 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13772 SortedNodes.clear();
13773 // Node -> remaining number of outstanding operands.
13774 DenseMap<const SDNode *, unsigned> RemainingOperands;
13775
13776 // Put nodes without any operands into SortedNodes first.
13777 for (const SDNode &N : allnodes()) {
13778 checkForCycles(&N, this);
13779 unsigned NumOperands = N.getNumOperands();
13780 if (NumOperands == 0)
13781 SortedNodes.push_back(&N);
13782 else
13783 // Record their total number of outstanding operands.
13784 RemainingOperands[&N] = NumOperands;
13785 }
13786
13787 // A node is pushed into SortedNodes when all of its operands (predecessors in
13788 // the graph) are also in SortedNodes.
13789 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13790 const SDNode *N = SortedNodes[i];
13791 for (const SDNode *U : N->users()) {
13792 // HandleSDNode is never part of a DAG and therefore has no entry in
13793 // RemainingOperands.
13794 if (U->getOpcode() == ISD::HANDLENODE)
13795 continue;
13796 unsigned &NumRemOperands = RemainingOperands[U];
13797 assert(NumRemOperands && "Invalid number of remaining operands");
13798 --NumRemOperands;
13799 if (!NumRemOperands)
13800 SortedNodes.push_back(U);
13801 }
13802 }
13803
13804 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13805 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13806 "First node in topological sort is not the entry token");
13807 assert(SortedNodes.front()->getNumOperands() == 0 &&
13808 "First node in topological sort has operands");
13809}
13810
13811/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13812/// value is produced by SD.
13813void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13814 for (SDNode *SD : DB->getSDNodes()) {
13815 if (!SD)
13816 continue;
13817 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13818 SD->setHasDebugValue(true);
13819 }
13820 DbgInfo->add(DB, isParameter);
13821}
13822
13823void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13824
13826 SDValue NewMemOpChain) {
13827 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13828 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13829 // The new memory operation must have the same position as the old load in
13830 // terms of memory dependency. Create a TokenFactor for the old load and new
13831 // memory operation and update uses of the old load's output chain to use that
13832 // TokenFactor.
13833 if (OldChain == NewMemOpChain || OldChain.use_empty())
13834 return NewMemOpChain;
13835
13836 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13837 OldChain, NewMemOpChain);
13838 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13839 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13840 return TokenFactor;
13841}
13842
13844 SDValue NewMemOp) {
13845 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13846 SDValue OldChain = SDValue(OldLoad, 1);
13847 SDValue NewMemOpChain = NewMemOp.getValue(1);
13848 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13849}
13850
13852 Function **OutFunction) {
13853 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13854
13855 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13856 auto *Module = MF->getFunction().getParent();
13857 auto *Function = Module->getFunction(Symbol);
13858
13859 if (OutFunction != nullptr)
13860 *OutFunction = Function;
13861
13862 if (Function != nullptr) {
13863 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13864 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13865 }
13866
13867 std::string ErrorStr;
13868 raw_string_ostream ErrorFormatter(ErrorStr);
13869 ErrorFormatter << "Undefined external symbol ";
13870 ErrorFormatter << '"' << Symbol << '"';
13871 report_fatal_error(Twine(ErrorStr));
13872}
13873
13874//===----------------------------------------------------------------------===//
13875// SDNode Class
13876//===----------------------------------------------------------------------===//
13877
13880 return Const != nullptr && Const->isZero();
13881}
13882
13884 return V.isUndef() || isNullConstant(V);
13885}
13886
13889 return Const != nullptr && Const->isZero() && !Const->isNegative();
13890}
13891
13894 return Const != nullptr && Const->isAllOnes();
13895}
13896
13899 return Const != nullptr && Const->isOne();
13900}
13901
13904 return Const != nullptr && Const->isMinSignedValue();
13905}
13906
13908 SDValue V, unsigned OperandNo,
13909 unsigned Depth) const {
13910 APInt DemandedElts = getDemandAllEltsMask(V);
13911 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13912}
13913
13915 SDValue V, const APInt &DemandedElts,
13916 unsigned OperandNo, unsigned Depth) const {
13917 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13918 // TODO: Target-specific opcodes could be added.
13919 if (V.getValueType().isInteger()) {
13920 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13921 if (Known.isConstant()) {
13922 const APInt &Const = Known.getConstant();
13923 switch (Opcode) {
13924 case ISD::ADD:
13925 case ISD::OR:
13926 case ISD::XOR:
13927 case ISD::UMAX:
13928 return Const.isZero();
13929 case ISD::MUL:
13930 return Const.isOne();
13931 case ISD::AND:
13932 case ISD::UMIN:
13933 return Const.isAllOnes();
13934 case ISD::SMAX:
13935 return Const.isMinSignedValue();
13936 case ISD::SMIN:
13937 return Const.isMaxSignedValue();
13938 case ISD::SUB:
13939 case ISD::SHL:
13940 case ISD::SRA:
13941 case ISD::SRL:
13942 return OperandNo == 1 && Const.isZero();
13943 case ISD::UDIV:
13944 case ISD::SDIV:
13945 return OperandNo == 1 && Const.isOne();
13946 }
13947 }
13948 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13949 switch (Opcode) {
13950 case ISD::FADD:
13951 return ConstFP->isZero() &&
13952 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13953 case ISD::FSUB:
13954 return OperandNo == 1 && ConstFP->isZero() &&
13955 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13956 case ISD::FMUL:
13957 return ConstFP->isOne();
13958 case ISD::FDIV:
13959 return OperandNo == 1 && ConstFP->isOne();
13960 case ISD::FMINNUM:
13961 case ISD::FMAXNUM: {
13962 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
13963 EVT VT = V.getValueType();
13964 const fltSemantics &Semantics = VT.getFltSemantics();
13965 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13966 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13967 : APFloat::getLargest(Semantics);
13968 if (Opcode == ISD::FMAXNUM)
13969 NeutralAF.changeSign();
13970
13971 return ConstFP->isExactlyValue(NeutralAF);
13972 }
13973 case ISD::FMINIMUM:
13974 case ISD::FMAXIMUM: {
13975 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
13976 const APFloat &VAPF = ConstFP->getValueAPF();
13977 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
13978 if (Flags.hasNoInfs())
13979 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
13980 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
13981 }
13982 }
13983 }
13984 return false;
13985}
13986
13988 while (V.getOpcode() == ISD::BITCAST)
13989 V = V.getOperand(0);
13990 return V;
13991}
13992
13994 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
13995 V = V.getOperand(0);
13996 return V;
13997}
13998
14000 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14001 V = V.getOperand(0);
14002 return V;
14003}
14004
14006 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14007 SDValue InVec = V.getOperand(0);
14008 SDValue EltNo = V.getOperand(2);
14009 EVT VT = InVec.getValueType();
14010 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14011 if (IndexC && VT.isFixedLengthVector() &&
14012 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
14013 !DemandedElts[IndexC->getZExtValue()]) {
14014 V = InVec;
14015 continue;
14016 }
14017 break;
14018 }
14019 return V;
14020}
14021
14023 while (V.getOpcode() == ISD::TRUNCATE)
14024 V = V.getOperand(0);
14025 return V;
14026}
14027
14028bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14029 if (V.getOpcode() != ISD::XOR)
14030 return false;
14031 V = peekThroughBitcasts(V.getOperand(1));
14032 unsigned NumBits = V.getScalarValueSizeInBits();
14033 ConstantSDNode *C =
14034 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14035 return C && (C->getAPIntValue().countr_one() >= NumBits);
14036}
14037
14039 bool AllowTruncation) {
14040 APInt DemandedElts = getDemandAllEltsMask(N);
14041 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14042}
14043
14045 bool AllowUndefs,
14046 bool AllowTruncation) {
14048 return CN;
14049
14050 // SplatVectors can truncate their operands. Ignore that case here unless
14051 // AllowTruncation is set.
14052 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14053 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14054 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14055 EVT CVT = CN->getValueType(0);
14056 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14057 if (AllowTruncation || CVT == VecEltVT)
14058 return CN;
14059 }
14060 }
14061
14063 BitVector UndefElements;
14064 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14065
14066 // BuildVectors can truncate their operands. Ignore that case here unless
14067 // AllowTruncation is set.
14068 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14069 if (CN && (UndefElements.none() || AllowUndefs)) {
14070 EVT CVT = CN->getValueType(0);
14071 EVT NSVT = N.getValueType().getScalarType();
14072 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14073 if (AllowTruncation || (CVT == NSVT))
14074 return CN;
14075 }
14076 }
14077
14078 return nullptr;
14079}
14080
14082 APInt DemandedElts = getDemandAllEltsMask(N);
14083 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14084}
14085
14087 const APInt &DemandedElts,
14088 bool AllowUndefs) {
14090 return CN;
14091
14093 BitVector UndefElements;
14094 ConstantFPSDNode *CN =
14095 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14096 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14097 if (CN && (UndefElements.none() || AllowUndefs))
14098 return CN;
14099 }
14100
14101 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14102 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14103 return CN;
14104
14105 return nullptr;
14106}
14107
14108bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14109 // TODO: may want to use peekThroughBitcast() here.
14110 ConstantSDNode *C =
14111 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14112 return C && C->isZero();
14113}
14114
14115bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14116 ConstantSDNode *C =
14117 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14118 return C && C->isOne();
14119}
14120
14121bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14122 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14123 return C && C->isOne();
14124}
14125
14126bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14128 unsigned BitWidth = N.getScalarValueSizeInBits();
14129 ConstantSDNode *C =
14130 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14131 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14132}
14133
14134bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
14135 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
14136 return C && APInt::isSameValue(C->getAPIntValue(),
14137 APInt(C->getAPIntValue().getBitWidth(), 1));
14138}
14139
14140bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14142 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14143 return C && C->isZero();
14144}
14145
14146bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14147 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14148 return C && C->isZero();
14149}
14150
14154
14156 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14158 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14159 bool IsVolatile = false;
14160 bool IsNonTemporal = false;
14161 bool IsDereferenceable = true;
14162 bool IsInvariant = true;
14163 for (const MachineMemOperand *MMO : memoperands()) {
14164 IsVolatile |= MMO->isVolatile();
14165 IsNonTemporal |= MMO->isNonTemporal();
14166 IsDereferenceable &= MMO->isDereferenceable();
14167 IsInvariant &= MMO->isInvariant();
14168 }
14169 MemSDNodeBits.IsVolatile = IsVolatile;
14170 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14171 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14172 MemSDNodeBits.IsInvariant = IsInvariant;
14173
14174 // For the single-MMO case, we check here that the size of the memory operand
14175 // fits within the size of the MMO. This is because the MMO might indicate
14176 // only a possible address range instead of specifying the affected memory
14177 // addresses precisely.
14180 getMemOperand()->getSize().getValue())) &&
14181 "Size mismatch!");
14182}
14183
14184/// Profile - Gather unique data for the node.
14185///
14187 AddNodeIDNode(ID, this);
14188}
14189
14190namespace {
14191
14192 struct EVTArray {
14193 std::vector<EVT> VTs;
14194
14195 EVTArray() {
14196 VTs.reserve(MVT::VALUETYPE_SIZE);
14197 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14198 VTs.push_back(MVT((MVT::SimpleValueType)i));
14199 }
14200 };
14201
14202} // end anonymous namespace
14203
14204/// getValueTypeList - Return a pointer to the specified value type.
14205///
14206const EVT *SDNode::getValueTypeList(MVT VT) {
14207 static EVTArray SimpleVTArray;
14208
14209 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14210 return &SimpleVTArray.VTs[VT.SimpleTy];
14211}
14212
14213/// hasAnyUseOfValue - Return true if there are any use of the indicated
14214/// value. This method ignores uses of other values defined by this operation.
14215bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14216 assert(Value < getNumValues() && "Bad value!");
14217
14218 for (SDUse &U : uses())
14219 if (U.getResNo() == Value)
14220 return true;
14221
14222 return false;
14223}
14224
14225/// isOnlyUserOf - Return true if this node is the only use of N.
14226bool SDNode::isOnlyUserOf(const SDNode *N) const {
14227 bool Seen = false;
14228 for (const SDNode *User : N->users()) {
14229 if (User == this)
14230 Seen = true;
14231 else
14232 return false;
14233 }
14234
14235 return Seen;
14236}
14237
14238/// Return true if the only users of N are contained in Nodes.
14240 bool Seen = false;
14241 for (const SDNode *User : N->users()) {
14242 if (llvm::is_contained(Nodes, User))
14243 Seen = true;
14244 else
14245 return false;
14246 }
14247
14248 return Seen;
14249}
14250
14251/// Return true if the referenced return value is an operand of N.
14252bool SDValue::isOperandOf(const SDNode *N) const {
14253 return is_contained(N->op_values(), *this);
14254}
14255
14256bool SDNode::isOperandOf(const SDNode *N) const {
14257 return any_of(N->op_values(),
14258 [this](SDValue Op) { return this == Op.getNode(); });
14259}
14260
14261/// reachesChainWithoutSideEffects - Return true if this operand (which must
14262/// be a chain) reaches the specified operand without crossing any
14263/// side-effecting instructions on any chain path. In practice, this looks
14264/// through token factors and non-volatile loads. In order to remain efficient,
14265/// this only looks a couple of nodes in, it does not do an exhaustive search.
14266///
14267/// Note that we only need to examine chains when we're searching for
14268/// side-effects; SelectionDAG requires that all side-effects are represented
14269/// by chains, even if another operand would force a specific ordering. This
14270/// constraint is necessary to allow transformations like splitting loads.
14272 unsigned Depth) const {
14273 if (*this == Dest) return true;
14274
14275 // Don't search too deeply, we just want to be able to see through
14276 // TokenFactor's etc.
14277 if (Depth == 0) return false;
14278
14279 // If this is a token factor, all inputs to the TF happen in parallel.
14280 if (getOpcode() == ISD::TokenFactor) {
14281 // First, try a shallow search.
14282 if (is_contained((*this)->ops(), Dest)) {
14283 // We found the chain we want as an operand of this TokenFactor.
14284 // Essentially, we reach the chain without side-effects if we could
14285 // serialize the TokenFactor into a simple chain of operations with
14286 // Dest as the last operation. This is automatically true if the
14287 // chain has one use: there are no other ordering constraints.
14288 // If the chain has more than one use, we give up: some other
14289 // use of Dest might force a side-effect between Dest and the current
14290 // node.
14291 if (Dest.hasOneUse())
14292 return true;
14293 }
14294 // Next, try a deep search: check whether every operand of the TokenFactor
14295 // reaches Dest.
14296 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14297 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14298 });
14299 }
14300
14301 // Loads don't have side effects, look through them.
14302 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14303 if (Ld->isUnordered())
14304 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14305 }
14306 return false;
14307}
14308
14309bool SDNode::hasPredecessor(const SDNode *N) const {
14312 Worklist.push_back(this);
14313 return hasPredecessorHelper(N, Visited, Worklist);
14314}
14315
14317 this->Flags &= Flags;
14318}
14319
14320SDValue
14322 ArrayRef<ISD::NodeType> CandidateBinOps,
14323 bool AllowPartials) {
14324 // The pattern must end in an extract from index 0.
14325 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14326 !isNullConstant(Extract->getOperand(1)))
14327 return SDValue();
14328
14329 // Match against one of the candidate binary ops.
14330 SDValue Op = Extract->getOperand(0);
14331 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14332 return Op.getOpcode() == unsigned(BinOp);
14333 }))
14334 return SDValue();
14335
14336 // Floating-point reductions may require relaxed constraints on the final step
14337 // of the reduction because they may reorder intermediate operations.
14338 unsigned CandidateBinOp = Op.getOpcode();
14339 if (Op.getValueType().isFloatingPoint()) {
14340 SDNodeFlags Flags = Op->getFlags();
14341 switch (CandidateBinOp) {
14342 case ISD::FADD:
14343 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14344 return SDValue();
14345 break;
14346 default:
14347 llvm_unreachable("Unhandled FP opcode for binop reduction");
14348 }
14349 }
14350
14351 // Matching failed - attempt to see if we did enough stages that a partial
14352 // reduction from a subvector is possible.
14353 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14354 if (!AllowPartials || !Op)
14355 return SDValue();
14356 EVT OpVT = Op.getValueType();
14357 EVT OpSVT = OpVT.getScalarType();
14358 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14359 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14361 return SDValue();
14362 BinOp = (ISD::NodeType)CandidateBinOp;
14363 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14364 };
14365
14366 // At each stage, we're looking for something that looks like:
14367 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14368 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14369 // i32 undef, i32 undef, i32 undef, i32 undef>
14370 // %a = binop <8 x i32> %op, %s
14371 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14372 // we expect something like:
14373 // <4,5,6,7,u,u,u,u>
14374 // <2,3,u,u,u,u,u,u>
14375 // <1,u,u,u,u,u,u,u>
14376 // While a partial reduction match would be:
14377 // <2,3,u,u,u,u,u,u>
14378 // <1,u,u,u,u,u,u,u>
14379 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14380 SDValue PrevOp;
14381 for (unsigned i = 0; i < Stages; ++i) {
14382 unsigned MaskEnd = (1 << i);
14383
14384 if (Op.getOpcode() != CandidateBinOp)
14385 return PartialReduction(PrevOp, MaskEnd);
14386
14387 SDValue Op0 = Op.getOperand(0);
14388 SDValue Op1 = Op.getOperand(1);
14389
14391 if (Shuffle) {
14392 Op = Op1;
14393 } else {
14394 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14395 Op = Op0;
14396 }
14397
14398 // The first operand of the shuffle should be the same as the other operand
14399 // of the binop.
14400 if (!Shuffle || Shuffle->getOperand(0) != Op)
14401 return PartialReduction(PrevOp, MaskEnd);
14402
14403 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14404 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14405 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14406 return PartialReduction(PrevOp, MaskEnd);
14407
14408 PrevOp = Op;
14409 }
14410
14411 // Handle subvector reductions, which tend to appear after the shuffle
14412 // reduction stages.
14413 while (Op.getOpcode() == CandidateBinOp) {
14414 unsigned NumElts = Op.getValueType().getVectorNumElements();
14415 SDValue Op0 = Op.getOperand(0);
14416 SDValue Op1 = Op.getOperand(1);
14417 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14419 Op0.getOperand(0) != Op1.getOperand(0))
14420 break;
14421 SDValue Src = Op0.getOperand(0);
14422 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14423 if (NumSrcElts != (2 * NumElts))
14424 break;
14425 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14426 Op1.getConstantOperandAPInt(1) == NumElts) &&
14427 !(Op1.getConstantOperandAPInt(1) == 0 &&
14428 Op0.getConstantOperandAPInt(1) == NumElts))
14429 break;
14430 Op = Src;
14431 }
14432
14433 BinOp = (ISD::NodeType)CandidateBinOp;
14434 return Op;
14435}
14436
14438 EVT VT = N->getValueType(0);
14439 EVT EltVT = VT.getVectorElementType();
14440 unsigned NE = VT.getVectorNumElements();
14441
14442 SDLoc dl(N);
14443
14444 // If ResNE is 0, fully unroll the vector op.
14445 if (ResNE == 0)
14446 ResNE = NE;
14447 else if (NE > ResNE)
14448 NE = ResNE;
14449
14450 if (N->getNumValues() == 2) {
14451 SmallVector<SDValue, 8> Scalars0, Scalars1;
14452 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14453 EVT VT1 = N->getValueType(1);
14454 EVT EltVT1 = VT1.getVectorElementType();
14455
14456 unsigned i;
14457 for (i = 0; i != NE; ++i) {
14458 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14459 SDValue Operand = N->getOperand(j);
14460 EVT OperandVT = Operand.getValueType();
14461
14462 // A vector operand; extract a single element.
14463 EVT OperandEltVT = OperandVT.getVectorElementType();
14464 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14465 }
14466
14467 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14468 Scalars0.push_back(EltOp);
14469 Scalars1.push_back(EltOp.getValue(1));
14470 }
14471
14472 for (; i < ResNE; ++i) {
14473 Scalars0.push_back(getUNDEF(EltVT));
14474 Scalars1.push_back(getUNDEF(EltVT1));
14475 }
14476
14477 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14478 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResNE);
14479 SDValue Vec0 = getBuildVector(VecVT, dl, Scalars0);
14480 SDValue Vec1 = getBuildVector(VecVT1, dl, Scalars1);
14481 return getMergeValues({Vec0, Vec1}, dl);
14482 }
14483
14484 assert(N->getNumValues() == 1 &&
14485 "Can't unroll a vector with multiple results!");
14486
14488 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14489
14490 unsigned i;
14491 for (i= 0; i != NE; ++i) {
14492 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14493 SDValue Operand = N->getOperand(j);
14494 EVT OperandVT = Operand.getValueType();
14495 if (OperandVT.isVector()) {
14496 // A vector operand; extract a single element.
14497 EVT OperandEltVT = OperandVT.getVectorElementType();
14498 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14499 } else {
14500 // A scalar operand; just use it as is.
14501 Operands[j] = Operand;
14502 }
14503 }
14504
14505 switch (N->getOpcode()) {
14506 default: {
14507 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14508 N->getFlags()));
14509 break;
14510 }
14511 case ISD::VSELECT:
14512 Scalars.push_back(
14513 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14514 break;
14515 case ISD::SHL:
14516 case ISD::SRA:
14517 case ISD::SRL:
14518 case ISD::ROTL:
14519 case ISD::ROTR:
14520 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14522 Operands[1])));
14523 break;
14525 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14526 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14527 Operands[0],
14528 getValueType(ExtVT)));
14529 break;
14530 }
14531 case ISD::ADDRSPACECAST: {
14532 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14533 Scalars.push_back(getAddrSpaceCast(dl, EltVT, Operands[0],
14534 ASC->getSrcAddressSpace(),
14535 ASC->getDestAddressSpace()));
14536 break;
14537 }
14538 }
14539 }
14540
14541 for (; i < ResNE; ++i)
14542 Scalars.push_back(getUNDEF(EltVT));
14543
14544 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14545 return getBuildVector(VecVT, dl, Scalars);
14546}
14547
14548std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14549 SDNode *N, unsigned ResNE) {
14550 unsigned Opcode = N->getOpcode();
14551 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14552 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14553 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14554 "Expected an overflow opcode");
14555
14556 EVT ResVT = N->getValueType(0);
14557 EVT OvVT = N->getValueType(1);
14558 EVT ResEltVT = ResVT.getVectorElementType();
14559 EVT OvEltVT = OvVT.getVectorElementType();
14560 SDLoc dl(N);
14561
14562 // If ResNE is 0, fully unroll the vector op.
14563 unsigned NE = ResVT.getVectorNumElements();
14564 if (ResNE == 0)
14565 ResNE = NE;
14566 else if (NE > ResNE)
14567 NE = ResNE;
14568
14569 SmallVector<SDValue, 8> LHSScalars;
14570 SmallVector<SDValue, 8> RHSScalars;
14571 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14572 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14573
14574 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14575 SDVTList VTs = getVTList(ResEltVT, SVT);
14576 SmallVector<SDValue, 8> ResScalars;
14577 SmallVector<SDValue, 8> OvScalars;
14578 for (unsigned i = 0; i < NE; ++i) {
14579 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14580 SDValue Ov =
14581 getSelect(dl, OvEltVT, Res.getValue(1),
14582 getBoolConstant(true, dl, OvEltVT, ResVT),
14583 getConstant(0, dl, OvEltVT));
14584
14585 ResScalars.push_back(Res);
14586 OvScalars.push_back(Ov);
14587 }
14588
14589 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14590 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14591
14592 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14593 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14594 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14595 getBuildVector(NewOvVT, dl, OvScalars));
14596}
14597
14600 unsigned Bytes,
14601 int Dist) const {
14602 if (LD->isVolatile() || Base->isVolatile())
14603 return false;
14604 // TODO: probably too restrictive for atomics, revisit
14605 if (!LD->isSimple())
14606 return false;
14607 if (LD->isIndexed() || Base->isIndexed())
14608 return false;
14609 if (LD->getChain() != Base->getChain())
14610 return false;
14611 EVT VT = LD->getMemoryVT();
14612 if (VT.getSizeInBits() / 8 != Bytes)
14613 return false;
14614
14615 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
14616 auto LocDecomp = BaseIndexOffset::match(LD, *this);
14617
14618 int64_t Offset = 0;
14619 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
14620 return (Dist * (int64_t)Bytes == Offset);
14621 return false;
14622}
14623
14624/// InferPtrAlignment - Infer alignment of a load / store address. Return
14625/// std::nullopt if it cannot be inferred.
14627 // If this is a GlobalAddress + cst, return the alignment.
14628 const GlobalValue *GV = nullptr;
14629 int64_t GVOffset = 0;
14630 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14631 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14632 KnownBits Known(PtrWidth);
14634 unsigned AlignBits = Known.countMinTrailingZeros();
14635 if (AlignBits)
14636 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
14637 }
14638
14639 // If this is a direct reference to a stack slot, use information about the
14640 // stack slot's alignment.
14641 int FrameIdx = INT_MIN;
14642 int64_t FrameOffset = 0;
14644 FrameIdx = FI->getIndex();
14645 } else if (isBaseWithConstantOffset(Ptr) &&
14647 // Handle FI+Cst
14648 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14649 FrameOffset = Ptr.getConstantOperandVal(1);
14650 }
14651
14652 if (FrameIdx != INT_MIN) {
14654 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14655 }
14656
14657 return std::nullopt;
14658}
14659
14660/// Split the scalar node with EXTRACT_ELEMENT using the provided
14661/// VTs and return the low/high part.
14662std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14663 const SDLoc &DL,
14664 const EVT &LoVT,
14665 const EVT &HiVT) {
14666 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14667 "Split node must be a scalar type");
14668 SDValue Lo =
14670 SDValue Hi =
14672 return std::make_pair(Lo, Hi);
14673}
14674
14675/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14676/// which is split (or expanded) into two not necessarily identical pieces.
14677std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14678 // Currently all types are split in half.
14679 EVT LoVT, HiVT;
14680 if (!VT.isVector())
14681 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14682 else
14683 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14684
14685 return std::make_pair(LoVT, HiVT);
14686}
14687
14688/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14689/// type, dependent on an enveloping VT that has been split into two identical
14690/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14691std::pair<EVT, EVT>
14693 bool *HiIsEmpty) const {
14694 EVT EltTp = VT.getVectorElementType();
14695 // Examples:
14696 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14697 // custom VL=9 with enveloping VL=8/8 yields 8/1
14698 // custom VL=10 with enveloping VL=8/8 yields 8/2
14699 // etc.
14700 ElementCount VTNumElts = VT.getVectorElementCount();
14701 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14702 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14703 "Mixing fixed width and scalable vectors when enveloping a type");
14704 EVT LoVT, HiVT;
14705 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14706 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14707 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14708 *HiIsEmpty = false;
14709 } else {
14710 // Flag that hi type has zero storage size, but return split envelop type
14711 // (this would be easier if vector types with zero elements were allowed).
14712 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14713 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14714 *HiIsEmpty = true;
14715 }
14716 return std::make_pair(LoVT, HiVT);
14717}
14718
14719/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14720/// low/high part.
14721std::pair<SDValue, SDValue>
14722SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14723 const EVT &HiVT) {
14724 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14725 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14726 "Splitting vector with an invalid mixture of fixed and scalable "
14727 "vector types");
14729 N.getValueType().getVectorMinNumElements() &&
14730 "More vector elements requested than available!");
14731 SDValue Lo, Hi;
14732 Lo = getExtractSubvector(DL, LoVT, N, 0);
14733 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14734 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14735 // IDX with the runtime scaling factor of the result vector type. For
14736 // fixed-width result vectors, that runtime scaling factor is 1.
14738 return std::make_pair(Lo, Hi);
14739}
14740
14741std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14742 const SDLoc &DL) {
14743 // Split the vector length parameter.
14744 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14745 EVT VT = N.getValueType();
14747 "Expecting the mask to be an evenly-sized vector");
14748 SDValue HalfNumElts = getElementCount(
14750 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14751 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14752 return std::make_pair(Lo, Hi);
14753}
14754
14755/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14757 EVT VT = N.getValueType();
14760 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14761}
14762
14765 unsigned Start, unsigned Count,
14766 EVT EltVT) {
14767 EVT VT = Op.getValueType();
14768 if (Count == 0)
14770 if (EltVT == EVT())
14771 EltVT = VT.getVectorElementType();
14772 SDLoc SL(Op);
14773 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14774 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14775 }
14776}
14777
14778// getAddressSpace - Return the address space this GlobalAddress belongs to.
14780 return getGlobal()->getType()->getAddressSpace();
14781}
14782
14785 return Val.MachineCPVal->getType();
14786 return Val.ConstVal->getType();
14787}
14788
14789bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14790 unsigned &SplatBitSize,
14791 bool &HasAnyUndefs,
14792 unsigned MinSplatBits,
14793 bool IsBigEndian) const {
14794 EVT VT = getValueType(0);
14795 assert(VT.isVector() && "Expected a vector type");
14796 unsigned VecWidth = VT.getSizeInBits();
14797 if (MinSplatBits > VecWidth)
14798 return false;
14799
14800 // FIXME: The widths are based on this node's type, but build vectors can
14801 // truncate their operands.
14802 SplatValue = APInt(VecWidth, 0);
14803 SplatUndef = APInt(VecWidth, 0);
14804
14805 // Get the bits. Bits with undefined values (when the corresponding element
14806 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14807 // in SplatValue. If any of the values are not constant, give up and return
14808 // false.
14809 unsigned int NumOps = getNumOperands();
14810 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14811 unsigned EltWidth = VT.getScalarSizeInBits();
14812
14813 for (unsigned j = 0; j < NumOps; ++j) {
14814 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14815 SDValue OpVal = getOperand(i);
14816 unsigned BitPos = j * EltWidth;
14817
14818 if (OpVal.isUndef())
14819 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14820 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14821 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14822 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14823 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14824 else
14825 return false;
14826 }
14827
14828 // The build_vector is all constants or undefs. Find the smallest element
14829 // size that splats the vector.
14830 HasAnyUndefs = (SplatUndef != 0);
14831
14832 // FIXME: This does not work for vectors with elements less than 8 bits.
14833 while (VecWidth > 8) {
14834 // If we can't split in half, stop here.
14835 if (VecWidth & 1)
14836 break;
14837
14838 unsigned HalfSize = VecWidth / 2;
14839 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14840 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14841 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14842 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14843
14844 // If the two halves do not match (ignoring undef bits), stop here.
14845 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14846 MinSplatBits > HalfSize)
14847 break;
14848
14849 SplatValue = HighValue | LowValue;
14850 SplatUndef = HighUndef & LowUndef;
14851
14852 VecWidth = HalfSize;
14853 }
14854
14855 // FIXME: The loop above only tries to split in halves. But if the input
14856 // vector for example is <3 x i16> it wouldn't be able to detect a
14857 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14858 // optimizations. I guess that back in the days when this helper was created
14859 // vectors normally was power-of-2 sized.
14860
14861 SplatBitSize = VecWidth;
14862 return true;
14863}
14864
14866 BitVector *UndefElements) const {
14867 unsigned NumOps = getNumOperands();
14868 if (UndefElements) {
14869 UndefElements->clear();
14870 UndefElements->resize(NumOps);
14871 }
14872 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14873 if (!DemandedElts)
14874 return SDValue();
14875 SDValue Splatted;
14876 for (unsigned i = 0; i != NumOps; ++i) {
14877 if (!DemandedElts[i])
14878 continue;
14879 SDValue Op = getOperand(i);
14880 if (Op.isUndef()) {
14881 if (UndefElements)
14882 (*UndefElements)[i] = true;
14883 } else if (!Splatted) {
14884 Splatted = Op;
14885 } else if (Splatted != Op) {
14886 return SDValue();
14887 }
14888 }
14889
14890 if (!Splatted) {
14891 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14892 assert(getOperand(FirstDemandedIdx).isUndef() &&
14893 "Can only have a splat without a constant for all undefs.");
14894 return getOperand(FirstDemandedIdx);
14895 }
14896
14897 return Splatted;
14898}
14899
14901 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14902 return getSplatValue(DemandedElts, UndefElements);
14903}
14904
14906 SmallVectorImpl<SDValue> &Sequence,
14907 BitVector *UndefElements) const {
14908 unsigned NumOps = getNumOperands();
14909 Sequence.clear();
14910 if (UndefElements) {
14911 UndefElements->clear();
14912 UndefElements->resize(NumOps);
14913 }
14914 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14915 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14916 return false;
14917
14918 // Set the undefs even if we don't find a sequence (like getSplatValue).
14919 if (UndefElements)
14920 for (unsigned I = 0; I != NumOps; ++I)
14921 if (DemandedElts[I] && getOperand(I).isUndef())
14922 (*UndefElements)[I] = true;
14923
14924 // Iteratively widen the sequence length looking for repetitions.
14925 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14926 Sequence.append(SeqLen, SDValue());
14927 for (unsigned I = 0; I != NumOps; ++I) {
14928 if (!DemandedElts[I])
14929 continue;
14930 SDValue &SeqOp = Sequence[I % SeqLen];
14932 if (Op.isUndef()) {
14933 if (!SeqOp)
14934 SeqOp = Op;
14935 continue;
14936 }
14937 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14938 Sequence.clear();
14939 break;
14940 }
14941 SeqOp = Op;
14942 }
14943 if (!Sequence.empty())
14944 return true;
14945 }
14946
14947 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14948 return false;
14949}
14950
14952 BitVector *UndefElements) const {
14953 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14954 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14955}
14956
14959 BitVector *UndefElements) const {
14961 getSplatValue(DemandedElts, UndefElements));
14962}
14963
14966 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14967}
14968
14971 BitVector *UndefElements) const {
14973 getSplatValue(DemandedElts, UndefElements));
14974}
14975
14980
14981int32_t
14983 uint32_t BitWidth) const {
14984 if (ConstantFPSDNode *CN =
14986 bool IsExact;
14987 APSInt IntVal(BitWidth);
14988 const APFloat &APF = CN->getValueAPF();
14989 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14990 APFloat::opOK ||
14991 !IsExact)
14992 return -1;
14993
14994 return IntVal.exactLogBase2();
14995 }
14996 return -1;
14997}
14998
15000 bool IsLittleEndian, unsigned DstEltSizeInBits,
15001 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
15002 // Early-out if this contains anything but Undef/Constant/ConstantFP.
15003 if (!isConstant())
15004 return false;
15005
15006 unsigned NumSrcOps = getNumOperands();
15007 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15008 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15009 "Invalid bitcast scale");
15010
15011 // Extract raw src bits.
15012 SmallVector<APInt> SrcBitElements(NumSrcOps,
15013 APInt::getZero(SrcEltSizeInBits));
15014 BitVector SrcUndeElements(NumSrcOps, false);
15015
15016 for (unsigned I = 0; I != NumSrcOps; ++I) {
15018 if (Op.isUndef()) {
15019 SrcUndeElements.set(I);
15020 continue;
15021 }
15022 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15023 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15024 assert((CInt || CFP) && "Unknown constant");
15025 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15026 : CFP->getValueAPF().bitcastToAPInt();
15027 }
15028
15029 // Recast to dst width.
15030 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15031 SrcBitElements, UndefElements, SrcUndeElements);
15032 return true;
15033}
15034
15035void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15036 unsigned DstEltSizeInBits,
15037 SmallVectorImpl<APInt> &DstBitElements,
15038 ArrayRef<APInt> SrcBitElements,
15039 BitVector &DstUndefElements,
15040 const BitVector &SrcUndefElements) {
15041 unsigned NumSrcOps = SrcBitElements.size();
15042 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15043 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15044 "Invalid bitcast scale");
15045 assert(NumSrcOps == SrcUndefElements.size() &&
15046 "Vector size mismatch");
15047
15048 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15049 DstUndefElements.clear();
15050 DstUndefElements.resize(NumDstOps, false);
15051 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15052
15053 // Concatenate src elements constant bits together into dst element.
15054 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15055 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15056 for (unsigned I = 0; I != NumDstOps; ++I) {
15057 DstUndefElements.set(I);
15058 APInt &DstBits = DstBitElements[I];
15059 for (unsigned J = 0; J != Scale; ++J) {
15060 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15061 if (SrcUndefElements[Idx])
15062 continue;
15063 DstUndefElements.reset(I);
15064 const APInt &SrcBits = SrcBitElements[Idx];
15065 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15066 "Illegal constant bitwidths");
15067 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15068 }
15069 }
15070 return;
15071 }
15072
15073 // Split src element constant bits into dst elements.
15074 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15075 for (unsigned I = 0; I != NumSrcOps; ++I) {
15076 if (SrcUndefElements[I]) {
15077 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15078 continue;
15079 }
15080 const APInt &SrcBits = SrcBitElements[I];
15081 for (unsigned J = 0; J != Scale; ++J) {
15082 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15083 APInt &DstBits = DstBitElements[Idx];
15084 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15085 }
15086 }
15087}
15088
15090 for (const SDValue &Op : op_values()) {
15091 unsigned Opc = Op.getOpcode();
15092 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15093 return false;
15094 }
15095 return true;
15096}
15097
15098std::optional<std::pair<APInt, APInt>>
15100 unsigned NumOps = getNumOperands();
15101 if (NumOps < 2)
15102 return std::nullopt;
15103
15104 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15105 APInt Start, Stride;
15106 int FirstIdx = -1, SecondIdx = -1;
15107
15108 // Find the first two non-undef constant elements to determine Start and
15109 // Stride, then verify all remaining elements match the sequence.
15110 for (unsigned I = 0; I < NumOps; ++I) {
15112 if (Op->isUndef())
15113 continue;
15114 if (!isa<ConstantSDNode>(Op))
15115 return std::nullopt;
15116
15117 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15118 if (FirstIdx < 0) {
15119 FirstIdx = I;
15120 Start = Val;
15121 } else if (SecondIdx < 0) {
15122 SecondIdx = I;
15123 // Compute stride using modular arithmetic. Simple division would handle
15124 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15125 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15126 // Note that modular arithmetic is agnostic to signed/unsigned.
15127 unsigned IdxDiff = I - FirstIdx;
15128 APInt ValDiff = Val - Start;
15129
15130 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15131 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15132 if (ValDiff.countr_zero() < CommonPow2Bits)
15133 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15134 IdxDiff >>= CommonPow2Bits;
15135 ValDiff.lshrInPlace(CommonPow2Bits);
15136
15137 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15138 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15139 // one, but we could try all candidates to handle more cases.
15140 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15141 if (Stride.isZero())
15142 return std::nullopt;
15143
15144 // Step 3: Adjust Start based on the first defined element's index.
15145 Start -= Stride * FirstIdx;
15146 } else {
15147 // Verify this element matches the sequence.
15148 if (Val != Start + Stride * I)
15149 return std::nullopt;
15150 }
15151 }
15152
15153 // Need at least two defined elements.
15154 if (SecondIdx < 0)
15155 return std::nullopt;
15156
15157 return std::make_pair(Start, Stride);
15158}
15159
15161 // Find the first non-undef value in the shuffle mask.
15162 unsigned i, e;
15163 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15164 /* search */;
15165
15166 // If all elements are undefined, this shuffle can be considered a splat
15167 // (although it should eventually get simplified away completely).
15168 if (i == e)
15169 return true;
15170
15171 // Make sure all remaining elements are either undef or the same as the first
15172 // non-undef value.
15173 for (int Idx = Mask[i]; i != e; ++i)
15174 if (Mask[i] >= 0 && Mask[i] != Idx)
15175 return false;
15176 return true;
15177}
15178
15179// Returns true if it is a constant integer BuildVector or constant integer,
15180// possibly hidden by a bitcast.
15182 SDValue N, bool AllowOpaques) const {
15184
15185 if (auto *C = dyn_cast<ConstantSDNode>(N))
15186 return AllowOpaques || !C->isOpaque();
15187
15189 return true;
15190
15191 // Treat a GlobalAddress supporting constant offset folding as a
15192 // constant integer.
15193 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15194 if (GA->getOpcode() == ISD::GlobalAddress &&
15195 TLI->isOffsetFoldingLegal(GA))
15196 return true;
15197
15198 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15199 isa<ConstantSDNode>(N.getOperand(0)))
15200 return true;
15201 return false;
15202}
15203
15204// Returns true if it is a constant float BuildVector or constant float.
15207 return true;
15208
15210 return true;
15211
15212 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15213 isa<ConstantFPSDNode>(N.getOperand(0)))
15214 return true;
15215
15216 return false;
15217}
15218
15219std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15220 ConstantSDNode *Const =
15221 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15222 if (!Const)
15223 return std::nullopt;
15224
15225 EVT VT = N->getValueType(0);
15226 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15227 switch (TLI->getBooleanContents(N.getValueType())) {
15229 if (CVal.isOne())
15230 return true;
15231 if (CVal.isZero())
15232 return false;
15233 return std::nullopt;
15235 if (CVal.isAllOnes())
15236 return true;
15237 if (CVal.isZero())
15238 return false;
15239 return std::nullopt;
15241 return CVal[0];
15242 }
15243 llvm_unreachable("Unknown BooleanContent enum");
15244}
15245
15246void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15247 assert(!Node->OperandList && "Node already has operands");
15249 "too many operands to fit into SDNode");
15250 SDUse *Ops = OperandRecycler.allocate(
15251 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15252
15253 bool IsDivergent = false;
15254 for (unsigned I = 0; I != Vals.size(); ++I) {
15255 Ops[I].setUser(Node);
15256 Ops[I].setInitial(Vals[I]);
15257 EVT VT = Ops[I].getValueType();
15258
15259 // Skip Chain. It does not carry divergence.
15260 if (VT != MVT::Other &&
15261 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15262 Ops[I].getNode()->isDivergent()) {
15263 IsDivergent = true;
15264 }
15265 }
15266 Node->NumOperands = Vals.size();
15267 Node->OperandList = Ops;
15268 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15269 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15270 Node->SDNodeBits.IsDivergent = IsDivergent;
15271 }
15272 checkForCycles(Node);
15273}
15274
15277 size_t Limit = SDNode::getMaxNumOperands();
15278 while (Vals.size() > Limit) {
15279 unsigned SliceIdx = Vals.size() - Limit;
15280 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15281 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15282 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15283 Vals.emplace_back(NewTF);
15284 }
15285 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15286}
15287
15289 EVT VT, SDNodeFlags Flags) {
15290 switch (Opcode) {
15291 default:
15292 return SDValue();
15293 case ISD::ADD:
15294 case ISD::OR:
15295 case ISD::XOR:
15296 case ISD::UMAX:
15297 case ISD::MUL:
15298 case ISD::AND:
15299 case ISD::UMIN:
15300 case ISD::SMAX:
15301 case ISD::SMIN:
15303 VT);
15304 case ISD::FADD:
15305 // If flags allow, prefer positive zero since it's generally cheaper
15306 // to materialize on most targets.
15307 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15308 case ISD::FMUL:
15309 return getConstantFP(1.0, DL, VT);
15310 case ISD::FMINNUM:
15311 case ISD::FMAXNUM: {
15312 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
15313 const fltSemantics &Semantics = VT.getFltSemantics();
15314 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15315 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15316 APFloat::getLargest(Semantics);
15317 if (Opcode == ISD::FMAXNUM)
15318 NeutralAF.changeSign();
15319
15320 return getConstantFP(NeutralAF, DL, VT);
15321 }
15322 case ISD::FMINIMUM:
15323 case ISD::FMAXIMUM: {
15324 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15325 const fltSemantics &Semantics = VT.getFltSemantics();
15326 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15327 : APFloat::getLargest(Semantics);
15328 if (Opcode == ISD::FMAXIMUM)
15329 NeutralAF.changeSign();
15330
15331 return getConstantFP(NeutralAF, DL, VT);
15332 }
15333
15334 }
15335}
15336
15338 SDValue Acc, SDValue LHS,
15339 SDValue RHS) {
15340 EVT AccVT = Acc.getValueType();
15341 if (AccVT.isFloatingPoint()) {
15342 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15343 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15344 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15345 }
15347 "Unexpected opcode");
15348 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15349 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15350 return getNegative(MLA, DL, AccVT);
15351}
15352
15353/// Helper used to make a call to a library function that has one argument of
15354/// pointer type.
15355///
15356/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15357/// used to get or set floating-point state. They have one argument of pointer
15358/// type, which points to the memory region containing bits of the
15359/// floating-point state. The value returned by such function is ignored in the
15360/// created call.
15361///
15362/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15363/// \param Ptr Pointer used to save/load state.
15364/// \param InChain Ingoing token chain.
15365/// \returns Outgoing chain token.
15367 SDValue InChain,
15368 const SDLoc &DLoc) {
15369 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15371 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15372 RTLIB::LibcallImpl LibcallImpl =
15373 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15374 if (LibcallImpl == RTLIB::Unsupported)
15375 reportFatalUsageError("emitting call to unsupported libcall");
15376
15377 SDValue Callee =
15378 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15380 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
15381 Libcalls->getLibcallImplCallingConv(LibcallImpl),
15382 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15383 return TLI->LowerCallTo(CLI).second;
15384}
15385
15387 assert(From && To && "Invalid SDNode; empty source SDValue?");
15388 auto I = SDEI.find(From);
15389 if (I == SDEI.end())
15390 return;
15391
15392 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15393 // the iterator, hence the need to make a copy to prevent a use-after-free.
15394 NodeExtraInfo NEI = I->second;
15395 if (LLVM_LIKELY(!NEI.PCSections)) {
15396 // No deep copy required for the types of extra info set.
15397 //
15398 // FIXME: Investigate if other types of extra info also need deep copy. This
15399 // depends on the types of nodes they can be attached to: if some extra info
15400 // is only ever attached to nodes where a replacement To node is always the
15401 // node where later use and propagation of the extra info has the intended
15402 // semantics, no deep copy is required.
15403 SDEI[To] = std::move(NEI);
15404 return;
15405 }
15406
15407 const SDNode *EntrySDN = getEntryNode().getNode();
15408
15409 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15410 // through the replacement of From with To. Otherwise, replacements of a node
15411 // (From) with more complex nodes (To and its operands) may result in lost
15412 // extra info where the root node (To) is insignificant in further propagating
15413 // and using extra info when further lowering to MIR.
15414 //
15415 // In the first step pre-populate the visited set with the nodes reachable
15416 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15417 // DAG that is not new and should be left untouched.
15418 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15419 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15420 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15421 if (MaxDepth == 0) {
15422 // Remember this node in case we need to increase MaxDepth and continue
15423 // populating FromReach from this node.
15424 Leafs.emplace_back(N);
15425 return;
15426 }
15427 if (!FromReach.insert(N).second)
15428 return;
15429 for (const SDValue &Op : N->op_values())
15430 Self(Self, Op.getNode(), MaxDepth - 1);
15431 };
15432
15433 // Copy extra info to To and all its transitive operands (that are new).
15435 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15436 if (FromReach.contains(N))
15437 return true;
15438 if (!Visited.insert(N).second)
15439 return true;
15440 if (EntrySDN == N)
15441 return false;
15442 for (const SDValue &Op : N->op_values()) {
15443 if (N == To && Op.getNode() == EntrySDN) {
15444 // Special case: New node's operand is the entry node; just need to
15445 // copy extra info to new node.
15446 break;
15447 }
15448 if (!Self(Self, Op.getNode()))
15449 return false;
15450 }
15451 // Copy only if entry node was not reached.
15452 SDEI[N] = std::move(NEI);
15453 return true;
15454 };
15455
15456 // We first try with a lower MaxDepth, assuming that the path to common
15457 // operands between From and To is relatively short. This significantly
15458 // improves performance in the common case. The initial MaxDepth is big
15459 // enough to avoid retry in the common case; the last MaxDepth is large
15460 // enough to avoid having to use the fallback below (and protects from
15461 // potential stack exhaustion from recursion).
15462 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15463 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15464 // StartFrom is the previous (or initial) set of leafs reachable at the
15465 // previous maximum depth.
15467 std::swap(StartFrom, Leafs);
15468 for (const SDNode *N : StartFrom)
15469 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15470 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15471 return;
15472 // This should happen very rarely (reached the entry node).
15473 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15474 assert(!Leafs.empty());
15475 }
15476
15477 // This should not happen - but if it did, that means the subgraph reachable
15478 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15479 // could not visit all reachable common operands. Consequently, we were able
15480 // to reach the entry node.
15481 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15482 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15483 // Best-effort fallback if assertions disabled.
15484 SDEI[To] = std::move(NEI);
15485}
15486
15487#ifndef NDEBUG
15488static void checkForCyclesHelper(const SDNode *N,
15491 const llvm::SelectionDAG *DAG) {
15492 // If this node has already been checked, don't check it again.
15493 if (Checked.count(N))
15494 return;
15495
15496 // If a node has already been visited on this depth-first walk, reject it as
15497 // a cycle.
15498 if (!Visited.insert(N).second) {
15499 errs() << "Detected cycle in SelectionDAG\n";
15500 dbgs() << "Offending node:\n";
15501 N->dumprFull(DAG); dbgs() << "\n";
15502 abort();
15503 }
15504
15505 for (const SDValue &Op : N->op_values())
15506 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15507
15508 Checked.insert(N);
15509 Visited.erase(N);
15510}
15511#endif
15512
15514 const llvm::SelectionDAG *DAG,
15515 bool force) {
15516#ifndef NDEBUG
15517 bool check = force;
15518#ifdef EXPENSIVE_CHECKS
15519 check = true;
15520#endif // EXPENSIVE_CHECKS
15521 if (check) {
15522 assert(N && "Checking nonexistent SDNode");
15525 checkForCyclesHelper(N, visited, checked, DAG);
15526 }
15527#endif // !NDEBUG
15528}
15529
15530void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15531 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15532}
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
Function Alias Analysis Results
#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.
SI Fold Operands
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 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 getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo, BatchAAResults *BatchAA, const MDNode *DstMemCacheHint, const MDNode *SrcMemCacheHint)
static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
static void removeOperands(MachineInstr &MI, unsigned i)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static unsigned getSize(unsigned Kind)
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h: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:5934
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1286
bool isNegative() const
Definition APFloat.h:1575
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
bool isLargest() const
Definition APFloat.h:1591
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
bool isInfinity() const
Definition APFloat.h:1572
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.
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h: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 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 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
bool hasSwiftErrorArg() 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 getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
LLVM_ABI std::pair< SDValue, SDValue > getStrcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, const CallInst *CI)
Lower a strcpy operation into a target library call and return the resulting chain and call result as...
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const
Test whether the given value is a constant FP or similar node.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getPartialReduceMLS(unsigned Opc, const SDLoc &DL, SDValue Acc, SDValue LHS, SDValue RHS)
Get an expression that implements a partial multiply-subtract reduction.
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(SDValue Op, bool ForSigned, unsigned Depth=0) const
Combine constant ranges from computeConstantRange() and computeKnownBits().
const SelectionDAGTargetInfo & getSelectionDAGInfo() const
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDDbgLabel * getDbgLabel(DILabel *Label, const DebugLoc &DL, unsigned O)
Creates a SDDbgLabel node.
LLVM_ABI SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI OverflowKind computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const
Determine if the result of the unsigned mul of 2 nodes can overflow.
LLVM_ABI void copyExtraInfo(SDNode *From, SDNode *To)
Copy extra info associated with one node to another.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI SDValue getLoadFFVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachineMemOperand *MMO)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
LLVM_ABI std::pair< SDValue, SDValue > getMemcmp(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, const CallInst *CI)
Lower a memcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, const SDLoc &DLoc)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getSrcValue(const Value *v)
Construct a node to track a Value* through the backend.
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const
Determine if the result of the signed mul of 2 nodes can overflow.
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
LLVM_ABI void dump() const
Dump the textual format of this DAG.
LLVM_ABI bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if '(Op & Mask) == Mask'.
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI void AddDbgLabel(SDDbgLabel *DB)
Add a dbg_label SDNode.
bool isConstantValueOfAnyType(SDValue N) const
LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, bool ConsiderFlags=true, unsigned Depth=0) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDDbgValue * getVRegDbgValue(DIVariable *Var, DIExpression *Expr, Register VReg, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a VReg SDDbgValue node.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI KnownFPClass computeKnownFPClass(SDValue Op, FPClassTest InterestedClasses, unsigned Depth=0) const
Determine floating-point class information about Op.
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI SDValue getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI std::optional< unsigned > getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI std::pair< SDValue, SDValue > SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL)
Split the explicit vector length parameter of a VP operation.
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue 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)
LLVM_ABI unsigned rot(unsigned SrcSignBits, unsigned BitWidth, std::optional< APInt > RotAmt, bool IsRotateRight)
Compute the number of sign bits after rotating a value.
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h: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 const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI SDValue peekThroughTruncates(SDValue V)
Return the non-truncated source operand of V if it exists.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI SDValue peekThroughOneUseBitcasts(SDValue V)
Return the non-bitcasted and one-use source operand of V if it exists.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:149
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
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.
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI bool isDereferenceable(unsigned Size, LLVMContext &C, const DataLayout &DL) const
Return true if memory region [V, V+Offset+Size) is known to be dereferenceable.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
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)