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 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
366 return true;
367
368 EVT SVT = Op.getValueType().getScalarType();
369 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
370 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
371 continue;
372
373 if (AllowUndefs && Op.getOperand(i).isUndef()) {
374 if (!Match(nullptr))
375 return false;
376 continue;
377 }
378
379 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
380 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
381 !Match(Cst))
382 return false;
383 }
384 return true;
385}
386// Build used template types.
388 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
390 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
391 bool);
392
394 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
395 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
396 bool AllowUndefs, bool AllowTypeMismatch) {
397 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
398 return false;
399
400 // TODO: Add support for scalar UNDEF cases?
401 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
402 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
403 return Match(LHSCst, RHSCst);
404
405 // TODO: Add support for vector UNDEF cases?
406 if (LHS.getOpcode() != RHS.getOpcode() ||
407 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
408 LHS.getOpcode() != ISD::SPLAT_VECTOR))
409 return false;
410
411 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
412 return true;
413
414 EVT SVT = LHS.getValueType().getScalarType();
415 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
416 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
417 continue;
418 SDValue LHSOp = LHS.getOperand(i);
419 SDValue RHSOp = RHS.getOperand(i);
420 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
421 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
422 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
423 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
424 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
425 return false;
426 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
427 LHSOp.getValueType() != RHSOp.getValueType()))
428 return false;
429 if (!Match(LHSCst, RHSCst))
430 return false;
431 }
432 return true;
433}
434
436 switch (MinMaxOpc) {
437 default:
438 llvm_unreachable("unrecognized opcode");
439 case ISD::UMIN:
440 return ISD::UMAX;
441 case ISD::UMAX:
442 return ISD::UMIN;
443 case ISD::SMIN:
444 return ISD::SMAX;
445 case ISD::SMAX:
446 return ISD::SMIN;
447 }
448}
449
451 switch (MinMaxOpc) {
452 default:
453 llvm_unreachable("unrecognized min/max opcode");
454 case ISD::SMIN:
455 return ISD::UMIN;
456 case ISD::SMAX:
457 return ISD::UMAX;
458 case ISD::UMIN:
459 return ISD::SMIN;
460 case ISD::UMAX:
461 return ISD::SMAX;
462 }
463}
464
466 switch (VecReduceOpcode) {
467 default:
468 llvm_unreachable("Expected VECREDUCE opcode");
471 case ISD::VP_REDUCE_FADD:
472 case ISD::VP_REDUCE_SEQ_FADD:
473 return ISD::FADD;
476 case ISD::VP_REDUCE_FMUL:
477 case ISD::VP_REDUCE_SEQ_FMUL:
478 return ISD::FMUL;
480 case ISD::VP_REDUCE_ADD:
481 return ISD::ADD;
483 case ISD::VP_REDUCE_MUL:
484 return ISD::MUL;
486 case ISD::VP_REDUCE_AND:
487 return ISD::AND;
489 case ISD::VP_REDUCE_OR:
490 return ISD::OR;
492 case ISD::VP_REDUCE_XOR:
493 return ISD::XOR;
495 case ISD::VP_REDUCE_SMAX:
496 return ISD::SMAX;
498 case ISD::VP_REDUCE_SMIN:
499 return ISD::SMIN;
501 case ISD::VP_REDUCE_UMAX:
502 return ISD::UMAX;
504 case ISD::VP_REDUCE_UMIN:
505 return ISD::UMIN;
507 case ISD::VP_REDUCE_FMAX:
508 return ISD::FMAXNUM;
510 case ISD::VP_REDUCE_FMIN:
511 return ISD::FMINNUM;
513 case ISD::VP_REDUCE_FMAXIMUM:
514 return ISD::FMAXIMUM;
516 case ISD::VP_REDUCE_FMINIMUM:
517 return ISD::FMINIMUM;
518 }
519}
520
522 switch (MaskedOpc) {
523 case ISD::MASKED_UDIV:
524 return ISD::UDIV;
525 case ISD::MASKED_SDIV:
526 return ISD::SDIV;
527 case ISD::MASKED_UREM:
528 return ISD::UREM;
529 case ISD::MASKED_SREM:
530 return ISD::SREM;
531 default:
532 llvm_unreachable("Expected masked binop opcode");
533 }
534}
535
536bool ISD::isVPOpcode(unsigned Opcode) {
537 switch (Opcode) {
538 default:
539 return false;
540#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
541 case ISD::VPSD: \
542 return true;
543#include "llvm/IR/VPIntrinsics.def"
544 }
545}
546
547bool ISD::isVPBinaryOp(unsigned Opcode) {
548 switch (Opcode) {
549 default:
550 break;
551#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
552#define VP_PROPERTY_BINARYOP return true;
553#define END_REGISTER_VP_SDNODE(VPSD) break;
554#include "llvm/IR/VPIntrinsics.def"
555 }
556 return false;
557}
558
559bool ISD::isVPReduction(unsigned Opcode) {
560 switch (Opcode) {
561 default:
562 return false;
563 case ISD::VP_REDUCE_ADD:
564 case ISD::VP_REDUCE_MUL:
565 case ISD::VP_REDUCE_AND:
566 case ISD::VP_REDUCE_OR:
567 case ISD::VP_REDUCE_XOR:
568 case ISD::VP_REDUCE_SMAX:
569 case ISD::VP_REDUCE_SMIN:
570 case ISD::VP_REDUCE_UMAX:
571 case ISD::VP_REDUCE_UMIN:
572 case ISD::VP_REDUCE_FMAX:
573 case ISD::VP_REDUCE_FMIN:
574 case ISD::VP_REDUCE_FMAXIMUM:
575 case ISD::VP_REDUCE_FMINIMUM:
576 case ISD::VP_REDUCE_FADD:
577 case ISD::VP_REDUCE_FMUL:
578 case ISD::VP_REDUCE_SEQ_FADD:
579 case ISD::VP_REDUCE_SEQ_FMUL:
580 return true;
581 }
582}
583
584/// The operand position of the vector mask.
585std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
586 switch (Opcode) {
587 default:
588 return std::nullopt;
589#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
590 case ISD::VPSD: \
591 return MASKPOS;
592#include "llvm/IR/VPIntrinsics.def"
593 }
594}
595
596/// The operand position of the explicit vector length parameter.
597std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
598 switch (Opcode) {
599 default:
600 return std::nullopt;
601#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
602 case ISD::VPSD: \
603 return EVLPOS;
604#include "llvm/IR/VPIntrinsics.def"
605 }
606}
607
608std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
609 bool hasFPExcept) {
610 // FIXME: Return strict opcodes in case of fp exceptions.
611 switch (VPOpcode) {
612 default:
613 return std::nullopt;
614#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
615#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
616#define END_REGISTER_VP_SDNODE(VPOPC) break;
617#include "llvm/IR/VPIntrinsics.def"
618 }
619 return std::nullopt;
620}
621
622std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
623 switch (Opcode) {
624 default:
625 return std::nullopt;
626#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
627#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
628#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
629#include "llvm/IR/VPIntrinsics.def"
630 }
631}
632
634 switch (ExtType) {
635 case ISD::EXTLOAD:
636 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
637 case ISD::SEXTLOAD:
638 return ISD::SIGN_EXTEND;
639 case ISD::ZEXTLOAD:
640 return ISD::ZERO_EXTEND;
641 default:
642 break;
643 }
644
645 llvm_unreachable("Invalid LoadExtType");
646}
647
649 // To perform this operation, we just need to swap the L and G bits of the
650 // operation.
651 unsigned OldL = (Operation >> 2) & 1;
652 unsigned OldG = (Operation >> 1) & 1;
653 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
654 (OldL << 1) | // New G bit
655 (OldG << 2)); // New L bit.
656}
657
659 unsigned Operation = Op;
660 if (isIntegerLike)
661 Operation ^= 7; // Flip L, G, E bits, but not U.
662 else
663 Operation ^= 15; // Flip all of the condition bits.
664
666 Operation &= ~8; // Don't let N and U bits get set.
667
668 return ISD::CondCode(Operation);
669}
670
674
676 bool isIntegerLike) {
677 return getSetCCInverseImpl(Op, isIntegerLike);
678}
679
680/// For an integer comparison, return 1 if the comparison is a signed operation
681/// and 2 if the result is an unsigned comparison. Return zero if the operation
682/// does not depend on the sign of the input (setne and seteq).
683static int isSignedOp(ISD::CondCode Opcode) {
684 switch (Opcode) {
685 default: llvm_unreachable("Illegal integer setcc operation!");
686 case ISD::SETEQ:
687 case ISD::SETNE: return 0;
688 case ISD::SETLT:
689 case ISD::SETLE:
690 case ISD::SETGT:
691 case ISD::SETGE: return 1;
692 case ISD::SETULT:
693 case ISD::SETULE:
694 case ISD::SETUGT:
695 case ISD::SETUGE: return 2;
696 }
697}
698
700 EVT Type) {
701 bool IsInteger = Type.isInteger();
702 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
703 // Cannot fold a signed integer setcc with an unsigned integer setcc.
704 return ISD::SETCC_INVALID;
705
706 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
707
708 // If the N and U bits get set, then the resultant comparison DOES suddenly
709 // care about orderedness, and it is true when ordered.
710 if (Op > ISD::SETTRUE2)
711 Op &= ~16; // Clear the U bit if the N bit is set.
712
713 // Canonicalize illegal integer setcc's.
714 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
715 Op = ISD::SETNE;
716
717 return ISD::CondCode(Op);
718}
719
721 EVT Type) {
722 bool IsInteger = Type.isInteger();
723 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
724 // Cannot fold a signed setcc with an unsigned setcc.
725 return ISD::SETCC_INVALID;
726
727 // Combine all of the condition bits.
728 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
729
730 // Canonicalize illegal integer setcc's.
731 if (IsInteger) {
732 switch (Result) {
733 default: break;
734 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
735 case ISD::SETOEQ: // SETEQ & SETU[LG]E
736 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
737 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
738 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
739 }
740 }
741
742 return Result;
743}
744
745//===----------------------------------------------------------------------===//
746// SDNode Profile Support
747//===----------------------------------------------------------------------===//
748
749/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
750static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
751 ID.AddInteger(OpC);
752}
753
754/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
755/// solely with their pointer.
757 ID.AddPointer(VTList.VTs);
758}
759
760/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
763 for (const auto &Op : Ops) {
764 ID.AddPointer(Op.getNode());
765 ID.AddInteger(Op.getResNo());
766 }
767}
768
769/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
772 for (const auto &Op : Ops) {
773 ID.AddPointer(Op.getNode());
774 ID.AddInteger(Op.getResNo());
775 }
776}
777
778static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
779 SDVTList VTList, ArrayRef<SDValue> OpList) {
780 AddNodeIDOpcode(ID, OpC);
781 AddNodeIDValueTypes(ID, VTList);
782 AddNodeIDOperands(ID, OpList);
783}
784
785/// If this is an SDNode with special info, add this info to the NodeID data.
786static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
787 switch (N->getOpcode()) {
790 case ISD::MCSymbol:
791 llvm_unreachable("Should only be used on nodes with operands");
792 default: break; // Normal nodes don't need extra info.
794 case ISD::Constant: {
796 ID.AddPointer(C->getConstantIntValue());
797 ID.AddBoolean(C->isOpaque());
798 break;
799 }
801 case ISD::ConstantFP:
802 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
803 break;
809 ID.AddPointer(GA->getGlobal());
810 ID.AddInteger(GA->getOffset());
811 ID.AddInteger(GA->getTargetFlags());
812 break;
813 }
814 case ISD::BasicBlock:
815 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
816 break;
817 case ISD::Register:
818 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
819 break;
821 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
822 break;
823 case ISD::SRCVALUE:
824 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
825 break;
826 case ISD::FrameIndex:
828 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
829 break;
831 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
832 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
833 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
834 break;
835 case ISD::JumpTable:
837 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
838 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
839 break;
843 ID.AddInteger(CP->getAlign().value());
844 ID.AddInteger(CP->getOffset());
847 else
848 ID.AddPointer(CP->getConstVal());
849 ID.AddInteger(CP->getTargetFlags());
850 break;
851 }
852 case ISD::TargetIndex: {
854 ID.AddInteger(TI->getIndex());
855 ID.AddInteger(TI->getOffset());
856 ID.AddInteger(TI->getTargetFlags());
857 break;
858 }
859 case ISD::LOAD: {
860 const LoadSDNode *LD = cast<LoadSDNode>(N);
861 ID.AddInteger(LD->getMemoryVT().getRawBits());
862 ID.AddInteger(LD->getRawSubclassData());
863 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
864 ID.AddInteger(LD->getMemOperand()->getFlags());
865 break;
866 }
867 case ISD::STORE: {
868 const StoreSDNode *ST = cast<StoreSDNode>(N);
869 ID.AddInteger(ST->getMemoryVT().getRawBits());
870 ID.AddInteger(ST->getRawSubclassData());
871 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
872 ID.AddInteger(ST->getMemOperand()->getFlags());
873 break;
874 }
875 case ISD::VP_LOAD: {
876 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
877 ID.AddInteger(ELD->getMemoryVT().getRawBits());
878 ID.AddInteger(ELD->getRawSubclassData());
879 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
880 ID.AddInteger(ELD->getMemOperand()->getFlags());
881 break;
882 }
883 case ISD::VP_LOAD_FF: {
884 const auto *LD = cast<VPLoadFFSDNode>(N);
885 ID.AddInteger(LD->getMemoryVT().getRawBits());
886 ID.AddInteger(LD->getRawSubclassData());
887 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
888 ID.AddInteger(LD->getMemOperand()->getFlags());
889 break;
890 }
891 case ISD::VP_STORE: {
892 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
893 ID.AddInteger(EST->getMemoryVT().getRawBits());
894 ID.AddInteger(EST->getRawSubclassData());
895 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
896 ID.AddInteger(EST->getMemOperand()->getFlags());
897 break;
898 }
899 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
901 ID.AddInteger(SLD->getMemoryVT().getRawBits());
902 ID.AddInteger(SLD->getRawSubclassData());
903 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
904 break;
905 }
906 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
908 ID.AddInteger(SST->getMemoryVT().getRawBits());
909 ID.AddInteger(SST->getRawSubclassData());
910 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
911 break;
912 }
913 case ISD::VP_GATHER: {
915 ID.AddInteger(EG->getMemoryVT().getRawBits());
916 ID.AddInteger(EG->getRawSubclassData());
917 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
918 ID.AddInteger(EG->getMemOperand()->getFlags());
919 break;
920 }
921 case ISD::VP_SCATTER: {
923 ID.AddInteger(ES->getMemoryVT().getRawBits());
924 ID.AddInteger(ES->getRawSubclassData());
925 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
926 ID.AddInteger(ES->getMemOperand()->getFlags());
927 break;
928 }
929 case ISD::MLOAD: {
931 ID.AddInteger(MLD->getMemoryVT().getRawBits());
932 ID.AddInteger(MLD->getRawSubclassData());
933 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
934 ID.AddInteger(MLD->getMemOperand()->getFlags());
935 break;
936 }
937 case ISD::MSTORE: {
939 ID.AddInteger(MST->getMemoryVT().getRawBits());
940 ID.AddInteger(MST->getRawSubclassData());
941 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
942 ID.AddInteger(MST->getMemOperand()->getFlags());
943 break;
944 }
945 case ISD::MGATHER: {
947 ID.AddInteger(MG->getMemoryVT().getRawBits());
948 ID.AddInteger(MG->getRawSubclassData());
949 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
950 ID.AddInteger(MG->getMemOperand()->getFlags());
951 break;
952 }
953 case ISD::MSCATTER: {
955 ID.AddInteger(MS->getMemoryVT().getRawBits());
956 ID.AddInteger(MS->getRawSubclassData());
957 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
958 ID.AddInteger(MS->getMemOperand()->getFlags());
959 break;
960 }
963 case ISD::ATOMIC_SWAP:
975 case ISD::ATOMIC_LOAD:
976 case ISD::ATOMIC_STORE: {
977 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
978 ID.AddInteger(AT->getMemoryVT().getRawBits());
979 ID.AddInteger(AT->getRawSubclassData());
980 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
981 ID.AddInteger(AT->getMemOperand()->getFlags());
982 break;
983 }
984 case ISD::VECTOR_SHUFFLE: {
985 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
986 for (int M : Mask)
987 ID.AddInteger(M);
988 break;
989 }
990 case ISD::ADDRSPACECAST: {
992 ID.AddInteger(ASC->getSrcAddressSpace());
993 ID.AddInteger(ASC->getDestAddressSpace());
994 break;
995 }
997 case ISD::BlockAddress: {
999 ID.AddPointer(BA->getBlockAddress());
1000 ID.AddInteger(BA->getOffset());
1001 ID.AddInteger(BA->getTargetFlags());
1002 break;
1003 }
1004 case ISD::AssertAlign:
1005 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
1006 break;
1007 case ISD::PREFETCH:
1010 // Handled by MemIntrinsicSDNode check after the switch.
1011 break;
1012 case ISD::MDNODE_SDNODE:
1013 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
1014 break;
1015 } // end switch (N->getOpcode())
1016
1017 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
1018 // to check.
1019 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
1020 ID.AddInteger(MN->getRawSubclassData());
1021 ID.AddInteger(MN->getMemoryVT().getRawBits());
1022 for (const MachineMemOperand *MMO : MN->memoperands()) {
1023 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1024 ID.AddInteger(MMO->getFlags());
1025 }
1026 }
1027}
1028
1029/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
1030/// data.
1031static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1032 AddNodeIDOpcode(ID, N->getOpcode());
1033 // Add the return value info.
1034 AddNodeIDValueTypes(ID, N->getVTList());
1035 // Add the operand info.
1036 AddNodeIDOperands(ID, N->ops());
1037
1038 // Handle SDNode leafs with special info.
1039 AddNodeIDCustom(ID, N);
1040}
1041
1042//===----------------------------------------------------------------------===//
1043// SelectionDAG Class
1044//===----------------------------------------------------------------------===//
1045
1046/// doNotCSE - Return true if CSE should not be performed for this node.
1047static bool doNotCSE(SDNode *N) {
1048 if (N->getValueType(0) == MVT::Glue)
1049 return true; // Never CSE anything that produces a glue result.
1050
1051 switch (N->getOpcode()) {
1052 default: break;
1053 case ISD::HANDLENODE:
1054 case ISD::EH_LABEL:
1055 return true; // Never CSE these nodes.
1056 }
1057
1058 // Check that remaining values produced are not flags.
1059 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1060 if (N->getValueType(i) == MVT::Glue)
1061 return true; // Never CSE anything that produces a glue result.
1062
1063 return false;
1064}
1065
1066/// Construct a DemandedElts mask which demands all elements of \p V.
1067/// If \p V is not a fixed-length vector, then this will return a single bit.
1069 EVT VT = V.getValueType();
1070 // Since the number of lanes in a scalable vector is unknown at compile time,
1071 // we track one bit which is implicitly broadcast to all lanes. This means
1072 // that all lanes in a scalable vector are considered demanded.
1074 : APInt(1, 1);
1075}
1076
1077/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1078/// SelectionDAG.
1080 // Create a dummy node (which is not added to allnodes), that adds a reference
1081 // to the root node, preventing it from being deleted.
1082 HandleSDNode Dummy(getRoot());
1083
1084 SmallVector<SDNode*, 128> DeadNodes;
1085
1086 // Add all obviously-dead nodes to the DeadNodes worklist.
1087 for (SDNode &Node : allnodes())
1088 if (Node.use_empty())
1089 DeadNodes.push_back(&Node);
1090
1091 RemoveDeadNodes(DeadNodes);
1092
1093 // If the root changed (e.g. it was a dead load, update the root).
1094 setRoot(Dummy.getValue());
1095}
1096
1097/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1098/// given list, and any nodes that become unreachable as a result.
1100
1101 // Process the worklist, deleting the nodes and adding their uses to the
1102 // worklist.
1103 while (!DeadNodes.empty()) {
1104 SDNode *N = DeadNodes.pop_back_val();
1105 // Skip to next node if we've already managed to delete the node. This could
1106 // happen if replacing a node causes a node previously added to the node to
1107 // be deleted.
1108 if (N->getOpcode() == ISD::DELETED_NODE)
1109 continue;
1110
1111 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1112 DUL->NodeDeleted(N, nullptr);
1113
1114 // Take the node out of the appropriate CSE map.
1115 RemoveNodeFromCSEMaps(N);
1116
1117 // Next, brutally remove the operand list. This is safe to do, as there are
1118 // no cycles in the graph.
1119 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1120 SDUse &Use = *I++;
1121 SDNode *Operand = Use.getNode();
1122 Use.set(SDValue());
1123
1124 // Now that we removed this operand, see if there are no uses of it left.
1125 if (Operand->use_empty())
1126 DeadNodes.push_back(Operand);
1127 }
1128
1129 DeallocateNode(N);
1130 }
1131}
1132
1134 SmallVector<SDNode*, 16> DeadNodes(1, N);
1135
1136 // Create a dummy node that adds a reference to the root node, preventing
1137 // it from being deleted. (This matters if the root is an operand of the
1138 // dead node.)
1139 HandleSDNode Dummy(getRoot());
1140
1141 RemoveDeadNodes(DeadNodes);
1142}
1143
1145 // First take this out of the appropriate CSE map.
1146 RemoveNodeFromCSEMaps(N);
1147
1148 // Finally, remove uses due to operands of this node, remove from the
1149 // AllNodes list, and delete the node.
1150 DeleteNodeNotInCSEMaps(N);
1151}
1152
1153void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1154 assert(N->getIterator() != AllNodes.begin() &&
1155 "Cannot delete the entry node!");
1156 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1157
1158 // Drop all of the operands and decrement used node's use counts.
1159 N->DropOperands();
1160
1161 DeallocateNode(N);
1162}
1163
1164void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1165 assert(!(V->isVariadic() && isParameter));
1166 if (isParameter)
1167 ByvalParmDbgValues.push_back(V);
1168 else
1169 DbgValues.push_back(V);
1170 for (const SDNode *Node : V->getSDNodes())
1171 if (Node)
1172 DbgValMap[Node].push_back(V);
1173}
1174
1176 DbgValMapType::iterator I = DbgValMap.find(Node);
1177 if (I == DbgValMap.end())
1178 return;
1179 for (auto &Val: I->second)
1180 Val->setIsInvalidated();
1181 DbgValMap.erase(I);
1182}
1183
1184void SelectionDAG::DeallocateNode(SDNode *N) {
1185 // If we have operands, deallocate them.
1187
1188 NodeAllocator.Deallocate(AllNodes.remove(N));
1189
1190 // Set the opcode to DELETED_NODE to help catch bugs when node
1191 // memory is reallocated.
1192 // FIXME: There are places in SDag that have grown a dependency on the opcode
1193 // value in the released node.
1194 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1195 N->NodeType = ISD::DELETED_NODE;
1196
1197 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1198 // them and forget about that node.
1199 DbgInfo->erase(N);
1200
1201 // Invalidate extra info.
1202 SDEI.erase(N);
1203}
1204
1205#ifndef NDEBUG
1206/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1207void SelectionDAG::verifyNode(SDNode *N) const {
1208 switch (N->getOpcode()) {
1209 default:
1210 if (N->isTargetOpcode())
1212 break;
1213 case ISD::BUILD_PAIR: {
1214 EVT VT = N->getValueType(0);
1215 assert(N->getNumValues() == 1 && "Too many results!");
1216 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1217 "Wrong return type!");
1218 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1219 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1220 "Mismatched operand types!");
1221 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1222 "Wrong operand type!");
1223 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1224 "Wrong return type size");
1225 break;
1226 }
1227 case ISD::BUILD_VECTOR: {
1228 assert(N->getNumValues() == 1 && "Too many results!");
1229 assert(N->getValueType(0).isVector() && "Wrong return type!");
1230 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1231 "Wrong number of operands!");
1232 EVT EltVT = N->getValueType(0).getVectorElementType();
1233 for (const SDUse &Op : N->ops()) {
1234 assert((Op.getValueType() == EltVT ||
1235 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1236 EltVT.bitsLE(Op.getValueType()))) &&
1237 "Wrong operand type!");
1238 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1239 "Operands must all have the same type");
1240 }
1241 break;
1242 }
1243 case ISD::SADDO:
1244 case ISD::UADDO:
1245 case ISD::SSUBO:
1246 case ISD::USUBO:
1247 assert(N->getNumValues() == 2 && "Wrong number of results!");
1248 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1249 "Invalid add/sub overflow op!");
1250 assert(N->getVTList().VTs[0].isInteger() &&
1251 N->getVTList().VTs[1].isInteger() &&
1252 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1253 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1254 "Binary operator types must match!");
1255 break;
1256 }
1257}
1258#endif // NDEBUG
1259
1260/// Insert a newly allocated node into the DAG.
1261///
1262/// Handles insertion into the all nodes list and CSE map, as well as
1263/// verification and other common operations when a new node is allocated.
1264void SelectionDAG::InsertNode(SDNode *N) {
1265 AllNodes.push_back(N);
1266#ifndef NDEBUG
1267 N->PersistentId = NextPersistentId++;
1268 verifyNode(N);
1269#endif
1270 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1271 DUL->NodeInserted(N);
1272}
1273
1274/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1275/// correspond to it. This is useful when we're about to delete or repurpose
1276/// the node. We don't want future request for structurally identical nodes
1277/// to return N anymore.
1278bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1279 bool Erased = false;
1280 switch (N->getOpcode()) {
1281 case ISD::HANDLENODE: return false; // noop.
1282 case ISD::CONDCODE:
1283 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1284 "Cond code doesn't exist!");
1285 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1286 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1287 break;
1289 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1290 break;
1292 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1293 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1294 ESN->getSymbol(), ESN->getTargetFlags()));
1295 break;
1296 }
1297 case ISD::MCSymbol: {
1298 auto *MCSN = cast<MCSymbolSDNode>(N);
1299 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1300 break;
1301 }
1302 case ISD::VALUETYPE: {
1303 EVT VT = cast<VTSDNode>(N)->getVT();
1304 if (VT.isExtended()) {
1305 Erased = ExtendedValueTypeNodes.erase(VT);
1306 } else {
1307 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1308 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1309 }
1310 break;
1311 }
1312 default:
1313 // Remove it from the CSE Map.
1314 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1315 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1316 Erased = CSEMap.RemoveNode(N);
1317 break;
1318 }
1319#ifndef NDEBUG
1320 // Verify that the node was actually in one of the CSE maps, unless it has a
1321 // glue result (which cannot be CSE'd) or is one of the special cases that are
1322 // not subject to CSE.
1323 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1324 !N->isMachineOpcode() && !doNotCSE(N)) {
1325 N->dump(this);
1326 dbgs() << "\n";
1327 llvm_unreachable("Node is not in map!");
1328 }
1329#endif
1330 return Erased;
1331}
1332
1333/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1334/// maps and modified in place. Add it back to the CSE maps, unless an identical
1335/// node already exists, in which case transfer all its users to the existing
1336/// node. This transfer can potentially trigger recursive merging.
1337void
1338SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1339 // For node types that aren't CSE'd, just act as if no identical node
1340 // already exists.
1341 if (!doNotCSE(N)) {
1342 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1343 if (Existing != N) {
1344 // If there was already an existing matching node, use ReplaceAllUsesWith
1345 // to replace the dead one with the existing one. This can cause
1346 // recursive merging of other unrelated nodes down the line.
1347 Existing->intersectFlagsWith(N->getFlags());
1348 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1350 cast<MemSDNode>(N)->memoperands();
1351 // Range and cache hint metadata are not part of the DAG CSE key because
1352 // we prefer to CSE even when metadata does not match. Merge potentially
1353 // differing metadata conservatively.
1354 MemNode->refineMMOMetadata(NewMMOs);
1355 }
1356 ReplaceAllUsesWith(N, Existing);
1357
1358 // N is now dead. Inform the listeners and delete it.
1359 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1360 DUL->NodeDeleted(N, Existing);
1361 DeleteNodeNotInCSEMaps(N);
1362 return;
1363 }
1364 }
1365
1366 // If the node doesn't already exist, we updated it. Inform listeners.
1367 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1368 DUL->NodeUpdated(N);
1369}
1370
1371/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1372/// were replaced with those specified. If this node is never memoized,
1373/// return null, otherwise return a pointer to the slot it would take. If a
1374/// node already exists with these operands, the slot will be non-null.
1375SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1376 void *&InsertPos) {
1377 if (doNotCSE(N))
1378 return nullptr;
1379
1380 SDValue Ops[] = { Op };
1381 FoldingSetNodeID ID;
1382 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1383 AddNodeIDCustom(ID, N);
1384 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1385 if (Node)
1386 Node->intersectFlagsWith(N->getFlags());
1387 return Node;
1388}
1389
1390/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1391/// were replaced with those specified. If this node is never memoized,
1392/// return null, otherwise return a pointer to the slot it would take. If a
1393/// node already exists with these operands, the slot will be non-null.
1394SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1395 SDValue Op1, SDValue Op2,
1396 void *&InsertPos) {
1397 if (doNotCSE(N))
1398 return nullptr;
1399
1400 SDValue Ops[] = { Op1, Op2 };
1401 FoldingSetNodeID ID;
1402 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1403 AddNodeIDCustom(ID, N);
1404 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1405 if (Node)
1406 Node->intersectFlagsWith(N->getFlags());
1407 return Node;
1408}
1409
1410/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1411/// were replaced with those specified. If this node is never memoized,
1412/// return null, otherwise return a pointer to the slot it would take. If a
1413/// node already exists with these operands, the slot will be non-null.
1414SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1415 void *&InsertPos) {
1416 if (doNotCSE(N))
1417 return nullptr;
1418
1419 FoldingSetNodeID ID;
1420 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1421 AddNodeIDCustom(ID, N);
1422 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1423 if (Node)
1424 Node->intersectFlagsWith(N->getFlags());
1425 return Node;
1426}
1427
1429 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1430 : VT.getTypeForEVT(*getContext());
1431
1432 return getDataLayout().getABITypeAlign(Ty);
1433}
1434
1435// EntryNode could meaningfully have debug info if we can find it...
1437 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1438 getVTList(MVT::Other, MVT::Glue)),
1439 Root(getEntryNode()) {
1440 InsertNode(&EntryNode);
1441 DbgInfo = new SDDbgInfo();
1442}
1443
1445 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1446 const TargetLibraryInfo *LibraryInfo,
1447 const LibcallLoweringInfo *LibcallsInfo,
1448 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1450 FunctionVarLocs const *VarLocs) {
1451 MF = &NewMF;
1452 SDAGISelPass = PassPtr;
1453 ORE = &NewORE;
1456 LibInfo = LibraryInfo;
1457 Libcalls = LibcallsInfo;
1458 Context = &MF->getFunction().getContext();
1459 UA = NewUA;
1460 PSI = PSIin;
1461 BFI = BFIin;
1462 MMI = &MMIin;
1463 FnVarLocs = VarLocs;
1464}
1465
1467 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1468 allnodes_clear();
1469 OperandRecycler.clear(OperandAllocator);
1470 delete DbgInfo;
1471}
1472
1474 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1475}
1476
1477void SelectionDAG::allnodes_clear() {
1478 assert(&*AllNodes.begin() == &EntryNode);
1479 AllNodes.remove(AllNodes.begin());
1480 while (!AllNodes.empty())
1481 DeallocateNode(&AllNodes.front());
1482#ifndef NDEBUG
1483 NextPersistentId = 0;
1484#endif
1485}
1486
1487SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1488 void *&InsertPos) {
1489 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1490 if (N) {
1491 switch (N->getOpcode()) {
1492 default: break;
1493 case ISD::Constant:
1494 case ISD::ConstantFP:
1495 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1496 "debug location. Use another overload.");
1497 }
1498 }
1499 return N;
1500}
1501
1502SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1503 const SDLoc &DL, void *&InsertPos) {
1504 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1505 if (N) {
1506 switch (N->getOpcode()) {
1507 case ISD::Constant:
1508 case ISD::ConstantFP:
1509 // Erase debug location from the node if the node is used at several
1510 // different places. Do not propagate one location to all uses as it
1511 // will cause a worse single stepping debugging experience.
1512 if (N->getDebugLoc() != DL.getDebugLoc())
1513 N->setDebugLoc(DebugLoc());
1514 break;
1515 default:
1516 // When the node's point of use is located earlier in the instruction
1517 // sequence than its prior point of use, update its debug info to the
1518 // earlier location.
1519 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1520 N->setDebugLoc(DL.getDebugLoc());
1521 break;
1522 }
1523 }
1524 return N;
1525}
1526
1528 allnodes_clear();
1529 OperandRecycler.clear(OperandAllocator);
1530 OperandAllocator.Reset();
1531 CSEMap.clear();
1532
1533 ExtendedValueTypeNodes.clear();
1534 ExternalSymbols.clear();
1535 TargetExternalSymbols.clear();
1536 MCSymbols.clear();
1537 SDEI.clear();
1538 llvm::fill(CondCodeNodes, nullptr);
1539 llvm::fill(ValueTypeNodes, nullptr);
1540
1541 EntryNode.UseList = nullptr;
1542 InsertNode(&EntryNode);
1543 Root = getEntryNode();
1544 DbgInfo->clear();
1545}
1546
1548 return VT.bitsGT(Op.getValueType())
1549 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1550 : getNode(ISD::FP_ROUND, DL, VT, Op,
1551 getIntPtrConstant(0, DL, /*isTarget=*/true));
1552}
1553
1554std::pair<SDValue, SDValue>
1556 const SDLoc &DL, EVT VT) {
1557 assert(!VT.bitsEq(Op.getValueType()) &&
1558 "Strict no-op FP extend/round not allowed.");
1559 SDValue Res =
1560 VT.bitsGT(Op.getValueType())
1561 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1562 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1563 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1564
1565 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1566}
1567
1569 return VT.bitsGT(Op.getValueType()) ?
1570 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1571 getNode(ISD::TRUNCATE, DL, VT, Op);
1572}
1573
1575 return VT.bitsGT(Op.getValueType()) ?
1576 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1577 getNode(ISD::TRUNCATE, DL, VT, Op);
1578}
1579
1581 return VT.bitsGT(Op.getValueType()) ?
1582 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1583 getNode(ISD::TRUNCATE, DL, VT, Op);
1584}
1585
1587 EVT VT) {
1588 assert(!VT.isVector());
1589 auto Type = Op.getValueType();
1590 SDValue DestOp;
1591 if (Type == VT)
1592 return Op;
1593 auto Size = Op.getValueSizeInBits();
1594 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1595 if (DestOp.getValueType() == VT)
1596 return DestOp;
1597
1598 return getAnyExtOrTrunc(DestOp, DL, VT);
1599}
1600
1602 EVT VT) {
1603 assert(!VT.isVector());
1604 auto Type = Op.getValueType();
1605 SDValue DestOp;
1606 if (Type == VT)
1607 return Op;
1608 auto Size = Op.getValueSizeInBits();
1609 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1610 if (DestOp.getValueType() == VT)
1611 return DestOp;
1612
1613 return getSExtOrTrunc(DestOp, DL, VT);
1614}
1615
1617 EVT VT) {
1618 assert(!VT.isVector());
1619 auto Type = Op.getValueType();
1620 SDValue DestOp;
1621 if (Type == VT)
1622 return Op;
1623 auto Size = Op.getValueSizeInBits();
1624 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1625 if (DestOp.getValueType() == VT)
1626 return DestOp;
1627
1628 return getZExtOrTrunc(DestOp, DL, VT);
1629}
1630
1632 EVT OpVT) {
1633 if (VT.bitsLE(Op.getValueType()))
1634 return getNode(ISD::TRUNCATE, SL, VT, Op);
1635
1636 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1637 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1638}
1639
1641 EVT OpVT = Op.getValueType();
1642 assert(VT.isInteger() && OpVT.isInteger() &&
1643 "Cannot getZeroExtendInReg FP types");
1644 assert(VT.isVector() == OpVT.isVector() &&
1645 "getZeroExtendInReg type should be vector iff the operand "
1646 "type is vector!");
1647 assert((!VT.isVector() ||
1649 "Vector element counts must match in getZeroExtendInReg");
1650 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1651 if (OpVT == VT)
1652 return Op;
1653 // TODO: Use computeKnownBits instead of AssertZext.
1654 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1655 ->getVT()
1656 .getScalarType()
1657 .bitsLE(VT.getScalarType()))
1658 return Op;
1660 VT.getScalarSizeInBits());
1661 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1662}
1663
1665 // Only unsigned pointer semantics are supported right now. In the future this
1666 // might delegate to TLI to check pointer signedness.
1667 return getZExtOrTrunc(Op, DL, VT);
1668}
1669
1671 // Only unsigned pointer semantics are supported right now. In the future this
1672 // might delegate to TLI to check pointer signedness.
1673 return getZeroExtendInReg(Op, DL, VT);
1674}
1675
1677 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1678}
1679
1680/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1682 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1683}
1684
1686 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1687 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1688}
1689
1691 EVT OpVT) {
1692 if (!V)
1693 return getConstant(0, DL, VT);
1694
1695 switch (TLI->getBooleanContents(OpVT)) {
1698 return getConstant(1, DL, VT);
1700 return getAllOnesConstant(DL, VT);
1701 }
1702 llvm_unreachable("Unexpected boolean content enum!");
1703}
1704
1706 bool isT, bool isO) {
1707 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1708 DL, VT, isT, isO);
1709}
1710
1712 bool isT, bool isO) {
1713 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1714}
1715
1717 EVT VT, bool isT, bool isO) {
1718 assert(VT.isInteger() && "Cannot create FP integer constant!");
1719
1720 EVT EltVT = VT.getScalarType();
1721 const ConstantInt *Elt = &Val;
1722
1723 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1724 // to-be-splatted scalar ConstantInt.
1725 if (isa<VectorType>(Elt->getType()))
1726 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1727
1728 // In some cases the vector type is legal but the element type is illegal and
1729 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1730 // inserted value (the type does not need to match the vector element type).
1731 // Any extra bits introduced will be truncated away.
1732 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1734 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1735 APInt NewVal;
1736 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1737 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1738 else
1739 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1740 Elt = ConstantInt::get(*getContext(), NewVal);
1741 }
1742 // In other cases the element type is illegal and needs to be expanded, for
1743 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1744 // the value into n parts and use a vector type with n-times the elements.
1745 // Then bitcast to the type requested.
1746 // Legalizing constants too early makes the DAGCombiner's job harder so we
1747 // only legalize if the DAG tells us we must produce legal types.
1748 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1749 TLI->getTypeAction(*getContext(), EltVT) ==
1751 const APInt &NewVal = Elt->getValue();
1752 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1753 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1754
1755 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1756 if (VT.isScalableVector() ||
1757 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1758 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1759 "Can only handle an even split!");
1760 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1761
1762 SmallVector<SDValue, 2> ScalarParts;
1763 for (unsigned i = 0; i != Parts; ++i)
1764 ScalarParts.push_back(getConstant(
1765 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1766 ViaEltVT, isT, isO));
1767
1768 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1769 }
1770
1771 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1772 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1773
1774 // Check the temporary vector is the correct size. If this fails then
1775 // getTypeToTransformTo() probably returned a type whose size (in bits)
1776 // isn't a power-of-2 factor of the requested type size.
1777 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1778
1779 SmallVector<SDValue, 2> EltParts;
1780 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1781 EltParts.push_back(getConstant(
1782 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1783 ViaEltVT, isT, isO));
1784
1785 // EltParts is currently in little endian order. If we actually want
1786 // big-endian order then reverse it now.
1787 if (getDataLayout().isBigEndian())
1788 std::reverse(EltParts.begin(), EltParts.end());
1789
1790 // The elements must be reversed when the element order is different
1791 // to the endianness of the elements (because the BITCAST is itself a
1792 // vector shuffle in this situation). However, we do not need any code to
1793 // perform this reversal because getConstant() is producing a vector
1794 // splat.
1795 // This situation occurs in MIPS MSA.
1796
1798 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1799 llvm::append_range(Ops, EltParts);
1800
1801 SDValue V =
1802 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1803 return V;
1804 }
1805
1806 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1807 "APInt size does not match type size!");
1808 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1809 SDVTList VTs = getVTList(EltVT);
1811 AddNodeIDNode(ID, Opc, VTs, {});
1812 ID.AddPointer(Elt);
1813 ID.AddBoolean(isO);
1814 void *IP = nullptr;
1815 SDNode *N = nullptr;
1816 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1817 if (!VT.isVector())
1818 return SDValue(N, 0);
1819
1820 if (!N) {
1821 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1822 if (!isT)
1823 N->setDebugLoc(DL.getDebugLoc());
1824 CSEMap.InsertNode(N, IP);
1825 InsertNode(N);
1826 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1827 }
1828
1829 SDValue Result(N, 0);
1830 if (VT.isVector())
1831 Result = getSplat(VT, DL, Result);
1832 return Result;
1833}
1834
1836 bool isT, bool isO) {
1837 unsigned Size = VT.getScalarSizeInBits();
1838 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1839}
1840
1842 bool IsOpaque) {
1844 IsTarget, IsOpaque);
1845}
1846
1848 bool isTarget) {
1849 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1850}
1851
1853 const SDLoc &DL) {
1854 assert(VT.isInteger() && "Shift amount is not an integer type!");
1855 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1856 return getConstant(Val, DL, ShiftVT);
1857}
1858
1860 const SDLoc &DL) {
1861 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1862 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1863}
1864
1866 bool isTarget) {
1867 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1868}
1869
1871 bool isTarget) {
1872 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1873}
1874
1876 EVT VT, bool isTarget) {
1877 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1878
1879 EVT EltVT = VT.getScalarType();
1880 const ConstantFP *Elt = &V;
1881
1882 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1883 // the to-be-splatted scalar ConstantFP.
1884 if (isa<VectorType>(Elt->getType()))
1885 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1886
1887 // Do the map lookup using the actual bit pattern for the floating point
1888 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1889 // we don't have issues with SNANs.
1890 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1891 SDVTList VTs = getVTList(EltVT);
1893 AddNodeIDNode(ID, Opc, VTs, {});
1894 ID.AddPointer(Elt);
1895 void *IP = nullptr;
1896 SDNode *N = nullptr;
1897 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1898 if (!VT.isVector())
1899 return SDValue(N, 0);
1900
1901 if (!N) {
1902 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1903 CSEMap.InsertNode(N, IP);
1904 InsertNode(N);
1905 }
1906
1907 SDValue Result(N, 0);
1908 if (VT.isVector())
1909 Result = getSplat(VT, DL, Result);
1910 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1911 return Result;
1912}
1913
1915 bool isTarget) {
1916 EVT EltVT = VT.getScalarType();
1917 if (EltVT == MVT::f32)
1918 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1919 if (EltVT == MVT::f64)
1920 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1921 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1922 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1923 bool Ignored;
1924 APFloat APF = APFloat(Val);
1926 &Ignored);
1927 return getConstantFP(APF, DL, VT, isTarget);
1928 }
1929 llvm_unreachable("Unsupported type in getConstantFP");
1930}
1931
1933 EVT VT, int64_t Offset, bool isTargetGA,
1934 unsigned TargetFlags) {
1935 assert((TargetFlags == 0 || isTargetGA) &&
1936 "Cannot set target flags on target-independent globals");
1937
1938 // Truncate (with sign-extension) the offset value to the pointer size.
1940 if (BitWidth < 64)
1942
1943 unsigned Opc;
1944 if (GV->isThreadLocal())
1946 else
1948
1949 SDVTList VTs = getVTList(VT);
1951 AddNodeIDNode(ID, Opc, VTs, {});
1952 ID.AddPointer(GV);
1953 ID.AddInteger(Offset);
1954 ID.AddInteger(TargetFlags);
1955 void *IP = nullptr;
1956 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1957 return SDValue(E, 0);
1958
1959 auto *N = newSDNode<GlobalAddressSDNode>(
1960 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1961 CSEMap.InsertNode(N, IP);
1962 InsertNode(N);
1963 return SDValue(N, 0);
1964}
1965
1967 SDVTList VTs = getVTList(MVT::Untyped);
1970 ID.AddPointer(GV);
1971 void *IP = nullptr;
1972 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP))
1973 return SDValue(E, 0);
1974
1975 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1976 CSEMap.InsertNode(N, IP);
1977 InsertNode(N);
1978 return SDValue(N, 0);
1979}
1980
1981SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1982 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1983 SDVTList VTs = getVTList(VT);
1985 AddNodeIDNode(ID, Opc, VTs, {});
1986 ID.AddInteger(FI);
1987 void *IP = nullptr;
1988 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1989 return SDValue(E, 0);
1990
1991 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1992 CSEMap.InsertNode(N, IP);
1993 InsertNode(N);
1994 return SDValue(N, 0);
1995}
1996
1997SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1998 unsigned TargetFlags) {
1999 assert((TargetFlags == 0 || isTarget) &&
2000 "Cannot set target flags on target-independent jump tables");
2001 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
2002 SDVTList VTs = getVTList(VT);
2004 AddNodeIDNode(ID, Opc, VTs, {});
2005 ID.AddInteger(JTI);
2006 ID.AddInteger(TargetFlags);
2007 void *IP = nullptr;
2008 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2009 return SDValue(E, 0);
2010
2011 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
2012 CSEMap.InsertNode(N, IP);
2013 InsertNode(N);
2014 return SDValue(N, 0);
2015}
2016
2018 const SDLoc &DL) {
2020 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2021 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2022}
2023
2025 MaybeAlign Alignment, int Offset,
2026 bool isTarget, unsigned TargetFlags) {
2027 assert((TargetFlags == 0 || isTarget) &&
2028 "Cannot set target flags on target-independent globals");
2029 if (!Alignment)
2030 Alignment = shouldOptForSize()
2031 ? getDataLayout().getABITypeAlign(C->getType())
2032 : getDataLayout().getPrefTypeAlign(C->getType());
2033 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2034 SDVTList VTs = getVTList(VT);
2036 AddNodeIDNode(ID, Opc, VTs, {});
2037 ID.AddInteger(Alignment->value());
2038 ID.AddInteger(Offset);
2039 ID.AddPointer(C);
2040 ID.AddInteger(TargetFlags);
2041 void *IP = nullptr;
2042 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2043 return SDValue(E, 0);
2044
2045 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2046 TargetFlags);
2047 CSEMap.InsertNode(N, IP);
2048 InsertNode(N);
2049 SDValue V = SDValue(N, 0);
2050 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2051 return V;
2052}
2053
2055 MaybeAlign Alignment, int Offset,
2056 bool isTarget, unsigned TargetFlags) {
2057 assert((TargetFlags == 0 || isTarget) &&
2058 "Cannot set target flags on target-independent globals");
2059 if (!Alignment)
2060 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2061 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2062 SDVTList VTs = getVTList(VT);
2064 AddNodeIDNode(ID, Opc, VTs, {});
2065 ID.AddInteger(Alignment->value());
2066 ID.AddInteger(Offset);
2067 C->addSelectionDAGCSEId(ID);
2068 ID.AddInteger(TargetFlags);
2069 void *IP = nullptr;
2070 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2071 return SDValue(E, 0);
2072
2073 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2074 TargetFlags);
2075 CSEMap.InsertNode(N, IP);
2076 InsertNode(N);
2077 return SDValue(N, 0);
2078}
2079
2082 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), {});
2083 ID.AddPointer(MBB);
2084 void *IP = nullptr;
2085 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2086 return SDValue(E, 0);
2087
2088 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2089 CSEMap.InsertNode(N, IP);
2090 InsertNode(N);
2091 return SDValue(N, 0);
2092}
2093
2095 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2096 ValueTypeNodes.size())
2097 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2098
2099 SDNode *&N = VT.isExtended() ?
2100 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2101
2102 if (N) return SDValue(N, 0);
2103 N = newSDNode<VTSDNode>(VT);
2104 InsertNode(N);
2105 return SDValue(N, 0);
2106}
2107
2109 SDNode *&N = ExternalSymbols[Sym];
2110 if (N) return SDValue(N, 0);
2111 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2112 InsertNode(N);
2113 return SDValue(N, 0);
2114}
2115
2116SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2118 return getExternalSymbol(SymName.data(), VT);
2119}
2120
2122 SDNode *&N = MCSymbols[Sym];
2123 if (N)
2124 return SDValue(N, 0);
2125 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2126 InsertNode(N);
2127 return SDValue(N, 0);
2128}
2129
2131 unsigned TargetFlags) {
2132 SDNode *&N =
2133 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2134 if (N) return SDValue(N, 0);
2135 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2136 InsertNode(N);
2137 return SDValue(N, 0);
2138}
2139
2141 EVT VT, unsigned TargetFlags) {
2143 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2144}
2145
2147 if ((unsigned)Cond >= CondCodeNodes.size())
2148 CondCodeNodes.resize(Cond+1);
2149
2150 if (!CondCodeNodes[Cond]) {
2151 auto *N = newSDNode<CondCodeSDNode>(Cond);
2152 CondCodeNodes[Cond] = N;
2153 InsertNode(N);
2154 }
2155
2156 return SDValue(CondCodeNodes[Cond], 0);
2157}
2158
2160 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2161 "APInt size does not match type size!");
2162
2163 if (MulImm == 0)
2164 return getConstant(0, DL, VT);
2165
2166 const MachineFunction &MF = getMachineFunction();
2167 const Function &F = MF.getFunction();
2168 ConstantRange CR = getVScaleRange(&F, 64);
2169 if (const APInt *C = CR.getSingleElement())
2170 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2171
2172 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2173}
2174
2175/// \returns a value of type \p VT that represents the runtime value of \p
2176/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2177/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2178/// or TypeSize.
2179template <typename Ty>
2181 EVT VT, Ty Quantity) {
2182 if (Quantity.isScalable())
2183 return DAG.getVScale(
2184 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2185
2186 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2187}
2188
2190 ElementCount EC) {
2191 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2192}
2193
2195 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2196}
2197
2199 ElementCount EC) {
2200 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2201 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2202 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2203 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2204}
2205
2207 APInt One(ResVT.getScalarSizeInBits(), 1);
2208 return getStepVector(DL, ResVT, One);
2209}
2210
2212 const APInt &StepVal) {
2213 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2214 if (ResVT.isScalableVector())
2215 return getNode(
2216 ISD::STEP_VECTOR, DL, ResVT,
2217 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2218
2219 SmallVector<SDValue, 16> OpsStepConstants;
2220 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2221 OpsStepConstants.push_back(
2222 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2223 return getBuildVector(ResVT, DL, OpsStepConstants);
2224}
2225
2226/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2227/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2232
2234 SDValue N2, ArrayRef<int> Mask) {
2235 assert(VT.getVectorNumElements() == Mask.size() &&
2236 "Must have the same number of vector elements as mask elements!");
2237 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2238 "Invalid VECTOR_SHUFFLE");
2239
2240 // Canonicalize shuffle undef, undef -> undef
2241 if (N1.isUndef() && N2.isUndef()) {
2242 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2243 return getPOISON(VT);
2244 return getUNDEF(VT);
2245 }
2246
2247 // Validate that all indices in Mask are within the range of the elements
2248 // input to the shuffle.
2249 int NElts = Mask.size();
2250 assert(llvm::all_of(Mask,
2251 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2252 "Index out of range");
2253
2254 // Copy the mask so we can do any needed cleanup.
2255 SmallVector<int, 8> MaskVec(Mask);
2256
2257 // Canonicalize shuffle v, v -> v, poison
2258 if (N1 == N2) {
2259 N2 = getPOISON(VT);
2260 for (int i = 0; i != NElts; ++i)
2261 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2262 }
2263
2264 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2265 if (N1.isUndef())
2266 commuteShuffle(N1, N2, MaskVec);
2267
2268 if (TLI->hasVectorBlend()) {
2269 // If shuffling a splat, try to blend the splat instead. We do this here so
2270 // that even when this arises during lowering we don't have to re-handle it.
2271 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2272 BitVector UndefElements;
2273 SDValue Splat = BV->getSplatValue(&UndefElements);
2274 if (!Splat)
2275 return;
2276
2277 for (int i = 0; i < NElts; ++i) {
2278 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2279 continue;
2280
2281 // If this input comes from undef, mark it as such.
2282 if (UndefElements[MaskVec[i] - Offset]) {
2283 MaskVec[i] = -1;
2284 continue;
2285 }
2286
2287 // If we can blend a non-undef lane, use that instead.
2288 if (!UndefElements[i])
2289 MaskVec[i] = i + Offset;
2290 }
2291 };
2292 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2293 BlendSplat(N1BV, 0);
2294 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2295 BlendSplat(N2BV, NElts);
2296 }
2297
2298 // Canonicalize all index into lhs, -> shuffle lhs, poison
2299 // Canonicalize all index into rhs, -> shuffle rhs, poison
2300 bool AllLHS = true, AllRHS = true;
2301 bool N2Undef = N2.isUndef();
2302 for (int i = 0; i != NElts; ++i) {
2303 if (MaskVec[i] >= NElts) {
2304 if (N2Undef)
2305 MaskVec[i] = -1;
2306 else
2307 AllLHS = false;
2308 } else if (MaskVec[i] >= 0) {
2309 AllRHS = false;
2310 }
2311 }
2312 if (AllLHS && AllRHS)
2313 return getPOISON(VT);
2314 if (AllLHS && !N2Undef)
2315 N2 = getPOISON(VT);
2316 if (AllRHS) {
2317 N1 = getPOISON(VT);
2318 commuteShuffle(N1, N2, MaskVec);
2319 }
2320 // Reset our undef status after accounting for the mask.
2321 N2Undef = N2.isUndef();
2322 // Re-check whether both sides ended up undef.
2323 if (N1.isUndef() && N2Undef) {
2324 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2325 return getPOISON(VT);
2326 return getUNDEF(VT);
2327 }
2328
2329 // If Identity shuffle return that node.
2330 bool Identity = true, AllSame = true;
2331 for (int i = 0; i != NElts; ++i) {
2332 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2333 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2334 }
2335 if (Identity && NElts)
2336 return N1;
2337
2338 // Shuffling a constant splat doesn't change the result.
2339 if (N2Undef) {
2340 SDValue V = N1;
2341
2342 // Look through any bitcasts. We check that these don't change the number
2343 // (and size) of elements and just changes their types.
2344 while (V.getOpcode() == ISD::BITCAST)
2345 V = V->getOperand(0);
2346
2347 // A splat should always show up as a build vector node.
2348 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2349 BitVector UndefElements;
2350 SDValue Splat = BV->getSplatValue(&UndefElements);
2351 // If this is a splat of an undef, shuffling it is also undef.
2352 if (Splat && Splat.isUndef())
2353 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2354
2355 bool SameNumElts =
2356 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2357
2358 // We only have a splat which can skip shuffles if there is a splatted
2359 // value and no undef lanes rearranged by the shuffle.
2360 if (Splat && UndefElements.none()) {
2361 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2362 // number of elements match or the value splatted is a zero constant.
2363 if (SameNumElts || isNullConstant(Splat))
2364 return N1;
2365 }
2366
2367 // If the shuffle itself creates a splat, build the vector directly.
2368 if (AllSame && SameNumElts) {
2369 EVT BuildVT = BV->getValueType(0);
2370 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2371 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2372
2373 // We may have jumped through bitcasts, so the type of the
2374 // BUILD_VECTOR may not match the type of the shuffle.
2375 if (BuildVT != VT)
2376 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2377 return NewBV;
2378 }
2379 }
2380 }
2381
2382 SDVTList VTs = getVTList(VT);
2384 SDValue Ops[2] = { N1, N2 };
2386 for (int i = 0; i != NElts; ++i)
2387 ID.AddInteger(MaskVec[i]);
2388
2389 void* IP = nullptr;
2390 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2391 return SDValue(E, 0);
2392
2393 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2394 // SDNode doesn't have access to it. This memory will be "leaked" when
2395 // the node is deallocated, but recovered when the NodeAllocator is released.
2396 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2397 llvm::copy(MaskVec, MaskAlloc);
2398
2399 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2400 dl.getDebugLoc(), MaskAlloc);
2401 createOperands(N, Ops);
2402
2403 CSEMap.InsertNode(N, IP);
2404 InsertNode(N);
2405 SDValue V = SDValue(N, 0);
2406 NewSDValueDbgMsg(V, "Creating new node: ", this);
2407 return V;
2408}
2409
2411 EVT VT = SV.getValueType(0);
2412 SmallVector<int, 8> MaskVec(SV.getMask());
2414
2415 SDValue Op0 = SV.getOperand(0);
2416 SDValue Op1 = SV.getOperand(1);
2417 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2418}
2419
2421 SDVTList VTs = getVTList(VT);
2423 AddNodeIDNode(ID, ISD::Register, VTs, {});
2424 ID.AddInteger(Reg.id());
2425 void *IP = nullptr;
2426 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2427 return SDValue(E, 0);
2428
2429 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2430 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2431 CSEMap.InsertNode(N, IP);
2432 InsertNode(N);
2433 return SDValue(N, 0);
2434}
2435
2438 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), {});
2439 ID.AddPointer(RegMask);
2440 void *IP = nullptr;
2441 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2442 return SDValue(E, 0);
2443
2444 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2445 CSEMap.InsertNode(N, IP);
2446 InsertNode(N);
2447 return SDValue(N, 0);
2448}
2449
2451 MCSymbol *Label) {
2452 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2453}
2454
2455SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2456 SDValue Root, MCSymbol *Label) {
2458 SDValue Ops[] = { Root };
2459 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2460 ID.AddPointer(Label);
2461 void *IP = nullptr;
2462 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2463 return SDValue(E, 0);
2464
2465 auto *N =
2466 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2467 createOperands(N, Ops);
2468
2469 CSEMap.InsertNode(N, IP);
2470 InsertNode(N);
2471 return SDValue(N, 0);
2472}
2473
2475 int64_t Offset, bool isTarget,
2476 unsigned TargetFlags) {
2477 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2478 SDVTList VTs = getVTList(VT);
2479
2481 AddNodeIDNode(ID, Opc, VTs, {});
2482 ID.AddPointer(BA);
2483 ID.AddInteger(Offset);
2484 ID.AddInteger(TargetFlags);
2485 void *IP = nullptr;
2486 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2487 return SDValue(E, 0);
2488
2489 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2490 CSEMap.InsertNode(N, IP);
2491 InsertNode(N);
2492 return SDValue(N, 0);
2493}
2494
2497 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), {});
2498 ID.AddPointer(V);
2499
2500 void *IP = nullptr;
2501 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2502 return SDValue(E, 0);
2503
2504 auto *N = newSDNode<SrcValueSDNode>(V);
2505 CSEMap.InsertNode(N, IP);
2506 InsertNode(N);
2507 return SDValue(N, 0);
2508}
2509
2512 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2513 ID.AddPointer(MD);
2514
2515 void *IP = nullptr;
2516 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2517 return SDValue(E, 0);
2518
2519 auto *N = newSDNode<MDNodeSDNode>(MD);
2520 CSEMap.InsertNode(N, IP);
2521 InsertNode(N);
2522 return SDValue(N, 0);
2523}
2524
2526 if (VT == V.getValueType())
2527 return V;
2528
2529 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2530}
2531
2533 unsigned SrcAS, unsigned DestAS) {
2534 SDVTList VTs = getVTList(VT);
2535 SDValue Ops[] = {Ptr};
2538 ID.AddInteger(SrcAS);
2539 ID.AddInteger(DestAS);
2540
2541 void *IP = nullptr;
2542 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2543 return SDValue(E, 0);
2544
2545 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2546 VTs, SrcAS, DestAS);
2547 createOperands(N, Ops);
2548
2549 CSEMap.InsertNode(N, IP);
2550 InsertNode(N);
2551 return SDValue(N, 0);
2552}
2553
2555 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2556}
2557
2559 UndefPoisonKind Kind) {
2560 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2561 return V;
2562 return getFreeze(V);
2563}
2564
2565/// getShiftAmountOperand - Return the specified value casted to
2566/// the target's desired shift amount type.
2568 EVT OpTy = Op.getValueType();
2569 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2570 if (OpTy == ShTy || OpTy.isVector()) return Op;
2571
2572 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2573}
2574
2576 SDLoc dl(Node);
2578 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2579 EVT VT = Node->getValueType(0);
2580 SDValue Tmp1 = Node->getOperand(0);
2581 SDValue Tmp2 = Node->getOperand(1);
2582 const MaybeAlign MA(Node->getConstantOperandVal(3));
2583
2584 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2585 Tmp2, MachinePointerInfo(V));
2586 SDValue VAList = VAListLoad;
2587
2588 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2589 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2590 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2591
2592 VAList = getNode(
2593 ISD::AND, dl, VAList.getValueType(), VAList,
2594 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2595 }
2596
2597 // Increment the pointer, VAList, to the next vaarg
2598 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2599 getConstant(getDataLayout().getTypeAllocSize(
2600 VT.getTypeForEVT(*getContext())),
2601 dl, VAList.getValueType()));
2602 // Store the incremented VAList to the legalized pointer
2603 Tmp1 =
2604 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2605 // Load the actual argument out of the pointer VAList
2606 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2607}
2608
2610 SDLoc dl(Node);
2612 // This defaults to loading a pointer from the input and storing it to the
2613 // output, returning the chain.
2614 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2615 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2616 SDValue Tmp1 =
2617 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2618 Node->getOperand(2), MachinePointerInfo(VS));
2619 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2620 MachinePointerInfo(VD));
2621}
2622
2624 const DataLayout &DL = getDataLayout();
2625 Type *Ty = VT.getTypeForEVT(*getContext());
2626 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2627
2628 if (TLI->isTypeLegal(VT) || !VT.isVector())
2629 return RedAlign;
2630
2631 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2632 const Align StackAlign = TFI->getStackAlign();
2633
2634 // See if we can choose a smaller ABI alignment in cases where it's an
2635 // illegal vector type that will get broken down.
2636 if (RedAlign > StackAlign) {
2637 EVT IntermediateVT;
2638 MVT RegisterVT;
2639 unsigned NumIntermediates;
2640 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2641 NumIntermediates, RegisterVT);
2642 Ty = IntermediateVT.getTypeForEVT(*getContext());
2643 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2644 if (RedAlign2 < RedAlign)
2645 RedAlign = RedAlign2;
2646
2647 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2648 // If the stack is not realignable, the alignment should be limited to the
2649 // StackAlignment
2650 RedAlign = std::min(RedAlign, StackAlign);
2651 }
2652
2653 return RedAlign;
2654}
2655
2657 MachineFrameInfo &MFI = MF->getFrameInfo();
2658 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2659 int StackID = 0;
2660 if (Bytes.isScalable())
2661 StackID = TFI->getStackIDForScalableVectors();
2662 // The stack id gives an indication of whether the object is scalable or
2663 // not, so it's safe to pass in the minimum size here.
2664 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2665 false, nullptr, StackID);
2666 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2667}
2668
2670 Type *Ty = VT.getTypeForEVT(*getContext());
2671 Align StackAlign =
2672 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2673 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2674}
2675
2677 TypeSize VT1Size = VT1.getStoreSize();
2678 TypeSize VT2Size = VT2.getStoreSize();
2679 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2680 "Don't know how to choose the maximum size when creating a stack "
2681 "temporary");
2682 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2683 ? VT1Size
2684 : VT2Size;
2685
2686 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2687 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2688 const DataLayout &DL = getDataLayout();
2689 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2690 return CreateStackTemporary(Bytes, Align);
2691}
2692
2694 ISD::CondCode Cond, const SDLoc &dl,
2695 SDNodeFlags Flags) {
2696 EVT OpVT = N1.getValueType();
2697
2698 auto GetUndefBooleanConstant = [&]() {
2699 if (VT.getScalarType() == MVT::i1 ||
2700 TLI->getBooleanContents(OpVT) ==
2702 return getUNDEF(VT);
2703 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2704 // so we cannot use getUNDEF(). Return zero instead.
2705 return getConstant(0, dl, VT);
2706 };
2707
2708 // These setcc operations always fold.
2709 switch (Cond) {
2710 default: break;
2711 case ISD::SETFALSE:
2712 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2713 case ISD::SETTRUE:
2714 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2715
2716 case ISD::SETOEQ:
2717 case ISD::SETOGT:
2718 case ISD::SETOGE:
2719 case ISD::SETOLT:
2720 case ISD::SETOLE:
2721 case ISD::SETONE:
2722 case ISD::SETO:
2723 case ISD::SETUO:
2724 case ISD::SETUEQ:
2725 case ISD::SETUNE:
2726 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2727 break;
2728 }
2729
2730 if (OpVT.isInteger()) {
2731 // For EQ and NE, we can always pick a value for the undef to make the
2732 // predicate pass or fail, so we can return undef.
2733 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2734 // icmp eq/ne X, undef -> undef.
2735 if ((N1.isUndef() || N2.isUndef()) &&
2736 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2737 return GetUndefBooleanConstant();
2738
2739 // If both operands are undef, we can return undef for int comparison.
2740 // icmp undef, undef -> undef.
2741 if (N1.isUndef() && N2.isUndef())
2742 return GetUndefBooleanConstant();
2743
2744 // icmp X, X -> true/false
2745 // icmp X, undef -> true/false because undef could be X.
2746 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2747 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2748 }
2749
2751 const APInt &C2 = N2C->getAPIntValue();
2753 const APInt &C1 = N1C->getAPIntValue();
2754
2756 dl, VT, OpVT);
2757 }
2758 }
2759
2760 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2761 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2762
2763 if (N1CFP && N2CFP) {
2764 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2765 switch (Cond) {
2766 default: break;
2767 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2768 return GetUndefBooleanConstant();
2769 [[fallthrough]];
2770 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2771 OpVT);
2772 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2773 return GetUndefBooleanConstant();
2774 [[fallthrough]];
2776 R==APFloat::cmpLessThan, dl, VT,
2777 OpVT);
2778 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2779 return GetUndefBooleanConstant();
2780 [[fallthrough]];
2781 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2782 OpVT);
2783 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2784 return GetUndefBooleanConstant();
2785 [[fallthrough]];
2787 VT, OpVT);
2788 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2789 return GetUndefBooleanConstant();
2790 [[fallthrough]];
2792 R==APFloat::cmpEqual, dl, VT,
2793 OpVT);
2794 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2795 return GetUndefBooleanConstant();
2796 [[fallthrough]];
2798 R==APFloat::cmpEqual, dl, VT, OpVT);
2799 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2800 OpVT);
2801 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2802 OpVT);
2804 R==APFloat::cmpEqual, dl, VT,
2805 OpVT);
2806 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2807 OpVT);
2809 R==APFloat::cmpLessThan, dl, VT,
2810 OpVT);
2812 R==APFloat::cmpUnordered, dl, VT,
2813 OpVT);
2815 VT, OpVT);
2816 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2817 OpVT);
2818 }
2819 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2820 // Ensure that the constant occurs on the RHS.
2822 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2823 return SDValue();
2824 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2825 /*IsSignaling=*/false, Flags);
2826 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2827 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2828 // If an operand is known to be a nan (or undef that could be a nan), we can
2829 // fold it.
2830 // Choosing NaN for the undef will always make unordered comparison succeed
2831 // and ordered comparison fails.
2832 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2833 switch (ISD::getUnorderedFlavor(Cond)) {
2834 default:
2835 llvm_unreachable("Unknown flavor!");
2836 case 0: // Known false.
2837 return getBoolConstant(false, dl, VT, OpVT);
2838 case 1: // Known true.
2839 return getBoolConstant(true, dl, VT, OpVT);
2840 case 2: // Undefined.
2841 return GetUndefBooleanConstant();
2842 }
2843 }
2844
2845 // Could not fold it.
2846 return SDValue();
2847}
2848
2849/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2850/// use this predicate to simplify operations downstream.
2852 unsigned BitWidth = Op.getScalarValueSizeInBits();
2854}
2855
2856// TODO: Should have argument to specify if sign bit of nan is ignorable.
2858 if (Depth >= MaxRecursionDepth)
2859 return false; // Limit search depth.
2860
2861 unsigned Opc = Op.getOpcode();
2862 switch (Opc) {
2863 case ISD::FABS:
2864 return true;
2865 case ISD::AssertNoFPClass: {
2866 FPClassTest NoFPClass =
2867 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2868
2869 const FPClassTest TestMask = fcNan | fcNegative;
2870 return (NoFPClass & TestMask) == TestMask;
2871 }
2872 case ISD::ARITH_FENCE:
2873 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2874 case ISD::FEXP:
2875 case ISD::FEXP2:
2876 case ISD::FEXP10:
2877 return Op->getFlags().hasNoNaNs();
2878 case ISD::FMINNUM:
2879 case ISD::FMINNUM_IEEE:
2880 case ISD::FMINIMUM:
2881 case ISD::FMINIMUMNUM:
2882 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2883 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2884 case ISD::FMAXNUM:
2885 case ISD::FMAXNUM_IEEE:
2886 case ISD::FMAXIMUM:
2887 case ISD::FMAXIMUMNUM:
2888 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2889 // is sufficient.
2890 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2891 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2892 default:
2893 return false;
2894 }
2895
2896 llvm_unreachable("covered opcode switch");
2897}
2898
2899/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2900/// this predicate to simplify operations downstream. Mask is known to be zero
2901/// for bits that V cannot have.
2903 unsigned Depth) const {
2904 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2905}
2906
2907/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2908/// DemandedElts. We use this predicate to simplify operations downstream.
2909/// Mask is known to be zero for bits that V cannot have.
2911 const APInt &DemandedElts,
2912 unsigned Depth) const {
2913 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2914}
2915
2916/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2917/// DemandedElts. We use this predicate to simplify operations downstream.
2919 unsigned Depth /* = 0 */) const {
2920 return computeKnownBits(V, DemandedElts, Depth).isZero();
2921}
2922
2923/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2925 unsigned Depth) const {
2926 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2927}
2928
2930 const APInt &DemandedElts,
2931 unsigned Depth) const {
2932 EVT VT = Op.getValueType();
2933 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2934
2935 unsigned NumElts = VT.getVectorNumElements();
2936 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2937
2938 APInt KnownZeroElements = APInt::getZero(NumElts);
2939 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2940 if (!DemandedElts[EltIdx])
2941 continue; // Don't query elements that are not demanded.
2942 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2943 if (MaskedVectorIsZero(Op, Mask, Depth))
2944 KnownZeroElements.setBit(EltIdx);
2945 }
2946 return KnownZeroElements;
2947}
2948
2949/// isSplatValue - Return true if the vector V has the same value
2950/// across all DemandedElts. For scalable vectors, we don't know the
2951/// number of lanes at compile time. Instead, we use a 1 bit APInt
2952/// to represent a conservative value for all lanes; that is, that
2953/// one bit value is implicitly splatted across all lanes.
2954bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2955 APInt &UndefElts, unsigned Depth) const {
2956 unsigned Opcode = V.getOpcode();
2957 EVT VT = V.getValueType();
2958 assert(VT.isVector() && "Vector type expected");
2959 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2960 "scalable demanded bits are ignored");
2961
2962 if (!DemandedElts)
2963 return false; // No demanded elts, better to assume we don't know anything.
2964
2965 if (Depth >= MaxRecursionDepth)
2966 return false; // Limit search depth.
2967
2968 // Deal with some common cases here that work for both fixed and scalable
2969 // vector types.
2970 switch (Opcode) {
2971 case ISD::SPLAT_VECTOR:
2972 UndefElts = V.getOperand(0).isUndef()
2973 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2974 : APInt(DemandedElts.getBitWidth(), 0);
2975 return true;
2976 case ISD::ADD:
2977 case ISD::SUB:
2978 case ISD::AND:
2979 case ISD::XOR:
2980 case ISD::OR: {
2981 APInt UndefLHS, UndefRHS;
2982 SDValue LHS = V.getOperand(0);
2983 SDValue RHS = V.getOperand(1);
2984 // Only recognize splats with the same demanded undef elements for both
2985 // operands, otherwise we might fail to handle binop-specific undef
2986 // handling.
2987 // e.g. (and undef, 0) -> 0 etc.
2988 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2989 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2990 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2991 UndefElts = UndefLHS | UndefRHS;
2992 return true;
2993 }
2994 return false;
2995 }
2996 case ISD::ABS:
2998 case ISD::TRUNCATE:
2999 case ISD::SIGN_EXTEND:
3000 case ISD::ZERO_EXTEND:
3001 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3002 default:
3003 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3004 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3005 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3006 Depth);
3007 break;
3008 }
3009
3010 // We don't support other cases than those above for scalable vectors at
3011 // the moment.
3012 if (VT.isScalableVector())
3013 return false;
3014
3015 unsigned NumElts = VT.getVectorNumElements();
3016 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3017 UndefElts = APInt::getZero(NumElts);
3018
3019 switch (Opcode) {
3020 case ISD::BUILD_VECTOR: {
3021 SDValue Scl;
3022 for (unsigned i = 0; i != NumElts; ++i) {
3023 SDValue Op = V.getOperand(i);
3024 if (Op.isUndef()) {
3025 UndefElts.setBit(i);
3026 continue;
3027 }
3028 if (!DemandedElts[i])
3029 continue;
3030 if (Scl && Scl != Op)
3031 return false;
3032 Scl = Op;
3033 }
3034 return true;
3035 }
3036 case ISD::VECTOR_SHUFFLE: {
3037 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3038 APInt DemandedLHS = APInt::getZero(NumElts);
3039 APInt DemandedRHS = APInt::getZero(NumElts);
3040 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3041 for (int i = 0; i != (int)NumElts; ++i) {
3042 int M = Mask[i];
3043 if (M < 0) {
3044 UndefElts.setBit(i);
3045 continue;
3046 }
3047 if (!DemandedElts[i])
3048 continue;
3049 if (M < (int)NumElts)
3050 DemandedLHS.setBit(M);
3051 else
3052 DemandedRHS.setBit(M - NumElts);
3053 }
3054
3055 // If we aren't demanding either op, assume there's no splat.
3056 // If we are demanding both ops, assume there's no splat.
3057 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3058 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3059 return false;
3060
3061 // See if the demanded elts of the source op is a splat or we only demand
3062 // one element, which should always be a splat.
3063 // TODO: Handle source ops splats with undefs.
3064 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3065 APInt SrcUndefs;
3066 return (SrcElts.popcount() == 1) ||
3067 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3068 (SrcElts & SrcUndefs).isZero());
3069 };
3070 if (!DemandedLHS.isZero())
3071 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3072 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3073 }
3075 // Offset the demanded elts by the subvector index.
3076 SDValue Src = V.getOperand(0);
3077 // We don't support scalable vectors at the moment.
3078 if (Src.getValueType().isScalableVector())
3079 return false;
3080 uint64_t Idx = V.getConstantOperandVal(1);
3081 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3082 APInt UndefSrcElts;
3083 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3084 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3085 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3086 return true;
3087 }
3088 break;
3089 }
3093 // Widen the demanded elts by the src element count.
3094 SDValue Src = V.getOperand(0);
3095 // We don't support scalable vectors at the moment.
3096 if (Src.getValueType().isScalableVector())
3097 return false;
3098 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3099 APInt UndefSrcElts;
3100 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3101 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3102 UndefElts = UndefSrcElts.trunc(NumElts);
3103 return true;
3104 }
3105 break;
3106 }
3107 case ISD::BITCAST: {
3108 SDValue Src = V.getOperand(0);
3109 EVT SrcVT = Src.getValueType();
3110 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3111 unsigned BitWidth = VT.getScalarSizeInBits();
3112
3113 // Ignore bitcasts from unsupported types.
3114 // TODO: Add fp support?
3115 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3116 break;
3117
3118 // Bitcast 'small element' vector to 'large element' vector.
3119 if ((BitWidth % SrcBitWidth) == 0) {
3120 // See if each sub element is a splat.
3121 unsigned Scale = BitWidth / SrcBitWidth;
3122 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3123 APInt ScaledDemandedElts =
3124 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3125 for (unsigned I = 0; I != Scale; ++I) {
3126 APInt SubUndefElts;
3127 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3128 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3129 SubDemandedElts &= ScaledDemandedElts;
3130 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3131 return false;
3132 // TODO: Add support for merging sub undef elements.
3133 if (!SubUndefElts.isZero())
3134 return false;
3135 }
3136 return true;
3137 }
3138 break;
3139 }
3140 }
3141
3142 return false;
3143}
3144
3145/// Helper wrapper to main isSplatValue function.
3146bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3147 EVT VT = V.getValueType();
3148 assert(VT.isVector() && "Vector type expected");
3149
3150 APInt UndefElts;
3151 // Since the number of lanes in a scalable vector is unknown at compile time,
3152 // we track one bit which is implicitly broadcast to all lanes. This means
3153 // that all lanes in a scalable vector are considered demanded.
3154 APInt DemandedElts
3156 return isSplatValue(V, DemandedElts, UndefElts) &&
3157 (AllowUndefs || !UndefElts);
3158}
3159
3162
3163 EVT VT = V.getValueType();
3164 unsigned Opcode = V.getOpcode();
3165 switch (Opcode) {
3166 default: {
3167 APInt UndefElts;
3168 // Since the number of lanes in a scalable vector is unknown at compile time,
3169 // we track one bit which is implicitly broadcast to all lanes. This means
3170 // that all lanes in a scalable vector are considered demanded.
3171 APInt DemandedElts
3173
3174 if (isSplatValue(V, DemandedElts, UndefElts)) {
3175 if (VT.isScalableVector()) {
3176 // DemandedElts and UndefElts are ignored for scalable vectors, since
3177 // the only supported cases are SPLAT_VECTOR nodes.
3178 SplatIdx = 0;
3179 } else {
3180 // Handle case where all demanded elements are UNDEF.
3181 if (DemandedElts.isSubsetOf(UndefElts)) {
3182 SplatIdx = 0;
3183 return getUNDEF(VT);
3184 }
3185 SplatIdx = (UndefElts & DemandedElts).countr_one();
3186 }
3187 return V;
3188 }
3189 break;
3190 }
3191 case ISD::SPLAT_VECTOR:
3192 SplatIdx = 0;
3193 return V;
3194 case ISD::VECTOR_SHUFFLE: {
3195 assert(!VT.isScalableVector());
3196 // Check if this is a shuffle node doing a splat.
3197 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3198 // getTargetVShiftNode currently struggles without the splat source.
3199 auto *SVN = cast<ShuffleVectorSDNode>(V);
3200 if (!SVN->isSplat())
3201 break;
3202 int Idx = SVN->getSplatIndex();
3203 int NumElts = V.getValueType().getVectorNumElements();
3204 SplatIdx = Idx % NumElts;
3205 return V.getOperand(Idx / NumElts);
3206 }
3207 }
3208
3209 return SDValue();
3210}
3211
3213 int SplatIdx;
3214 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3215 EVT SVT = SrcVector.getValueType().getScalarType();
3216 EVT LegalSVT = SVT;
3217 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3218 if (!SVT.isInteger())
3219 return SDValue();
3220 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3221 if (LegalSVT.bitsLT(SVT))
3222 return SDValue();
3223 }
3224 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3225 }
3226 return SDValue();
3227}
3228
3229std::optional<ConstantRange>
3231 unsigned Depth) const {
3232 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3233 V.getOpcode() == ISD::SRA) &&
3234 "Unknown shift node");
3235 // Shifting more than the bitwidth is not valid.
3236 unsigned BitWidth = V.getScalarValueSizeInBits();
3237
3238 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3239 const APInt &ShAmt = Cst->getAPIntValue();
3240 if (ShAmt.uge(BitWidth))
3241 return std::nullopt;
3242 return ConstantRange(ShAmt);
3243 }
3244
3245 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3246 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3247 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3248 if (!DemandedElts[i])
3249 continue;
3250 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3251 if (!SA) {
3252 MinAmt = MaxAmt = nullptr;
3253 break;
3254 }
3255 const APInt &ShAmt = SA->getAPIntValue();
3256 if (ShAmt.uge(BitWidth))
3257 return std::nullopt;
3258 if (!MinAmt || MinAmt->ugt(ShAmt))
3259 MinAmt = &ShAmt;
3260 if (!MaxAmt || MaxAmt->ult(ShAmt))
3261 MaxAmt = &ShAmt;
3262 }
3263 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3264 "Failed to find matching min/max shift amounts");
3265 if (MinAmt && MaxAmt)
3266 return ConstantRange(*MinAmt, *MaxAmt + 1);
3267 }
3268
3269 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3270 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3271 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3272 if (KnownAmt.getMaxValue().ult(BitWidth))
3273 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3274
3275 return std::nullopt;
3276}
3277
3278std::optional<unsigned>
3280 unsigned Depth) const {
3281 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3282 V.getOpcode() == ISD::SRA) &&
3283 "Unknown shift node");
3284 if (std::optional<ConstantRange> AmtRange =
3285 getValidShiftAmountRange(V, DemandedElts, Depth))
3286 if (const APInt *ShAmt = AmtRange->getSingleElement())
3287 return ShAmt->getZExtValue();
3288 return std::nullopt;
3289}
3290
3291std::optional<unsigned>
3293 APInt DemandedElts = getDemandAllEltsMask(V);
3294 return getValidShiftAmount(V, DemandedElts, Depth);
3295}
3296
3297std::optional<unsigned>
3299 unsigned Depth) const {
3300 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3301 V.getOpcode() == ISD::SRA) &&
3302 "Unknown shift node");
3303 if (std::optional<ConstantRange> AmtRange =
3304 getValidShiftAmountRange(V, DemandedElts, Depth))
3305 return AmtRange->getUnsignedMin().getZExtValue();
3306 return std::nullopt;
3307}
3308
3309std::optional<unsigned>
3311 APInt DemandedElts = getDemandAllEltsMask(V);
3312 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3313}
3314
3315std::optional<unsigned>
3317 unsigned Depth) const {
3318 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3319 V.getOpcode() == ISD::SRA) &&
3320 "Unknown shift node");
3321 if (std::optional<ConstantRange> AmtRange =
3322 getValidShiftAmountRange(V, DemandedElts, Depth))
3323 return AmtRange->getUnsignedMax().getZExtValue();
3324 return std::nullopt;
3325}
3326
3327std::optional<unsigned>
3329 APInt DemandedElts = getDemandAllEltsMask(V);
3330 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3331}
3332
3333/// Determine which bits of Op are known to be either zero or one and return
3334/// them in Known. For vectors, the known bits are those that are shared by
3335/// every vector element.
3337 APInt DemandedElts = getDemandAllEltsMask(Op);
3338 return computeKnownBits(Op, DemandedElts, Depth);
3339}
3340
3341/// Determine which bits of Op are known to be either zero or one and return
3342/// them in Known. The DemandedElts argument allows us to only collect the known
3343/// bits that are shared by the requested vector elements.
3345 unsigned Depth) const {
3346 unsigned BitWidth = Op.getScalarValueSizeInBits();
3347
3348 KnownBits Known(BitWidth); // Don't know anything.
3349
3350 if (auto OptAPInt = Op->bitcastToAPInt()) {
3351 // We know all of the bits for a constant!
3352 return KnownBits::makeConstant(*std::move(OptAPInt));
3353 }
3354
3355 if (Depth >= MaxRecursionDepth)
3356 return Known; // Limit search depth.
3357
3358 KnownBits Known2;
3359 unsigned NumElts = DemandedElts.getBitWidth();
3360 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3361 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3362 assert((!Op.getValueType().isFixedLengthVector() ||
3363 NumElts == Op.getValueType().getVectorNumElements()) &&
3364 "Unexpected vector size");
3365
3366 if (!DemandedElts)
3367 return Known; // No demanded elts, better to assume we don't know anything.
3368
3369 unsigned Opcode = Op.getOpcode();
3370 switch (Opcode) {
3371 case ISD::FREEZE: {
3372 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3374 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3375 break;
3376 }
3377 case ISD::MERGE_VALUES:
3378 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3379 Depth + 1);
3380 case ISD::SPLAT_VECTOR: {
3381 SDValue SrcOp = Op.getOperand(0);
3382 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3383 "Expected SPLAT_VECTOR implicit truncation");
3384 // Implicitly truncate the bits to match the official semantics of
3385 // SPLAT_VECTOR.
3387 break;
3388 }
3390 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3391 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3392 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3393 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3394 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3395 }
3396 break;
3397 }
3398 case ISD::STEP_VECTOR: {
3399 const APInt &Step = Op.getConstantOperandAPInt(0);
3400
3401 if (Step.isPowerOf2())
3402 Known.Zero.setLowBits(Step.logBase2());
3403
3405
3406 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3407 break;
3408 const APInt MinNumElts =
3409 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3410
3411 bool Overflow;
3412 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3414 .umul_ov(MinNumElts, Overflow);
3415 if (Overflow)
3416 break;
3417
3418 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3419 if (Overflow)
3420 break;
3421
3422 Known.Zero.setHighBits(MaxValue.countl_zero());
3423 break;
3424 }
3425 case ISD::BUILD_VECTOR:
3426 assert(!Op.getValueType().isScalableVector());
3427 // Collect the known bits that are shared by every demanded vector element.
3428 Known.setAllConflict();
3429 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3430 if (!DemandedElts[i])
3431 continue;
3432
3433 SDValue SrcOp = Op.getOperand(i);
3434 if (SrcOp.getOpcode() == ISD::POISON)
3435 continue;
3436
3437 Known2 = computeKnownBits(SrcOp, Depth + 1);
3438
3439 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3440 if (SrcOp.getValueSizeInBits() != BitWidth) {
3441 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3442 "Expected BUILD_VECTOR implicit truncation");
3443 Known2 = Known2.trunc(BitWidth);
3444 }
3445
3446 // Known bits are the values that are shared by every demanded element.
3447 Known = Known.intersectWith(Known2);
3448
3449 // If we don't know any bits, early out.
3450 if (Known.isUnknown())
3451 break;
3452 }
3453
3454 // If every demanded element was poison, we know nothing.
3455 if (Known.hasConflict())
3456 Known.resetAll();
3457 break;
3458 case ISD::VECTOR_COMPRESS: {
3459 SDValue Vec = Op.getOperand(0);
3460 SDValue PassThru = Op.getOperand(2);
3461 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3462 // If we don't know any bits, early out.
3463 if (Known.isUnknown())
3464 break;
3465 Known2 = computeKnownBits(Vec, Depth + 1);
3466 Known = Known.intersectWith(Known2);
3467 break;
3468 }
3469 case ISD::VECTOR_SHUFFLE: {
3470 assert(!Op.getValueType().isScalableVector());
3471 // Collect the known bits that are shared by every vector element referenced
3472 // by the shuffle.
3473 APInt DemandedLHS, DemandedRHS;
3475 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3476 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3477 DemandedLHS, DemandedRHS))
3478 break;
3479
3480 // Known bits are the values that are shared by every demanded element.
3481 Known.setAllConflict();
3482 if (!!DemandedLHS) {
3483 SDValue LHS = Op.getOperand(0);
3484 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3485 Known = Known.intersectWith(Known2);
3486 }
3487 // If we don't know any bits, early out.
3488 if (Known.isUnknown())
3489 break;
3490 if (!!DemandedRHS) {
3491 SDValue RHS = Op.getOperand(1);
3492 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3493 Known = Known.intersectWith(Known2);
3494 }
3495 break;
3496 }
3497 case ISD::VSCALE: {
3499 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3501 break;
3502 }
3503 case ISD::CONCAT_VECTORS: {
3504 if (Op.getValueType().isScalableVector())
3505 break;
3506 // Split DemandedElts and test each of the demanded subvectors.
3507 Known.setAllConflict();
3508 EVT SubVectorVT = Op.getOperand(0).getValueType();
3509 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3510 unsigned NumSubVectors = Op.getNumOperands();
3511 for (unsigned i = 0; i != NumSubVectors; ++i) {
3512 APInt DemandedSub =
3513 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3514 if (!!DemandedSub) {
3515 SDValue Sub = Op.getOperand(i);
3516 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3517 Known = Known.intersectWith(Known2);
3518 }
3519 // If we don't know any bits, early out.
3520 if (Known.isUnknown())
3521 break;
3522 }
3523 break;
3524 }
3525 case ISD::INSERT_SUBVECTOR: {
3526 if (Op.getValueType().isScalableVector())
3527 break;
3528 // Demand any elements from the subvector and the remainder from the src its
3529 // inserted into.
3530 SDValue Src = Op.getOperand(0);
3531 SDValue Sub = Op.getOperand(1);
3532 uint64_t Idx = Op.getConstantOperandVal(2);
3533 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3534 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3535 APInt DemandedSrcElts = DemandedElts;
3536 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3537
3538 Known.setAllConflict();
3539 if (!!DemandedSubElts) {
3540 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3541 if (Known.isUnknown())
3542 break; // early-out.
3543 }
3544 if (!!DemandedSrcElts) {
3545 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3546 Known = Known.intersectWith(Known2);
3547 }
3548 break;
3549 }
3551 // Offset the demanded elts by the subvector index.
3552 SDValue Src = Op.getOperand(0);
3553
3554 APInt DemandedSrcElts;
3555 if (Src.getValueType().isScalableVector())
3556 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3557 else {
3558 uint64_t Idx = Op.getConstantOperandVal(1);
3559 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3560 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3561 }
3562 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3563 break;
3564 }
3565 case ISD::SCALAR_TO_VECTOR: {
3566 if (Op.getValueType().isScalableVector())
3567 break;
3568 // We know about scalar_to_vector as much as we know about it source,
3569 // which becomes the first element of otherwise unknown vector.
3570 if (DemandedElts != 1)
3571 break;
3572
3573 SDValue N0 = Op.getOperand(0);
3574 Known = computeKnownBits(N0, Depth + 1);
3575 if (N0.getValueSizeInBits() != BitWidth)
3576 Known = Known.trunc(BitWidth);
3577
3578 break;
3579 }
3580 case ISD::BITCAST: {
3581 if (Op.getValueType().isScalableVector())
3582 break;
3583
3584 SDValue N0 = Op.getOperand(0);
3585 EVT SubVT = N0.getValueType();
3586 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3587
3588 // Ignore bitcasts from unsupported types.
3589 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3590 break;
3591
3592 // Fast handling of 'identity' bitcasts.
3593 if (BitWidth == SubBitWidth) {
3594 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3595 break;
3596 }
3597
3598 bool IsLE = getDataLayout().isLittleEndian();
3599
3600 // Bitcast 'small element' vector to 'large element' scalar/vector.
3601 if ((BitWidth % SubBitWidth) == 0) {
3602 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3603
3604 // Collect known bits for the (larger) output by collecting the known
3605 // bits from each set of sub elements and shift these into place.
3606 // We need to separately call computeKnownBits for each set of
3607 // sub elements as the knownbits for each is likely to be different.
3608 unsigned SubScale = BitWidth / SubBitWidth;
3609 APInt SubDemandedElts(NumElts * SubScale, 0);
3610 for (unsigned i = 0; i != NumElts; ++i)
3611 if (DemandedElts[i])
3612 SubDemandedElts.setBit(i * SubScale);
3613
3614 for (unsigned i = 0; i != SubScale; ++i) {
3615 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3616 Depth + 1);
3617 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3618 Known.insertBits(Known2, SubBitWidth * Shifts);
3619 }
3620 }
3621
3622 // Bitcast 'large element' scalar/vector to 'small element' vector.
3623 if ((SubBitWidth % BitWidth) == 0) {
3624 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3625
3626 // Collect known bits for the (smaller) output by collecting the known
3627 // bits from the overlapping larger input elements and extracting the
3628 // sub sections we actually care about.
3629 unsigned SubScale = SubBitWidth / BitWidth;
3630 APInt SubDemandedElts =
3631 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3632 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3633
3634 Known.setAllConflict();
3635 for (unsigned i = 0; i != NumElts; ++i)
3636 if (DemandedElts[i]) {
3637 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3638 unsigned Offset = (Shifts % SubScale) * BitWidth;
3639 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3640 // If we don't know any bits, early out.
3641 if (Known.isUnknown())
3642 break;
3643 }
3644 }
3645 break;
3646 }
3647 case ISD::AND:
3648 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3649 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3650
3651 Known &= Known2;
3652 break;
3653 case ISD::OR:
3654 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3655 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3656
3657 Known |= Known2;
3658 break;
3659 case ISD::XOR:
3660 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3661 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3662
3663 Known ^= Known2;
3664 break;
3665 case ISD::MUL: {
3666 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3668 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3669 // TODO: SelfMultiply can be poison, but not undef.
3670 if (SelfMultiply)
3671 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3672 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3673 Depth + 1);
3674 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3675
3676 // If the multiplication is known not to overflow, the product of a number
3677 // with itself is non-negative. Only do this if we didn't already computed
3678 // the opposite value for the sign bit.
3679 if (Op->getFlags().hasNoSignedWrap() &&
3680 Op.getOperand(0) == Op.getOperand(1) &&
3681 !Known.isNegative())
3682 Known.makeNonNegative();
3683 break;
3684 }
3685 case ISD::MULHU: {
3686 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3687 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3688 Known = KnownBits::mulhu(Known, Known2);
3689 break;
3690 }
3691 case ISD::MULHS: {
3692 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3693 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3694 Known = KnownBits::mulhs(Known, Known2);
3695 break;
3696 }
3697 case ISD::ABDU: {
3698 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3699 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3700 Known = KnownBits::abdu(Known, Known2);
3701 break;
3702 }
3703 case ISD::ABDS: {
3704 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3705 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3706 Known = KnownBits::abds(Known, Known2);
3707 unsigned SignBits1 =
3708 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3709 if (SignBits1 == 1)
3710 break;
3711 unsigned SignBits0 =
3712 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3713 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3714 break;
3715 }
3716 case ISD::UMUL_LOHI: {
3717 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3718 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3719 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3720 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3721 if (Op.getResNo() == 0)
3722 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3723 else
3724 Known = KnownBits::mulhu(Known, Known2);
3725 break;
3726 }
3727 case ISD::SMUL_LOHI: {
3728 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3729 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3730 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3731 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3732 if (Op.getResNo() == 0)
3733 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3734 else
3735 Known = KnownBits::mulhs(Known, Known2);
3736 break;
3737 }
3738 case ISD::AVGFLOORU: {
3739 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3740 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3741 Known = KnownBits::avgFloorU(Known, Known2);
3742 break;
3743 }
3744 case ISD::AVGCEILU: {
3745 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3746 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3747 Known = KnownBits::avgCeilU(Known, Known2);
3748 break;
3749 }
3750 case ISD::AVGFLOORS: {
3751 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3752 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3753 Known = KnownBits::avgFloorS(Known, Known2);
3754 break;
3755 }
3756 case ISD::AVGCEILS: {
3757 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3758 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3759 Known = KnownBits::avgCeilS(Known, Known2);
3760 break;
3761 }
3762 case ISD::SELECT:
3763 case ISD::VSELECT:
3764 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3765 // If we don't know any bits, early out.
3766 if (Known.isUnknown())
3767 break;
3768 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3769
3770 // Only known if known in both the LHS and RHS.
3771 Known = Known.intersectWith(Known2);
3772 break;
3773 case ISD::SELECT_CC:
3774 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3775 // If we don't know any bits, early out.
3776 if (Known.isUnknown())
3777 break;
3778 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3779
3780 // Only known if known in both the LHS and RHS.
3781 Known = Known.intersectWith(Known2);
3782 break;
3783 case ISD::SMULO:
3784 case ISD::UMULO:
3785 if (Op.getResNo() != 1)
3786 break;
3787 // The boolean result conforms to getBooleanContents.
3788 // If we know the result of a setcc has the top bits zero, use this info.
3789 // We know that we have an integer-based boolean since these operations
3790 // are only available for integer.
3791 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3793 BitWidth > 1)
3794 Known.Zero.setBitsFrom(1);
3795 break;
3796 case ISD::SETCC:
3797 case ISD::SETCCCARRY:
3798 case ISD::STRICT_FSETCC:
3799 case ISD::STRICT_FSETCCS: {
3800 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3801 // If we know the result of a setcc has the top bits zero, use this info.
3802 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3804 BitWidth > 1)
3805 Known.Zero.setBitsFrom(1);
3806 break;
3807 }
3808 case ISD::SHL: {
3809 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3810 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3811
3812 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3813 bool NSW = Op->getFlags().hasNoSignedWrap();
3814
3815 bool ShAmtNonZero = Known2.isNonZero();
3816
3817 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3818
3819 // Minimum shift low bits are known zero.
3820 if (std::optional<unsigned> ShMinAmt =
3821 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3822 Known.Zero.setLowBits(*ShMinAmt);
3823 break;
3824 }
3825 case ISD::SRL:
3826 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3827 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3828 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3829 Op->getFlags().hasExact());
3830
3831 // Minimum shift high bits are known zero.
3832 if (std::optional<unsigned> ShMinAmt =
3833 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3834 Known.Zero.setHighBits(*ShMinAmt);
3835 break;
3836 case ISD::SRA:
3837 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3838 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3839 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3840 Op->getFlags().hasExact());
3841 break;
3842 case ISD::ROTL:
3843 case ISD::ROTR:
3844 if (ConstantSDNode *C =
3845 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3846 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3847
3848 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3849
3850 // Canonicalize to ROTR.
3851 if (Opcode == ISD::ROTL && Amt != 0)
3852 Amt = BitWidth - Amt;
3853
3854 Known.Zero = Known.Zero.rotr(Amt);
3855 Known.One = Known.One.rotr(Amt);
3856 }
3857 break;
3858 case ISD::FSHL:
3859 case ISD::FSHR:
3860 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3861 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3862
3863 // For fshl, 0-shift returns the 1st arg.
3864 // For fshr, 0-shift returns the 2nd arg.
3865 if (Amt == 0) {
3866 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3867 DemandedElts, Depth + 1);
3868 break;
3869 }
3870
3871 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3872 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3873 const APInt ShAmt(BitWidth, Amt);
3874 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3875 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3876 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3877 : KnownBits::fshr(Known, Known2, ShAmt);
3878 }
3879 break;
3880 case ISD::SHL_PARTS:
3881 case ISD::SRA_PARTS:
3882 case ISD::SRL_PARTS: {
3883 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3884
3885 // Collect lo/hi source values and concatenate.
3886 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3887 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3888 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3889 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3890 Known = Known2.concat(Known);
3891
3892 // Collect shift amount.
3893 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3894
3895 if (Opcode == ISD::SHL_PARTS)
3896 Known = KnownBits::shl(Known, Known2);
3897 else if (Opcode == ISD::SRA_PARTS)
3898 Known = KnownBits::ashr(Known, Known2);
3899 else // if (Opcode == ISD::SRL_PARTS)
3900 Known = KnownBits::lshr(Known, Known2);
3901
3902 // TODO: Minimum shift low/high bits are known zero.
3903
3904 if (Op.getResNo() == 0)
3905 Known = Known.extractBits(LoBits, 0);
3906 else
3907 Known = Known.extractBits(HiBits, LoBits);
3908 break;
3909 }
3911 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3912 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3913 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3914 break;
3915 }
3916 case ISD::CTTZ:
3917 case ISD::CTTZ_ZERO_POISON: {
3918 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3919 // If we have a known 1, its position is our upper bound.
3920 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3921 unsigned LowBits = llvm::bit_width(PossibleTZ);
3922 Known.Zero.setBitsFrom(LowBits);
3923 break;
3924 }
3925 case ISD::CTLZ:
3926 case ISD::CTLZ_ZERO_POISON: {
3927 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3928 // If we have a known 1, its position is our upper bound.
3929 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3930 unsigned LowBits = llvm::bit_width(PossibleLZ);
3931 Known.Zero.setBitsFrom(LowBits);
3932 break;
3933 }
3934 case ISD::CTLS: {
3935 unsigned MinRedundantSignBits =
3936 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3937 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3939 Known = Range.toKnownBits();
3940 break;
3941 }
3942 case ISD::CTPOP: {
3943 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3944 // If we know some of the bits are zero, they can't be one.
3945 unsigned PossibleOnes = Known2.countMaxPopulation();
3946 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3947 break;
3948 }
3949 case ISD::PARITY: {
3950 // Parity returns 0 everywhere but the LSB.
3951 Known.Zero.setBitsFrom(1);
3952 break;
3953 }
3954 case ISD::PDEP: {
3955 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3956 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3957 Known = KnownBits::pdep(Known2, Known);
3958 break;
3959 }
3960 case ISD::PEXT: {
3961 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3962 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3963 Known = KnownBits::pext(Known2, Known);
3964 break;
3965 }
3966 case ISD::CLMUL: {
3967 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3968 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3969 Known = KnownBits::clmul(Known, Known2);
3970 break;
3971 }
3972 case ISD::MGATHER:
3973 case ISD::MLOAD: {
3974 ISD::LoadExtType ETy =
3975 (Opcode == ISD::MGATHER)
3976 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3977 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3978 if (ETy == ISD::ZEXTLOAD) {
3979 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3980 KnownBits Known0(MemVT.getScalarSizeInBits());
3981 return Known0.zext(BitWidth);
3982 }
3983 break;
3984 }
3985 case ISD::LOAD: {
3987 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3988 if (ISD::isNON_EXTLoad(LD) && Cst) {
3989 // Determine any common known bits from the loaded constant pool value.
3990 Type *CstTy = Cst->getType();
3991 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3992 !Op.getValueType().isScalableVector()) {
3993 // If its a vector splat, then we can (quickly) reuse the scalar path.
3994 // NOTE: We assume all elements match and none are UNDEF.
3995 if (CstTy->isVectorTy()) {
3996 if (const Constant *Splat = Cst->getSplatValue()) {
3997 Cst = Splat;
3998 CstTy = Cst->getType();
3999 }
4000 }
4001 // TODO - do we need to handle different bitwidths?
4002 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4003 // Iterate across all vector elements finding common known bits.
4004 Known.setAllConflict();
4005 for (unsigned i = 0; i != NumElts; ++i) {
4006 if (!DemandedElts[i])
4007 continue;
4008 if (Constant *Elt = Cst->getAggregateElement(i)) {
4009 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4010 const APInt &Value = CInt->getValue();
4011 Known.One &= Value;
4012 Known.Zero &= ~Value;
4013 continue;
4014 }
4015 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4016 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4017 Known.One &= Value;
4018 Known.Zero &= ~Value;
4019 continue;
4020 }
4021 }
4022 Known.One.clearAllBits();
4023 Known.Zero.clearAllBits();
4024 break;
4025 }
4026 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4027 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4028 Known = KnownBits::makeConstant(CInt->getValue());
4029 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4030 Known =
4031 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4032 }
4033 }
4034 }
4035 } else if (Op.getResNo() == 0) {
4036 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4037 KnownBits KnownScalarMemory(ScalarMemorySize);
4038 if (const MDNode *MD = LD->getRanges())
4039 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4040
4041 // Extend the Known bits from memory to the size of the scalar result.
4042 if (ISD::isZEXTLoad(Op.getNode()))
4043 Known = KnownScalarMemory.zext(BitWidth);
4044 else if (ISD::isSEXTLoad(Op.getNode()))
4045 Known = KnownScalarMemory.sext(BitWidth);
4046 else if (ISD::isEXTLoad(Op.getNode()))
4047 Known = KnownScalarMemory.anyext(BitWidth);
4048 else
4049 Known = KnownScalarMemory;
4050 assert(Known.getBitWidth() == BitWidth);
4051 return Known;
4052 }
4053 break;
4054 }
4056 if (Op.getValueType().isScalableVector())
4057 break;
4058 EVT InVT = Op.getOperand(0).getValueType();
4059 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4060 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4061 Known = Known.zext(BitWidth);
4062 break;
4063 }
4064 case ISD::ZERO_EXTEND: {
4065 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4066 Known = Known.zext(BitWidth);
4067 break;
4068 }
4070 if (Op.getValueType().isScalableVector())
4071 break;
4072 EVT InVT = Op.getOperand(0).getValueType();
4073 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4074 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4075 // If the sign bit is known to be zero or one, then sext will extend
4076 // it to the top bits, else it will just zext.
4077 Known = Known.sext(BitWidth);
4078 break;
4079 }
4080 case ISD::SIGN_EXTEND: {
4081 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4082 // If the sign bit is known to be zero or one, then sext will extend
4083 // it to the top bits, else it will just zext.
4084 Known = Known.sext(BitWidth);
4085 break;
4086 }
4088 if (Op.getValueType().isScalableVector())
4089 break;
4090 EVT InVT = Op.getOperand(0).getValueType();
4091 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4092 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4093 Known = Known.anyext(BitWidth);
4094 break;
4095 }
4096 case ISD::ANY_EXTEND: {
4097 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4098 Known = Known.anyext(BitWidth);
4099 break;
4100 }
4101 case ISD::TRUNCATE: {
4102 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4103 Known = Known.trunc(BitWidth);
4104 break;
4105 }
4106 case ISD::TRUNCATE_SSAT_S: {
4107 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4108 Known = Known.truncSSat(BitWidth);
4109 break;
4110 }
4111 case ISD::TRUNCATE_SSAT_U: {
4112 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4113 Known = Known.truncSSatU(BitWidth);
4114 break;
4115 }
4116 case ISD::TRUNCATE_USAT_U: {
4117 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4118 Known = Known.truncUSat(BitWidth);
4119 break;
4120 }
4121 case ISD::AssertZext: {
4122 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4124 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4125 Known.Zero |= (~InMask);
4126 Known.One &= (~Known.Zero);
4127 break;
4128 }
4129 case ISD::AssertAlign: {
4130 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4131 assert(LogOfAlign != 0);
4132
4133 // TODO: Should use maximum with source
4134 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4135 // well as clearing one bits.
4136 Known.Zero.setLowBits(LogOfAlign);
4137 Known.One.clearLowBits(LogOfAlign);
4138 break;
4139 }
4140 case ISD::AssertNoFPClass: {
4141 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4142
4143 FPClassTest NoFPClass =
4144 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4145 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4146 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4147 // Cannot be negative.
4148 Known.makeNonNegative();
4149 }
4150
4151 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4152 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4153 // Cannot be positive.
4154 Known.makeNegative();
4155 }
4156
4157 break;
4158 }
4159 case ISD::FABS:
4160 // fabs clears the sign bit
4161 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4162 Known.makeNonNegative();
4163 break;
4164 case ISD::FGETSIGN:
4165 // All bits are zero except the low bit.
4166 Known.Zero.setBitsFrom(1);
4167 break;
4168 case ISD::ADD: {
4169 SDNodeFlags Flags = Op.getNode()->getFlags();
4170 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4171 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4172 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4174 Op.getOperand(0), DemandedElts,
4176 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4177 Flags.hasNoUnsignedWrap(), SelfAdd);
4178 break;
4179 }
4180 case ISD::SUB: {
4181 SDNodeFlags Flags = Op.getNode()->getFlags();
4182 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4183 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4184 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4185 Flags.hasNoUnsignedWrap());
4186 break;
4187 }
4188 case ISD::USUBO:
4189 case ISD::SSUBO:
4190 case ISD::USUBO_CARRY:
4191 case ISD::SSUBO_CARRY:
4192 if (Op.getResNo() == 1) {
4193 // If we know the result of a setcc has the top bits zero, use this info.
4194 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4196 BitWidth > 1)
4197 Known.Zero.setBitsFrom(1);
4198 break;
4199 }
4200 [[fallthrough]];
4201 case ISD::SUBC: {
4202 assert(Op.getResNo() == 0 &&
4203 "We only compute knownbits for the difference here.");
4204
4205 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4206 KnownBits Borrow(1);
4207 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4208 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4209 // Borrow has bit width 1
4210 Borrow = Borrow.trunc(1);
4211 } else {
4212 Borrow.setAllZero();
4213 }
4214
4215 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4216 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4217 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4218 break;
4219 }
4220 case ISD::UADDO:
4221 case ISD::SADDO:
4222 case ISD::UADDO_CARRY:
4223 case ISD::SADDO_CARRY:
4224 if (Op.getResNo() == 1) {
4225 // If we know the result of a setcc has the top bits zero, use this info.
4226 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4228 BitWidth > 1)
4229 Known.Zero.setBitsFrom(1);
4230 break;
4231 }
4232 [[fallthrough]];
4233 case ISD::ADDC:
4234 case ISD::ADDE: {
4235 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4236
4237 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4238 KnownBits Carry(1);
4239 if (Opcode == ISD::ADDE)
4240 // Can't track carry from glue, set carry to unknown.
4241 Carry.resetAll();
4242 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4243 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4244 // Carry has bit width 1
4245 Carry = Carry.trunc(1);
4246 } else {
4247 Carry.setAllZero();
4248 }
4249
4250 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4251 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4252 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4253 break;
4254 }
4255 case ISD::UDIV: {
4256 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4257 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4258 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4259 break;
4260 }
4261 case ISD::SDIV: {
4262 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4263 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4264 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4265 break;
4266 }
4267 case ISD::SREM: {
4268 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4269 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4270 Known = KnownBits::srem(Known, Known2);
4271 break;
4272 }
4273 case ISD::UREM: {
4274 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4275 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4276 Known = KnownBits::urem(Known, Known2);
4277 break;
4278 }
4279 case ISD::EXTRACT_ELEMENT: {
4280 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4281 const unsigned Index = Op.getConstantOperandVal(1);
4282 const unsigned EltBitWidth = Op.getValueSizeInBits();
4283
4284 // Remove low part of known bits mask
4285 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4286 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4287
4288 // Remove high part of known bit mask
4289 Known = Known.trunc(EltBitWidth);
4290 break;
4291 }
4293 SDValue InVec = Op.getOperand(0);
4294 SDValue EltNo = Op.getOperand(1);
4295 EVT VecVT = InVec.getValueType();
4296 // computeKnownBits not yet implemented for scalable vectors.
4297 if (VecVT.isScalableVector())
4298 break;
4299 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4300 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4301
4302 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4303 // anything about the extended bits.
4304 if (BitWidth > EltBitWidth)
4305 Known = Known.trunc(EltBitWidth);
4306
4307 // If we know the element index, just demand that vector element, else for
4308 // an unknown element index, ignore DemandedElts and demand them all.
4309 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4310 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4311 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4312 DemandedSrcElts =
4313 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4314
4315 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4316 if (BitWidth > EltBitWidth)
4317 Known = Known.anyext(BitWidth);
4318 break;
4319 }
4321 if (Op.getValueType().isScalableVector())
4322 break;
4323
4324 // If we know the element index, split the demand between the
4325 // source vector and the inserted element, otherwise assume we need
4326 // the original demanded vector elements and the value.
4327 SDValue InVec = Op.getOperand(0);
4328 SDValue InVal = Op.getOperand(1);
4329 SDValue EltNo = Op.getOperand(2);
4330 bool DemandedVal = true;
4331 APInt DemandedVecElts = DemandedElts;
4332 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4333 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4334 unsigned EltIdx = CEltNo->getZExtValue();
4335 DemandedVal = !!DemandedElts[EltIdx];
4336 DemandedVecElts.clearBit(EltIdx);
4337 }
4338 Known.setAllConflict();
4339 if (DemandedVal) {
4340 Known2 = computeKnownBits(InVal, Depth + 1);
4341 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4342 }
4343 if (!!DemandedVecElts) {
4344 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4345 Known = Known.intersectWith(Known2);
4346 }
4347 break;
4348 }
4349 case ISD::BITREVERSE: {
4350 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4351 Known = Known2.reverseBits();
4352 break;
4353 }
4354 case ISD::BSWAP: {
4355 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4356 Known = Known2.byteSwap();
4357 break;
4358 }
4359 case ISD::ABS:
4360 case ISD::ABS_MIN_POISON: {
4361 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4362 Known = Known2.abs();
4363 Known.Zero.setHighBits(
4364 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4365 break;
4366 }
4367 case ISD::USUBSAT: {
4368 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4369 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4370 Known = KnownBits::usub_sat(Known, Known2);
4371 break;
4372 }
4373 case ISD::UMIN: {
4374 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4375 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4376 Known = KnownBits::umin(Known, Known2);
4377 break;
4378 }
4379 case ISD::UMAX: {
4380 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4381 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4382 Known = KnownBits::umax(Known, Known2);
4383 break;
4384 }
4385 case ISD::SMIN:
4386 case ISD::SMAX: {
4387 // If we have a clamp pattern, we know that the number of sign bits will be
4388 // the minimum of the clamp min/max range.
4389 bool IsMax = (Opcode == ISD::SMAX);
4390 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4391 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4392 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4393 CstHigh =
4394 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4395 if (CstLow && CstHigh) {
4396 if (!IsMax)
4397 std::swap(CstLow, CstHigh);
4398
4399 const APInt &ValueLow = CstLow->getAPIntValue();
4400 const APInt &ValueHigh = CstHigh->getAPIntValue();
4401 if (ValueLow.sle(ValueHigh)) {
4402 unsigned LowSignBits = ValueLow.getNumSignBits();
4403 unsigned HighSignBits = ValueHigh.getNumSignBits();
4404 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4405 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4406 Known.One.setHighBits(MinSignBits);
4407 break;
4408 }
4409 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4410 Known.Zero.setHighBits(MinSignBits);
4411 break;
4412 }
4413 }
4414 }
4415
4416 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4417 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4418 if (IsMax)
4419 Known = KnownBits::smax(Known, Known2);
4420 else
4421 Known = KnownBits::smin(Known, Known2);
4422
4423 // For SMAX, if CstLow is non-negative we know the result will be
4424 // non-negative and thus all sign bits are 0.
4425 // TODO: There's an equivalent of this for smin with negative constant for
4426 // known ones.
4427 if (IsMax && CstLow) {
4428 const APInt &ValueLow = CstLow->getAPIntValue();
4429 if (ValueLow.isNonNegative()) {
4430 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4431 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4432 }
4433 }
4434
4435 break;
4436 }
4437 case ISD::UINT_TO_FP: {
4438 Known.makeNonNegative();
4439 break;
4440 }
4441 case ISD::SINT_TO_FP: {
4442 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4443 if (Known2.isNonNegative())
4444 Known.makeNonNegative();
4445 else if (Known2.isNegative())
4446 Known.makeNegative();
4447 break;
4448 }
4449 case ISD::FP_TO_UINT_SAT: {
4450 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4451 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4453 break;
4454 }
4455 case ISD::ATOMIC_LOAD: {
4456 // If we are looking at the loaded value.
4457 if (Op.getResNo() == 0) {
4458 auto *AT = cast<AtomicSDNode>(Op);
4459 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4460 KnownBits KnownScalarMemory(ScalarMemorySize);
4461 if (const MDNode *MD = AT->getRanges())
4462 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4463
4464 switch (AT->getExtensionType()) {
4465 case ISD::ZEXTLOAD:
4466 Known = KnownScalarMemory.zext(BitWidth);
4467 break;
4468 case ISD::SEXTLOAD:
4469 Known = KnownScalarMemory.sext(BitWidth);
4470 break;
4471 case ISD::EXTLOAD:
4472 switch (TLI->getExtendForAtomicOps()) {
4473 case ISD::ZERO_EXTEND:
4474 Known = KnownScalarMemory.zext(BitWidth);
4475 break;
4476 case ISD::SIGN_EXTEND:
4477 Known = KnownScalarMemory.sext(BitWidth);
4478 break;
4479 default:
4480 Known = KnownScalarMemory.anyext(BitWidth);
4481 break;
4482 }
4483 break;
4484 case ISD::NON_EXTLOAD:
4485 Known = KnownScalarMemory;
4486 break;
4487 }
4488 assert(Known.getBitWidth() == BitWidth);
4489 }
4490 break;
4491 }
4493 if (Op.getResNo() == 1) {
4494 // The boolean result conforms to getBooleanContents.
4495 // If we know the result of a setcc has the top bits zero, use this info.
4496 // We know that we have an integer-based boolean since these operations
4497 // are only available for integer.
4498 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4500 BitWidth > 1)
4501 Known.Zero.setBitsFrom(1);
4502 break;
4503 }
4504 [[fallthrough]];
4506 case ISD::ATOMIC_SWAP:
4517 case ISD::ATOMIC_LOAD_UMAX: {
4518 // If we are looking at the loaded value.
4519 if (Op.getResNo() == 0) {
4520 auto *AT = cast<AtomicSDNode>(Op);
4521 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4522
4523 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4524 Known.Zero.setBitsFrom(MemBits);
4525 }
4526 break;
4527 }
4528 case ISD::FrameIndex:
4529 case ISD::TargetFrameIndex: {
4530 const MachineFunction &MF = getMachineFunction();
4531 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4532 TLI->computeKnownBitsForStackObjectPointer(
4533 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4534 break;
4535 }
4536
4537 default:
4538 if (Opcode < ISD::BUILTIN_OP_END)
4539 break;
4540 [[fallthrough]];
4544 // Allow the target to implement this method for its nodes.
4545 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4546 break;
4547 }
4548
4549 return Known;
4550}
4551
4552/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4565
4568 // X + 0 never overflow
4569 if (isNullConstant(N1))
4570 return OFK_Never;
4571
4572 // If both operands each have at least two sign bits, the addition
4573 // cannot overflow.
4574 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4575 return OFK_Never;
4576
4577 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4578 return OFK_Sometime;
4579}
4580
4583 // X + 0 never overflow
4584 if (isNullConstant(N1))
4585 return OFK_Never;
4586
4587 // mulhi + 1 never overflow
4588 KnownBits N1Known = computeKnownBits(N1);
4589 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4590 N1Known.getMaxValue().ult(2))
4591 return OFK_Never;
4592
4593 KnownBits N0Known = computeKnownBits(N0);
4594 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4595 N0Known.getMaxValue().ult(2))
4596 return OFK_Never;
4597
4598 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4599 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4600 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4601 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4602}
4603
4606 // X - 0 never overflow
4607 if (isNullConstant(N1))
4608 return OFK_Never;
4609
4610 // If both operands each have at least two sign bits, the subtraction
4611 // cannot overflow.
4612 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4613 return OFK_Never;
4614
4615 KnownBits N0Known = computeKnownBits(N0);
4616 KnownBits N1Known = computeKnownBits(N1);
4617 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4618 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4619 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4620}
4621
4624 // X - 0 never overflow
4625 if (isNullConstant(N1))
4626 return OFK_Never;
4627
4628 ConstantRange N0Range =
4629 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4630 ConstantRange N1Range =
4631 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4632 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4633}
4634
4637 // X * 0 and X * 1 never overflow.
4638 if (isNullConstant(N1) || isOneConstant(N1))
4639 return OFK_Never;
4640
4643 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4644}
4645
4648 // X * 0 and X * 1 never overflow.
4649 if (isNullConstant(N1) || isOneConstant(N1))
4650 return OFK_Never;
4651
4652 // Get the size of the result.
4653 unsigned BitWidth = N0.getScalarValueSizeInBits();
4654
4655 // Sum of the sign bits.
4656 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4657
4658 // If we have enough sign bits, then there's no overflow.
4659 if (SignBits > BitWidth + 1)
4660 return OFK_Never;
4661
4662 if (SignBits == BitWidth + 1) {
4663 // The overflow occurs when the true multiplication of the
4664 // the operands is the minimum negative number.
4665 KnownBits N0Known = computeKnownBits(N0);
4666 KnownBits N1Known = computeKnownBits(N1);
4667 // If one of the operands is non-negative, then there's no
4668 // overflow.
4669 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4670 return OFK_Never;
4671 }
4672
4673 return OFK_Sometime;
4674}
4675
4677 unsigned Depth) const {
4678 APInt DemandedElts = getDemandAllEltsMask(Op);
4679 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4680}
4681
4683 const APInt &DemandedElts,
4684 bool ForSigned,
4685 unsigned Depth) const {
4686 EVT VT = Op.getValueType();
4687 unsigned BitWidth = VT.getScalarSizeInBits();
4688
4689 if (Depth >= MaxRecursionDepth)
4690 return ConstantRange::getFull(BitWidth);
4691
4692 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4693 return ConstantRange(C->getAPIntValue());
4694
4695 unsigned Opcode = Op.getOpcode();
4696 switch (Opcode) {
4697 case ISD::VSCALE: {
4699 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4700 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4701 }
4702 default:
4703 break;
4704 }
4705
4706 return ConstantRange::getFull(BitWidth);
4707}
4708
4711 unsigned Depth) const {
4712 APInt DemandedElts = getDemandAllEltsMask(Op);
4713 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4714 Depth);
4715}
4716
4718 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4719 unsigned Depth) const {
4720 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4722 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4725 return CR1.intersectWith(CR2, RangeType);
4726}
4727
4729 unsigned Depth) const {
4730 APInt DemandedElts = getDemandAllEltsMask(Val);
4731 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4732}
4733
4735 const APInt &DemandedElts,
4736 bool OrZero, unsigned Depth) const {
4737 if (Depth >= MaxRecursionDepth)
4738 return false; // Limit search depth.
4739
4740 EVT OpVT = Val.getValueType();
4741 unsigned BitWidth = OpVT.getScalarSizeInBits();
4742 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4743 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4744 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4745 assert(
4746 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4747 "Unexpected vector size");
4748
4749 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4750 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4751 return (OrZero && V.isZero()) || V.isPowerOf2();
4752 };
4753
4754 // Is the constant a known power of 2 or zero?
4755 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4756 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4757 return true;
4758
4759 switch (Val.getOpcode()) {
4761 SDValue InVec = Val.getOperand(0);
4762 SDValue EltNo = Val.getOperand(1);
4763 EVT VecVT = InVec.getValueType();
4764
4765 // Skip scalable vectors or implicit extensions.
4766 if (VecVT.isScalableVector() ||
4767 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4768 break;
4769
4770 // If we know the element index, just demand that vector element, else for
4771 // an unknown element index, ignore DemandedElts and demand them all.
4772 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4773 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4774 APInt DemandedSrcElts =
4775 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4776 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4777 : APInt::getAllOnes(NumSrcElts);
4778 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4779 }
4780
4781 case ISD::AND: {
4782 // Looking for `x & -x` pattern:
4783 // If x == 0:
4784 // x & -x -> 0
4785 // If x != 0:
4786 // x & -x -> non-zero pow2
4787 // so if we find the pattern return whether we know `x` is non-zero.
4788 SDValue X, Z;
4789 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4790 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4791 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4792 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4793 break;
4794 }
4795
4796 case ISD::SHL: {
4797 // A left-shift of a constant one will have exactly one bit set because
4798 // shifting the bit off the end is undefined.
4799 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4800 if (C && C->getAPIntValue() == 1)
4801 return true;
4802 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4803 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4804 Depth + 1);
4805 }
4806
4807 case ISD::SRL: {
4808 // A logical right-shift of a constant sign-bit will have exactly
4809 // one bit set.
4810 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4811 if (C && C->getAPIntValue().isSignMask())
4812 return true;
4813 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4814 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4815 Depth + 1);
4816 }
4817
4818 case ISD::TRUNCATE:
4819 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4820 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4821 Depth + 1);
4822
4823 case ISD::ROTL:
4824 case ISD::ROTR:
4825 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4826 Depth + 1);
4827 case ISD::BSWAP:
4828 case ISD::BITREVERSE:
4829 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4830 Depth + 1);
4831
4832 case ISD::SMIN:
4833 case ISD::SMAX:
4834 case ISD::UMIN:
4835 case ISD::UMAX:
4836 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4837 Depth + 1) &&
4838 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4839 Depth + 1);
4840
4841 case ISD::SELECT:
4842 case ISD::VSELECT:
4843 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4844 Depth + 1) &&
4845 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4846 Depth + 1);
4847
4848 case ISD::ZERO_EXTEND:
4849 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4850 Depth + 1);
4851
4852 case ISD::VSCALE:
4853 // vscale(power-of-two) is a power-of-two
4854 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4855 Depth + 1);
4856
4857 case ISD::VECTOR_SHUFFLE: {
4859 // Demanded elements with undef shuffle mask elements are unknown
4860 // - we cannot guarantee they are a power of two, so return false.
4861 APInt DemandedLHS, DemandedRHS;
4863 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4864 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4865 DemandedLHS, DemandedRHS))
4866 return false;
4867
4868 // All demanded elements from LHS must be known power of two.
4869 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4870 OrZero, Depth + 1))
4871 return false;
4872
4873 // All demanded elements from RHS must be known power of two.
4874 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4875 OrZero, Depth + 1))
4876 return false;
4877
4878 return true;
4879 }
4880 }
4881
4882 // More could be done here, though the above checks are enough
4883 // to handle some common cases.
4884 return false;
4885}
4886
4888 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4889 return C1->getValueAPF().getExactLog2Abs() >= 0;
4890
4891 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4892 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4893
4894 return false;
4895}
4896
4898 APInt DemandedElts = getDemandAllEltsMask(Op);
4899 return ComputeNumSignBits(Op, DemandedElts, Depth);
4900}
4901
4902unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4903 unsigned Depth) const {
4904 EVT VT = Op.getValueType();
4905 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4906 unsigned VTBits = VT.getScalarSizeInBits();
4907 unsigned NumElts = DemandedElts.getBitWidth();
4908 unsigned Tmp, Tmp2;
4909 unsigned FirstAnswer = 1;
4910
4911 assert((!VT.isScalableVector() || NumElts == 1) &&
4912 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4913
4914 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4915 const APInt &Val = C->getAPIntValue();
4916 return Val.getNumSignBits();
4917 }
4918
4919 if (Depth >= MaxRecursionDepth)
4920 return 1; // Limit search depth.
4921
4922 if (!DemandedElts)
4923 return 1; // No demanded elts, better to assume we don't know anything.
4924
4925 unsigned Opcode = Op.getOpcode();
4926 switch (Opcode) {
4927 default: break;
4928 case ISD::AssertSext:
4929 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4930 return VTBits-Tmp+1;
4931 case ISD::AssertZext:
4932 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4933 return VTBits-Tmp;
4934 case ISD::FREEZE:
4935 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4937 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4938 break;
4939 case ISD::MERGE_VALUES:
4940 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4941 Depth + 1);
4942 case ISD::SPLAT_VECTOR: {
4943 // Check if the sign bits of source go down as far as the truncated value.
4944 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4945 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4946 if (NumSrcSignBits > (NumSrcBits - VTBits))
4947 return NumSrcSignBits - (NumSrcBits - VTBits);
4948 break;
4949 }
4950 case ISD::BUILD_VECTOR:
4951 assert(!VT.isScalableVector());
4952 Tmp = VTBits;
4953 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4954 if (!DemandedElts[i])
4955 continue;
4956
4957 SDValue SrcOp = Op.getOperand(i);
4958 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4959 // for constant nodes to ensure we only look at the sign bits.
4961 APInt T = C->getAPIntValue().trunc(VTBits);
4962 Tmp2 = T.getNumSignBits();
4963 } else {
4964 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4965
4966 if (SrcOp.getValueSizeInBits() != VTBits) {
4967 assert(SrcOp.getValueSizeInBits() > VTBits &&
4968 "Expected BUILD_VECTOR implicit truncation");
4969 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4970 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4971 }
4972 }
4973 Tmp = std::min(Tmp, Tmp2);
4974 }
4975 return Tmp;
4976
4977 case ISD::VECTOR_COMPRESS: {
4978 SDValue Vec = Op.getOperand(0);
4979 SDValue PassThru = Op.getOperand(2);
4980 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
4981 if (Tmp == 1)
4982 return 1;
4983 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
4984 Tmp = std::min(Tmp, Tmp2);
4985 return Tmp;
4986 }
4987
4988 case ISD::VECTOR_SHUFFLE: {
4989 // Collect the minimum number of sign bits that are shared by every vector
4990 // element referenced by the shuffle.
4991 APInt DemandedLHS, DemandedRHS;
4993 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4994 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4995 DemandedLHS, DemandedRHS))
4996 return 1;
4997
4998 Tmp = std::numeric_limits<unsigned>::max();
4999 if (!!DemandedLHS)
5000 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5001 if (!!DemandedRHS) {
5002 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5003 Tmp = std::min(Tmp, Tmp2);
5004 }
5005 // If we don't know anything, early out and try computeKnownBits fall-back.
5006 if (Tmp == 1)
5007 break;
5008 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5009 return Tmp;
5010 }
5011
5012 case ISD::BITCAST: {
5013 if (VT.isScalableVector())
5014 break;
5015 SDValue N0 = Op.getOperand(0);
5016 EVT SrcVT = N0.getValueType();
5017 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5018
5019 // Ignore bitcasts from unsupported types..
5020 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5021 break;
5022
5023 // Fast handling of 'identity' bitcasts.
5024 if (VTBits == SrcBits)
5025 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5026
5027 bool IsLE = getDataLayout().isLittleEndian();
5028
5029 // Bitcast 'large element' scalar/vector to 'small element' vector.
5030 if ((SrcBits % VTBits) == 0) {
5031 assert(VT.isVector() && "Expected bitcast to vector");
5032
5033 unsigned Scale = SrcBits / VTBits;
5034 APInt SrcDemandedElts =
5035 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5036
5037 // Fast case - sign splat can be simply split across the small elements.
5038 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5039 if (Tmp == SrcBits)
5040 return VTBits;
5041
5042 // Slow case - determine how far the sign extends into each sub-element.
5043 Tmp2 = VTBits;
5044 for (unsigned i = 0; i != NumElts; ++i)
5045 if (DemandedElts[i]) {
5046 unsigned SubOffset = i % Scale;
5047 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5048 SubOffset = SubOffset * VTBits;
5049 if (Tmp <= SubOffset)
5050 return 1;
5051 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5052 }
5053 return Tmp2;
5054 }
5055 break;
5056 }
5057
5059 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5060 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5061 return VTBits - Tmp + 1;
5062 case ISD::SIGN_EXTEND:
5063 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5064 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5066 // Max of the input and what this extends.
5067 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5068 Tmp = VTBits-Tmp+1;
5069 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5070 return std::max(Tmp, Tmp2);
5072 if (VT.isScalableVector())
5073 break;
5074 SDValue Src = Op.getOperand(0);
5075 EVT SrcVT = Src.getValueType();
5076 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5077 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5078 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5079 }
5080 case ISD::SRA:
5081 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5082 // SRA X, C -> adds C sign bits.
5083 if (std::optional<unsigned> ShAmt =
5084 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5085 Tmp = std::min(Tmp + *ShAmt, VTBits);
5086 return Tmp;
5087 case ISD::SHL:
5088 if (std::optional<ConstantRange> ShAmtRange =
5089 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5090 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5091 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5092 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5093 // shifted out, then we can compute the number of sign bits for the
5094 // operand being extended. A future improvement could be to pass along the
5095 // "shifted left by" information in the recursive calls to
5096 // ComputeKnownSignBits. Allowing us to handle this more generically.
5097 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5098 SDValue Ext = Op.getOperand(0);
5099 EVT ExtVT = Ext.getValueType();
5100 SDValue Extendee = Ext.getOperand(0);
5101 EVT ExtendeeVT = Extendee.getValueType();
5102 unsigned SizeDifference =
5103 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5104 if (SizeDifference <= MinShAmt) {
5105 Tmp = SizeDifference +
5106 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5107 if (MaxShAmt < Tmp)
5108 return Tmp - MaxShAmt;
5109 }
5110 }
5111 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5112 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5113 if (MaxShAmt < Tmp)
5114 return Tmp - MaxShAmt;
5115 }
5116 break;
5117 case ISD::AND:
5118 case ISD::OR:
5119 case ISD::XOR: // NOT is handled here.
5120 // Logical binary ops preserve the number of sign bits at the worst.
5121 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5122 if (Tmp != 1) {
5123 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5124 FirstAnswer = std::min(Tmp, Tmp2);
5125 // We computed what we know about the sign bits as our first
5126 // answer. Now proceed to the generic code that uses
5127 // computeKnownBits, and pick whichever answer is better.
5128 }
5129 break;
5130
5131 case ISD::SELECT:
5132 case ISD::VSELECT:
5133 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5134 if (Tmp == 1) return 1; // Early out.
5135 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5136 return std::min(Tmp, Tmp2);
5137 case ISD::SELECT_CC:
5138 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5139 if (Tmp == 1) return 1; // Early out.
5140 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5141 return std::min(Tmp, Tmp2);
5142
5143 case ISD::SMIN:
5144 case ISD::SMAX: {
5145 // If we have a clamp pattern, we know that the number of sign bits will be
5146 // the minimum of the clamp min/max range.
5147 bool IsMax = (Opcode == ISD::SMAX);
5148 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5149 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5150 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5151 CstHigh =
5152 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5153 if (CstLow && CstHigh) {
5154 if (!IsMax)
5155 std::swap(CstLow, CstHigh);
5156 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5157 Tmp = CstLow->getAPIntValue().getNumSignBits();
5158 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5159 return std::min(Tmp, Tmp2);
5160 }
5161 }
5162
5163 // Fallback - just get the minimum number of sign bits of the operands.
5164 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5165 if (Tmp == 1)
5166 return 1; // Early out.
5167 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5168 return std::min(Tmp, Tmp2);
5169 }
5170 case ISD::UMIN:
5171 case ISD::UMAX:
5172 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5173 if (Tmp == 1)
5174 return 1; // Early out.
5175 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5176 return std::min(Tmp, Tmp2);
5177 case ISD::SSUBO_CARRY:
5178 case ISD::USUBO_CARRY:
5179 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5180 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5181 return VTBits;
5182 [[fallthrough]];
5183 case ISD::SADDO:
5184 case ISD::UADDO:
5185 case ISD::SADDO_CARRY:
5186 case ISD::UADDO_CARRY:
5187 case ISD::SSUBO:
5188 case ISD::USUBO:
5189 case ISD::SMULO:
5190 case ISD::UMULO:
5191 if (Op.getResNo() != 1)
5192 break;
5193 // The boolean result conforms to getBooleanContents. Fall through.
5194 // If setcc returns 0/-1, all bits are sign bits.
5195 // We know that we have an integer-based boolean since these operations
5196 // are only available for integer.
5197 if (TLI->getBooleanContents(VT.isVector(), false) ==
5199 return VTBits;
5200 break;
5201 case ISD::SETCC:
5202 case ISD::SETCCCARRY:
5203 case ISD::STRICT_FSETCC:
5204 case ISD::STRICT_FSETCCS: {
5205 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5206 // If setcc returns 0/-1, all bits are sign bits.
5207 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5209 return VTBits;
5210 break;
5211 }
5213 // Semantically similar to icmp ult.
5214 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5216 return VTBits;
5217 break;
5218 case ISD::ROTL:
5219 case ISD::ROTR: {
5220 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5221 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5222 FirstAnswer = SignBitsOps::rot(
5223 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5224 Opcode == ISD::ROTR);
5225 break;
5226 }
5227 case ISD::ADD:
5228 case ISD::ADDC:
5229 // TODO: Move Operand 1 check before Operand 0 check
5230 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5231 if (Tmp == 1) return 1; // Early out.
5232
5233 // Special case decrementing a value (ADD X, -1):
5234 if (ConstantSDNode *CRHS =
5235 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5236 if (CRHS->isAllOnes()) {
5238 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5239
5240 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5241 // sign bits set.
5242 if ((Known.Zero | 1).isAllOnes())
5243 return VTBits;
5244
5245 // If we are subtracting one from a positive number, there is no carry
5246 // out of the result.
5247 if (Known.isNonNegative())
5248 return Tmp;
5249 }
5250
5251 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5252 if (Tmp2 == 1) return 1; // Early out.
5253
5254 // Add can have at most one carry bit. Thus we know that the output
5255 // is, at worst, one more bit than the inputs.
5256 return std::min(Tmp, Tmp2) - 1;
5257 case ISD::SUB:
5258 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5259 if (Tmp2 == 1) return 1; // Early out.
5260
5261 // Handle NEG.
5262 if (ConstantSDNode *CLHS =
5263 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5264 if (CLHS->isZero()) {
5266 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5267 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5268 // sign bits set.
5269 if ((Known.Zero | 1).isAllOnes())
5270 return VTBits;
5271
5272 // If the input is known to be positive (the sign bit is known clear),
5273 // the output of the NEG has the same number of sign bits as the input.
5274 if (Known.isNonNegative())
5275 return Tmp2;
5276
5277 // Otherwise, we treat this like a SUB.
5278 }
5279
5280 // Sub can have at most one carry bit. Thus we know that the output
5281 // is, at worst, one more bit than the inputs.
5282 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5283 if (Tmp == 1) return 1; // Early out.
5284 return std::min(Tmp, Tmp2) - 1;
5285 case ISD::MUL: {
5286 // The output of the Mul can be at most twice the valid bits in the inputs.
5287 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5288 if (SignBitsOp0 == 1)
5289 break;
5290 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5291 if (SignBitsOp1 == 1)
5292 break;
5293 unsigned OutValidBits =
5294 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5295 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5296 }
5297 case ISD::AVGCEILS:
5298 case ISD::AVGFLOORS:
5299 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5300 if (Tmp == 1)
5301 return 1; // Early out.
5302 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5303 return std::min(Tmp, Tmp2);
5304 case ISD::SREM:
5305 // The sign bit is the LHS's sign bit, except when the result of the
5306 // remainder is zero. The magnitude of the result should be less than or
5307 // equal to the magnitude of the LHS. Therefore, the result should have
5308 // at least as many sign bits as the left hand side.
5309 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5310 case ISD::TRUNCATE: {
5311 // Check if the sign bits of source go down as far as the truncated value.
5312 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5313 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5314 if (NumSrcSignBits > (NumSrcBits - VTBits))
5315 return NumSrcSignBits - (NumSrcBits - VTBits);
5316 break;
5317 }
5318 case ISD::EXTRACT_ELEMENT: {
5319 if (VT.isScalableVector())
5320 break;
5321 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5322 const int BitWidth = Op.getValueSizeInBits();
5323 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5324
5325 // Get reverse index (starting from 1), Op1 value indexes elements from
5326 // little end. Sign starts at big end.
5327 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5328
5329 // If the sign portion ends in our element the subtraction gives correct
5330 // result. Otherwise it gives either negative or > bitwidth result
5331 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5332 }
5334 if (VT.isScalableVector())
5335 break;
5336 // If we know the element index, split the demand between the
5337 // source vector and the inserted element, otherwise assume we need
5338 // the original demanded vector elements and the value.
5339 SDValue InVec = Op.getOperand(0);
5340 SDValue InVal = Op.getOperand(1);
5341 SDValue EltNo = Op.getOperand(2);
5342 bool DemandedVal = true;
5343 APInt DemandedVecElts = DemandedElts;
5344 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5345 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5346 unsigned EltIdx = CEltNo->getZExtValue();
5347 DemandedVal = !!DemandedElts[EltIdx];
5348 DemandedVecElts.clearBit(EltIdx);
5349 }
5350 Tmp = std::numeric_limits<unsigned>::max();
5351 if (DemandedVal) {
5352 // TODO - handle implicit truncation of inserted elements.
5353 if (InVal.getScalarValueSizeInBits() != VTBits)
5354 break;
5355 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5356 Tmp = std::min(Tmp, Tmp2);
5357 }
5358 if (!!DemandedVecElts) {
5359 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5360 Tmp = std::min(Tmp, Tmp2);
5361 }
5362 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5363 return Tmp;
5364 }
5366 SDValue InVec = Op.getOperand(0);
5367 SDValue EltNo = Op.getOperand(1);
5368 EVT VecVT = InVec.getValueType();
5369 // ComputeNumSignBits not yet implemented for scalable vectors.
5370 if (VecVT.isScalableVector())
5371 break;
5372 const unsigned BitWidth = Op.getValueSizeInBits();
5373 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5374 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5375
5376 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5377 // anything about sign bits. But if the sizes match we can derive knowledge
5378 // about sign bits from the vector operand.
5379 if (BitWidth != EltBitWidth)
5380 break;
5381
5382 // If we know the element index, just demand that vector element, else for
5383 // an unknown element index, ignore DemandedElts and demand them all.
5384 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5385 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5386 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5387 DemandedSrcElts =
5388 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5389
5390 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5391 }
5393 // Offset the demanded elts by the subvector index.
5394 SDValue Src = Op.getOperand(0);
5395
5396 APInt DemandedSrcElts;
5397 if (Src.getValueType().isScalableVector())
5398 DemandedSrcElts = APInt(1, 1);
5399 else {
5400 uint64_t Idx = Op.getConstantOperandVal(1);
5401 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5402 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5403 }
5404 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5405 }
5406 case ISD::CONCAT_VECTORS: {
5407 if (VT.isScalableVector())
5408 break;
5409 // Determine the minimum number of sign bits across all demanded
5410 // elts of the input vectors. Early out if the result is already 1.
5411 Tmp = std::numeric_limits<unsigned>::max();
5412 EVT SubVectorVT = Op.getOperand(0).getValueType();
5413 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5414 unsigned NumSubVectors = Op.getNumOperands();
5415 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5416 APInt DemandedSub =
5417 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5418 if (!DemandedSub)
5419 continue;
5420 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5421 Tmp = std::min(Tmp, Tmp2);
5422 }
5423 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5424 return Tmp;
5425 }
5426 case ISD::INSERT_SUBVECTOR: {
5427 if (VT.isScalableVector())
5428 break;
5429 // Demand any elements from the subvector and the remainder from the src its
5430 // inserted into.
5431 SDValue Src = Op.getOperand(0);
5432 SDValue Sub = Op.getOperand(1);
5433 uint64_t Idx = Op.getConstantOperandVal(2);
5434 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5435 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5436 APInt DemandedSrcElts = DemandedElts;
5437 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5438
5439 Tmp = std::numeric_limits<unsigned>::max();
5440 if (!!DemandedSubElts) {
5441 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5442 if (Tmp == 1)
5443 return 1; // early-out
5444 }
5445 if (!!DemandedSrcElts) {
5446 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5447 Tmp = std::min(Tmp, Tmp2);
5448 }
5449 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5450 return Tmp;
5451 }
5452 case ISD::LOAD: {
5453 // If we are looking at the loaded value of the SDNode.
5454 if (Op.getResNo() != 0)
5455 break;
5456
5458 if (const MDNode *Ranges = LD->getRanges()) {
5459 if (DemandedElts != 1)
5460 break;
5461
5463 if (VTBits > CR.getBitWidth()) {
5464 switch (LD->getExtensionType()) {
5465 case ISD::SEXTLOAD:
5466 CR = CR.signExtend(VTBits);
5467 break;
5468 case ISD::ZEXTLOAD:
5469 CR = CR.zeroExtend(VTBits);
5470 break;
5471 default:
5472 break;
5473 }
5474 }
5475
5476 if (VTBits != CR.getBitWidth())
5477 break;
5478 return std::min(CR.getSignedMin().getNumSignBits(),
5480 }
5481
5482 unsigned ExtType = LD->getExtensionType();
5483 switch (ExtType) {
5484 default:
5485 break;
5486 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5487 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5488 return VTBits - Tmp + 1;
5489 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5490 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5491 return VTBits - Tmp;
5492 case ISD::NON_EXTLOAD:
5493 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5494 // We only need to handle vectors - computeKnownBits should handle
5495 // scalar cases.
5496 Type *CstTy = Cst->getType();
5497 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5498 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5499 VTBits == CstTy->getScalarSizeInBits()) {
5500 Tmp = VTBits;
5501 for (unsigned i = 0; i != NumElts; ++i) {
5502 if (!DemandedElts[i])
5503 continue;
5504 if (Constant *Elt = Cst->getAggregateElement(i)) {
5505 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5506 const APInt &Value = CInt->getValue();
5507 Tmp = std::min(Tmp, Value.getNumSignBits());
5508 continue;
5509 }
5510 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5511 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5512 Tmp = std::min(Tmp, Value.getNumSignBits());
5513 continue;
5514 }
5515 }
5516 // Unknown type. Conservatively assume no bits match sign bit.
5517 return 1;
5518 }
5519 return Tmp;
5520 }
5521 }
5522 break;
5523 }
5524
5525 break;
5526 }
5529 case ISD::ATOMIC_SWAP:
5541 case ISD::ATOMIC_LOAD: {
5542 auto *AT = cast<AtomicSDNode>(Op);
5543 // If we are looking at the loaded value.
5544 if (Op.getResNo() == 0) {
5545 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5546 if (Tmp == VTBits)
5547 return 1; // early-out
5548
5549 // For atomic_load, prefer to use the extension type.
5550 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5551 switch (AT->getExtensionType()) {
5552 default:
5553 break;
5554 case ISD::SEXTLOAD:
5555 return VTBits - Tmp + 1;
5556 case ISD::ZEXTLOAD:
5557 return VTBits - Tmp;
5558 }
5559 }
5560
5561 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5562 return VTBits - Tmp + 1;
5563 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5564 return VTBits - Tmp;
5565 }
5566 break;
5567 }
5568 }
5569
5570 // Allow the target to implement this method for its nodes.
5571 if (Opcode >= ISD::BUILTIN_OP_END ||
5572 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5573 Opcode == ISD::INTRINSIC_W_CHAIN ||
5574 Opcode == ISD::INTRINSIC_VOID) {
5575 // TODO: This can probably be removed once target code is audited. This
5576 // is here purely to reduce patch size and review complexity.
5577 if (!VT.isScalableVector()) {
5578 unsigned NumBits =
5579 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5580 if (NumBits > 1)
5581 FirstAnswer = std::max(FirstAnswer, NumBits);
5582 }
5583 }
5584
5585 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5586 // use this information.
5587 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5588 return std::max(FirstAnswer, Known.countMinSignBits());
5589}
5590
5592 unsigned Depth) const {
5593 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5594 return Op.getScalarValueSizeInBits() - SignBits + 1;
5595}
5596
5598 const APInt &DemandedElts,
5599 unsigned Depth) const {
5600 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5601 return Op.getScalarValueSizeInBits() - SignBits + 1;
5602}
5603
5605 UndefPoisonKind Kind,
5606 unsigned Depth) const {
5607 // Early out for FREEZE.
5608 if (Op.getOpcode() == ISD::FREEZE)
5609 return true;
5610
5611 APInt DemandedElts = getDemandAllEltsMask(Op);
5612 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5613}
5614
5616 const APInt &DemandedElts,
5617 UndefPoisonKind Kind,
5618 unsigned Depth) const {
5619 unsigned Opcode = Op.getOpcode();
5620
5621 // Early out for FREEZE.
5622 if (Opcode == ISD::FREEZE)
5623 return true;
5624
5625 if (Depth >= MaxRecursionDepth)
5626 return false; // Limit search depth.
5627
5628 if (isIntOrFPConstant(Op))
5629 return true;
5630
5631 switch (Opcode) {
5632 case ISD::CONDCODE:
5633 case ISD::VALUETYPE:
5634 case ISD::FrameIndex:
5636 case ISD::CopyFromReg:
5637 return true;
5638
5639 case ISD::POISON:
5640 return !includesPoison(Kind);
5641
5642 case ISD::UNDEF:
5643 return !includesUndef(Kind);
5644
5645 case ISD::BITCAST: {
5646 SDValue Src = Op.getOperand(0);
5647 EVT SrcVT = Src.getValueType();
5648 EVT DstVT = Op.getValueType();
5649
5650 if (!SrcVT.isVector() || !DstVT.isVector())
5651 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5652
5653 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5654 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5655 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5656 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5657
5658 if (SrcEltBits == DstEltBits)
5659 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5660 Depth + 1);
5661
5662 if (SrcEltBits < DstEltBits) {
5663 if (DstEltBits % SrcEltBits != 0)
5664 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5665
5666 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5667 "Unexpected vector bitcast");
5668 APInt DemandedSrcElts =
5669 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5670 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5671 Depth + 1);
5672 }
5673
5674 if (SrcEltBits % DstEltBits != 0)
5675 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5676
5677 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5678 "Unexpected vector bitcast");
5679 APInt DemandedSrcElts =
5680 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5681 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5682 Depth + 1);
5683 }
5684
5685 case ISD::BUILD_VECTOR:
5686 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5687 // this shouldn't affect the result.
5688 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5689 if (!DemandedElts[i])
5690 continue;
5691 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5692 return false;
5693 }
5694 return true;
5695
5696 case ISD::CONCAT_VECTORS: {
5697 EVT VT = Op.getValueType();
5698 if (!VT.isFixedLengthVector())
5699 break;
5700
5701 EVT SubVT = Op.getOperand(0).getValueType();
5702 unsigned NumSubElts = SubVT.getVectorNumElements();
5703 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5704 APInt DemandedSubElts =
5705 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5706 if (!!DemandedSubElts &&
5707 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5708 Kind, Depth + 1))
5709 return false;
5710 }
5711 return true;
5712 }
5713
5715 SDValue Src = Op.getOperand(0);
5716 if (Src.getValueType().isScalableVector())
5717 break;
5718 uint64_t Idx = Op.getConstantOperandVal(1);
5719 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5720 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5721 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5722 Depth + 1);
5723 }
5724
5725 case ISD::INSERT_SUBVECTOR: {
5726 if (Op.getValueType().isScalableVector())
5727 break;
5728 SDValue Src = Op.getOperand(0);
5729 SDValue Sub = Op.getOperand(1);
5730 uint64_t Idx = Op.getConstantOperandVal(2);
5731 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5732 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5733 APInt DemandedSrcElts = DemandedElts;
5734 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5735
5736 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5737 Sub, DemandedSubElts, Kind, Depth + 1))
5738 return false;
5739 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5740 Src, DemandedSrcElts, Kind, Depth + 1))
5741 return false;
5742 return true;
5743 }
5744
5746 SDValue Src = Op.getOperand(0);
5747 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5748 EVT SrcVT = Src.getValueType();
5749 if (SrcVT.isFixedLengthVector() && IndexC &&
5750 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5751 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5752 IndexC->getZExtValue());
5753 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5754 Depth + 1);
5755 }
5756 break;
5757 }
5758
5760 SDValue InVec = Op.getOperand(0);
5761 SDValue InVal = Op.getOperand(1);
5762 SDValue EltNo = Op.getOperand(2);
5763 EVT VT = InVec.getValueType();
5764 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5765 if (IndexC && VT.isFixedLengthVector() &&
5766 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5767 if (DemandedElts[IndexC->getZExtValue()] &&
5768 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5769 return false;
5770 APInt InVecDemandedElts = DemandedElts;
5771 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5772 if (!!InVecDemandedElts &&
5774 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5775 InVecDemandedElts, Kind, Depth + 1))
5776 return false;
5777 return true;
5778 }
5779 break;
5780 }
5781
5783 // Check upper (known undef) elements.
5784 if (DemandedElts.ugt(1) && includesUndef(Kind))
5785 return false;
5786 // Check element zero.
5787 if (DemandedElts[0] &&
5788 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5789 return false;
5790 return true;
5791
5792 case ISD::SPLAT_VECTOR:
5793 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5794
5795 case ISD::SELECT: {
5796 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5797 /*ConsiderFlags*/ true, Depth) &&
5798 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5799 Depth + 1) &&
5800 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5801 Kind, Depth + 1) &&
5802 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5803 Kind, Depth + 1);
5804 }
5805
5806 case ISD::VECTOR_SHUFFLE: {
5807 APInt DemandedLHS, DemandedRHS;
5808 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5809 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5810 DemandedElts, DemandedLHS, DemandedRHS,
5811 /*AllowUndefElts=*/false))
5812 return false;
5813 if (!DemandedLHS.isZero() &&
5814 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5815 Depth + 1))
5816 return false;
5817 if (!DemandedRHS.isZero() &&
5818 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5819 Depth + 1))
5820 return false;
5821 return true;
5822 }
5823
5824 case ISD::SHL:
5825 case ISD::SRL:
5826 case ISD::SRA:
5827 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5828 // enough to check operand 0 if Op can't create undef/poison.
5829 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5830 /*ConsiderFlags*/ true, Depth) &&
5831 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5832 Kind, Depth + 1);
5833
5834 case ISD::BSWAP:
5835 case ISD::CTPOP:
5836 case ISD::BITREVERSE:
5837 case ISD::AND:
5838 case ISD::OR:
5839 case ISD::XOR:
5840 case ISD::ADD:
5841 case ISD::SUB:
5842 case ISD::MUL:
5843 case ISD::SADDSAT:
5844 case ISD::UADDSAT:
5845 case ISD::SSUBSAT:
5846 case ISD::USUBSAT:
5847 case ISD::SSHLSAT:
5848 case ISD::USHLSAT:
5849 case ISD::SMIN:
5850 case ISD::SMAX:
5851 case ISD::UMIN:
5852 case ISD::UMAX:
5853 case ISD::ZERO_EXTEND:
5854 case ISD::SIGN_EXTEND:
5855 case ISD::ANY_EXTEND:
5856 case ISD::TRUNCATE:
5857 case ISD::VSELECT: {
5858 // If Op can't create undef/poison and none of its operands are undef/poison
5859 // then Op is never undef/poison. A difference from the more common check
5860 // below, outside the switch, is that we handle elementwise operations for
5861 // which the DemandedElts mask is valid for all operands here.
5862 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5863 /*ConsiderFlags*/ true, Depth) &&
5864 all_of(Op->ops(), [&](SDValue V) {
5865 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5866 Depth + 1);
5867 });
5868 }
5869
5870 // TODO: Search for noundef attributes from library functions.
5871
5872 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5873
5874 default:
5875 // Allow the target to implement this method for its nodes.
5876 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5877 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5878 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5879 Op, DemandedElts, *this, Kind, Depth);
5880 break;
5881 }
5882
5883 // If Op can't create undef/poison and none of its operands are undef/poison
5884 // then Op is never undef/poison.
5885 // NOTE: TargetNodes can handle this in themselves in
5886 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5887 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5888 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5889 all_of(Op->ops(), [&](SDValue V) {
5890 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5891 });
5892}
5893
5895 bool ConsiderFlags,
5896 unsigned Depth) const {
5897 APInt DemandedElts = getDemandAllEltsMask(Op);
5898 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5899}
5900
5902 UndefPoisonKind Kind,
5903 bool ConsiderFlags,
5904 unsigned Depth) const {
5905 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5906 return true;
5907
5908 unsigned Opcode = Op.getOpcode();
5909 switch (Opcode) {
5910 case ISD::AssertSext:
5911 case ISD::AssertZext:
5912 case ISD::AssertAlign:
5914 // Assertion nodes can create poison if the assertion fails.
5915 return includesPoison(Kind);
5916
5917 case ISD::FREEZE:
5921 case ISD::SADDSAT:
5922 case ISD::UADDSAT:
5923 case ISD::SSUBSAT:
5924 case ISD::USUBSAT:
5925 case ISD::MULHU:
5926 case ISD::MULHS:
5927 case ISD::AVGFLOORS:
5928 case ISD::AVGFLOORU:
5929 case ISD::AVGCEILS:
5930 case ISD::AVGCEILU:
5931 case ISD::ABDU:
5932 case ISD::ABDS:
5933 case ISD::SMIN:
5934 case ISD::SMAX:
5935 case ISD::SCMP:
5936 case ISD::UMIN:
5937 case ISD::UMAX:
5938 case ISD::UCMP:
5939 case ISD::AND:
5940 case ISD::XOR:
5941 case ISD::ROTL:
5942 case ISD::ROTR:
5943 case ISD::FSHL:
5944 case ISD::FSHR:
5945 case ISD::BSWAP:
5946 case ISD::CTTZ:
5947 case ISD::CTLZ:
5948 case ISD::CTLS:
5949 case ISD::CTPOP:
5950 case ISD::BITREVERSE:
5951 case ISD::PARITY:
5952 case ISD::SIGN_EXTEND:
5953 case ISD::TRUNCATE:
5957 case ISD::BITCAST:
5958 case ISD::BUILD_VECTOR:
5959 case ISD::BUILD_PAIR:
5960 case ISD::SPLAT_VECTOR:
5961 case ISD::FABS:
5962 case ISD::FCEIL:
5963 case ISD::FFLOOR:
5964 case ISD::FTRUNC:
5965 case ISD::FRINT:
5966 case ISD::FNEARBYINT:
5967 case ISD::FROUND:
5968 case ISD::FROUNDEVEN:
5969 return false;
5970
5971 case ISD::ABS:
5972 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
5973 // Different to Intrinsic::abs.
5974 return false;
5976 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
5977 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
5978
5979 case ISD::ADDC:
5980 case ISD::SUBC:
5981 case ISD::ADDE:
5982 case ISD::SUBE:
5983 case ISD::SADDO:
5984 case ISD::SSUBO:
5985 case ISD::SMULO:
5986 case ISD::SADDO_CARRY:
5987 case ISD::SSUBO_CARRY:
5988 case ISD::UADDO:
5989 case ISD::USUBO:
5990 case ISD::UMULO:
5991 case ISD::UADDO_CARRY:
5992 case ISD::USUBO_CARRY:
5993 // No poison on result or overflow flags.
5994 return false;
5995
5996 case ISD::SELECT_CC:
5997 case ISD::SETCC: {
5998 // Integer setcc cannot create undef or poison.
5999 if (Op.getOperand(0).getValueType().isInteger())
6000 return false;
6001
6002 // FP compares are more complicated. They can create poison for nan/infinity
6003 // based on options and flags. The options and flags also cause special
6004 // nonan condition codes to be used. Those condition codes may be preserved
6005 // even if the nonan flag is dropped somewhere.
6006 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6007 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6008 return (unsigned)CCCode & 0x10U;
6009 }
6010
6011 case ISD::OR:
6012 case ISD::ZERO_EXTEND:
6013 case ISD::SELECT:
6014 case ISD::VSELECT:
6015 case ISD::ADD:
6016 case ISD::SUB:
6017 case ISD::MUL:
6018 case ISD::FNEG:
6019 case ISD::FADD:
6020 case ISD::FSUB:
6021 case ISD::FMUL:
6022 case ISD::FDIV:
6023 case ISD::FREM:
6024 case ISD::FCOPYSIGN:
6025 case ISD::FMA:
6026 case ISD::FMAD:
6027 case ISD::FMULADD:
6028 case ISD::FP_EXTEND:
6029 case ISD::FMINNUM:
6030 case ISD::FMAXNUM:
6031 case ISD::FMINNUM_IEEE:
6032 case ISD::FMAXNUM_IEEE:
6033 case ISD::FMINIMUM:
6034 case ISD::FMAXIMUM:
6035 case ISD::FMINIMUMNUM:
6036 case ISD::FMAXIMUMNUM:
6042 // No poison except from flags (which is handled above)
6043 return false;
6044
6045 case ISD::SHL:
6046 case ISD::SRL:
6047 case ISD::SRA:
6048 // If the max shift amount isn't in range, then the shift can
6049 // create poison.
6050 return includesPoison(Kind) &&
6051 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6052
6055 // If the amount is zero then the result will be poison.
6056 // TODO: Add isKnownNeverZero DemandedElts handling.
6057 return includesPoison(Kind) &&
6058 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6059
6061 // Check if we demand any upper (undef) elements.
6062 return includesUndef(Kind) && DemandedElts.ugt(1);
6063
6066 // Ensure that the element index is in bounds.
6067 if (includesPoison(Kind)) {
6068 EVT VecVT = Op.getOperand(0).getValueType();
6069 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6070 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6071 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6072 }
6073 return false;
6074 }
6075
6076 case ISD::VECTOR_SHUFFLE: {
6077 // Check for any demanded shuffle element that is undef.
6078 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6079 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6080 if (Elt < 0 && DemandedElts[Idx])
6081 return true;
6082 return false;
6083 }
6084
6086 return false;
6087
6088 default:
6089 // Allow the target to implement this method for its nodes.
6090 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6091 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6092 return TLI->canCreateUndefOrPoisonForTargetNode(
6093 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6094 break;
6095 }
6096
6097 // Be conservative and return true.
6098 return true;
6099}
6100
6101bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6102 unsigned Opcode = Op.getOpcode();
6103 if (Opcode == ISD::OR)
6104 return Op->getFlags().hasDisjoint() ||
6105 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6106 if (Opcode == ISD::XOR)
6107 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6108 return false;
6109}
6110
6112 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6113 (Op.isAnyAdd() || isADDLike(Op));
6114}
6115
6117 FPClassTest InterestedClasses,
6118 unsigned Depth) const {
6119 APInt DemandedElts = getDemandAllEltsMask(Op);
6120 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6121}
6122
6124 const APInt &DemandedElts,
6125 FPClassTest InterestedClasses,
6126 unsigned Depth) const {
6128
6129 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6130 return KnownFPClass(CFP->getValueAPF());
6131
6132 if (Depth >= MaxRecursionDepth)
6133 return Known;
6134
6135 if (Op.getOpcode() == ISD::UNDEF)
6136 return Known;
6137
6138 EVT VT = Op.getValueType();
6139 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6140 assert((!VT.isFixedLengthVector() ||
6141 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6142 "Unexpected vector size");
6143
6144 if (!DemandedElts)
6145 return Known;
6146
6147 unsigned Opcode = Op.getOpcode();
6148 switch (Opcode) {
6149 case ISD::POISON: {
6150 Known.KnownFPClasses = fcNone;
6151 Known.SignBit = false;
6152 break;
6153 }
6154 case ISD::FNEG: {
6155 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6156 InterestedClasses, Depth + 1);
6157 Known.fneg();
6158 break;
6159 }
6160 case ISD::BUILD_VECTOR: {
6161 assert(!VT.isScalableVector());
6162 bool First = true;
6163 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6164 if (!DemandedElts[I])
6165 continue;
6166
6167 if (First) {
6168 Known =
6169 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6170 First = false;
6171 } else {
6172 Known |=
6173 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6174 }
6175
6176 if (Known.isUnknown())
6177 break;
6178 }
6179 break;
6180 }
6182 SDValue Src = Op.getOperand(0);
6183 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6184 EVT SrcVT = Src.getValueType();
6185 if (SrcVT.isFixedLengthVector() && CIdx) {
6186 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6187 APInt DemandedSrcElts = APInt::getOneBitSet(
6188 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6189 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6190 Depth + 1);
6191 } else {
6192 // Out of bounds index is poison.
6193 Known.KnownFPClasses = fcNone;
6194 }
6195 } else {
6196 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6197 }
6198 break;
6199 }
6200 case ISD::SPLAT_VECTOR: {
6201 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6202 break;
6203 }
6204 case ISD::BITCAST: {
6205 // FIXME: It should not be necessary to check for an elementwise bitcast.
6206 // If a bitcast is not elementwise between vector / scalar types,
6207 // computeKnownBits already splices the known bits of the source elements
6208 // appropriately so as to line up with the bits of the result's demanded
6209 // elements.
6210 EVT SrcVT = Op.getOperand(0).getValueType();
6211 if (VT.isScalableVector() || SrcVT.isScalableVector())
6212 break;
6213 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6214 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6215 if (VTNumElts != SrcVTNumElts)
6216 break;
6217
6218 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6220 break;
6221 }
6222 case ISD::FABS: {
6223 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6224 InterestedClasses, Depth + 1);
6225 Known.fabs();
6226 break;
6227 }
6228 case ISD::FCOPYSIGN: {
6229 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6230 InterestedClasses, Depth + 1);
6231 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6232 InterestedClasses, Depth + 1);
6233 Known.copysign(KnownSign);
6234 break;
6235 }
6236 case ISD::AssertNoFPClass: {
6237 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6238 InterestedClasses, Depth + 1);
6239 FPClassTest AssertedClasses =
6240 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6241 Known.KnownFPClasses &= ~AssertedClasses;
6242 break;
6243 }
6245 SDValue Src = Op.getOperand(0);
6246 EVT SrcVT = Src.getValueType();
6247 if (SrcVT.isFixedLengthVector()) {
6248 unsigned Idx = Op.getConstantOperandVal(1);
6249 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6250
6251 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6252 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6253 Depth + 1);
6254 } else {
6255 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6256 }
6257 break;
6258 }
6259 case ISD::INSERT_SUBVECTOR: {
6260 SDValue BaseVector = Op.getOperand(0);
6261 SDValue SubVector = Op.getOperand(1);
6262 EVT BaseVT = BaseVector.getValueType();
6263 if (BaseVT.isFixedLengthVector()) {
6264 unsigned Idx = Op.getConstantOperandVal(2);
6265 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6266 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6267
6268 APInt DemandedMask =
6269 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6270 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6271 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6272
6273 if (!DemandedSrcElts.isZero())
6274 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6275 InterestedClasses, Depth + 1);
6276 if (!DemandedSubElts.isZero()) {
6278 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6279 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6280 }
6281 } else {
6282 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6283 if (!Known.isUnknown())
6284 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6285 }
6286 break;
6287 }
6288 case ISD::SELECT:
6289 case ISD::VSELECT: {
6290 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6291 // IR-level ValueTracking.
6292 KnownFPClass KnownFalseClass = computeKnownFPClass(
6293 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6294 if (KnownFalseClass.isUnknown())
6295 break;
6296 KnownFPClass KnownTrueClass = computeKnownFPClass(
6297 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6298 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6299 break;
6300 }
6301 default:
6302 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6303 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6304 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6305 Depth);
6306 }
6307 break;
6308 }
6309
6310 return Known;
6311}
6312
6314 unsigned Depth) const {
6315 APInt DemandedElts = getDemandAllEltsMask(Op);
6316 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6317}
6318
6320 bool SNaN, unsigned Depth) const {
6321 assert(!DemandedElts.isZero() && "No demanded elements");
6322
6323 // If we're told that NaNs won't happen, assume they won't.
6324 if (Op->getFlags().hasNoNaNs())
6325 return true;
6326
6327 if (Depth >= MaxRecursionDepth)
6328 return false; // Limit search depth.
6329
6330 unsigned Opcode = Op.getOpcode();
6331 switch (Opcode) {
6332 case ISD::FADD:
6333 case ISD::FSUB:
6334 case ISD::FMUL:
6335 case ISD::FDIV:
6336 case ISD::FREM:
6337 case ISD::FSIN:
6338 case ISD::FCOS:
6339 case ISD::FTAN:
6340 case ISD::FASIN:
6341 case ISD::FACOS:
6342 case ISD::FATAN:
6343 case ISD::FATAN2:
6344 case ISD::FSINH:
6345 case ISD::FCOSH:
6346 case ISD::FTANH:
6347 case ISD::FMA:
6348 case ISD::FMULADD:
6349 case ISD::FMAD: {
6350 if (SNaN)
6351 return true;
6352 // TODO: Need isKnownNeverInfinity
6353 return false;
6354 }
6355 case ISD::FCANONICALIZE:
6356 case ISD::FEXP:
6357 case ISD::FEXP2:
6358 case ISD::FEXP10:
6359 case ISD::FTRUNC:
6360 case ISD::FFLOOR:
6361 case ISD::FCEIL:
6362 case ISD::FROUND:
6363 case ISD::FROUNDEVEN:
6364 case ISD::LROUND:
6365 case ISD::LLROUND:
6366 case ISD::FRINT:
6367 case ISD::LRINT:
6368 case ISD::LLRINT:
6369 case ISD::FNEARBYINT:
6370 case ISD::FLDEXP: {
6371 if (SNaN)
6372 return true;
6373 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6374 }
6375 case ISD::FABS:
6376 case ISD::FNEG:
6377 case ISD::FCOPYSIGN: {
6378 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6379 }
6380 case ISD::SELECT:
6381 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6382 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6383 case ISD::FP_EXTEND:
6384 case ISD::FP_ROUND: {
6385 if (SNaN)
6386 return true;
6387 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6388 }
6389 case ISD::SINT_TO_FP:
6390 case ISD::UINT_TO_FP:
6391 return true;
6392 case ISD::FSQRT: // Need is known positive
6393 case ISD::FLOG:
6394 case ISD::FLOG2:
6395 case ISD::FLOG10:
6396 case ISD::FPOWI:
6397 case ISD::FPOW: {
6398 if (SNaN)
6399 return true;
6400 // TODO: Refine on operand
6401 return false;
6402 }
6403 case ISD::FMINNUM:
6404 case ISD::FMAXNUM:
6405 case ISD::FMINIMUMNUM:
6406 case ISD::FMAXIMUMNUM: {
6407 // Only one needs to be known not-nan, since it will be returned if the
6408 // other ends up being one.
6409 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6410 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6411 }
6412 case ISD::FMINNUM_IEEE:
6413 case ISD::FMAXNUM_IEEE: {
6414 if (SNaN)
6415 return true;
6416 // This can return a NaN if either operand is an sNaN, or if both operands
6417 // are NaN.
6418 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6419 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6420 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6421 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6422 }
6423 case ISD::FMINIMUM:
6424 case ISD::FMAXIMUM: {
6425 // TODO: Does this quiet or return the origina NaN as-is?
6426 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6427 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6428 }
6430 SDValue Src = Op.getOperand(0);
6431 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6432 EVT SrcVT = Src.getValueType();
6433 if (SrcVT.isFixedLengthVector() && Idx &&
6434 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6435 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6436 Idx->getZExtValue());
6437 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6438 }
6439 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6440 }
6442 SDValue Src = Op.getOperand(0);
6443 if (Src.getValueType().isFixedLengthVector()) {
6444 unsigned Idx = Op.getConstantOperandVal(1);
6445 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6446 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6447 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6448 }
6449 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6450 }
6451 case ISD::INSERT_SUBVECTOR: {
6452 SDValue BaseVector = Op.getOperand(0);
6453 SDValue SubVector = Op.getOperand(1);
6454 EVT BaseVectorVT = BaseVector.getValueType();
6455 if (BaseVectorVT.isFixedLengthVector()) {
6456 unsigned Idx = Op.getConstantOperandVal(2);
6457 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6458 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6459
6460 // Clear/Extract the bits at the position where the subvector will be
6461 // inserted.
6462 APInt DemandedMask =
6463 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6464 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6465 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6466
6467 bool NeverNaN = true;
6468 if (!DemandedSrcElts.isZero())
6469 NeverNaN &=
6470 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6471 if (NeverNaN && !DemandedSubElts.isZero())
6472 NeverNaN &=
6473 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6474 return NeverNaN;
6475 }
6476 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6477 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6478 }
6479 case ISD::BUILD_VECTOR: {
6480 unsigned NumElts = Op.getNumOperands();
6481 for (unsigned I = 0; I != NumElts; ++I)
6482 if (DemandedElts[I] &&
6483 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6484 return false;
6485 return true;
6486 }
6487 case ISD::SPLAT_VECTOR:
6488 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6489 case ISD::AssertNoFPClass: {
6490 FPClassTest NoFPClass =
6491 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6492 if ((NoFPClass & fcNan) == fcNan)
6493 return true;
6494 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6495 return true;
6496 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6497 }
6498 default:
6499 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6500 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6501 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6502 Depth);
6503 }
6504 break;
6505 }
6506
6507 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6508 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6509 return Known.isKnownNever(NanMask);
6510}
6511
6513 APInt DemandedElts = getDemandAllEltsMask(Op);
6514 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6515}
6516
6518 const APInt &DemandedElts,
6519 unsigned Depth) const {
6520 assert(!DemandedElts.isZero() && "No demanded elements");
6521 EVT VT = Op.getValueType();
6523 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6524 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6525}
6526
6528 APInt DemandedElts = getDemandAllEltsMask(Op);
6529 return isKnownNeverZero(Op, DemandedElts, Depth);
6530}
6531
6533 unsigned Depth) const {
6534 if (Depth >= MaxRecursionDepth)
6535 return false; // Limit search depth.
6536
6537 EVT OpVT = Op.getValueType();
6538 unsigned BitWidth = OpVT.getScalarSizeInBits();
6539
6540 assert(!Op.getValueType().isFloatingPoint() &&
6541 "Floating point types unsupported - use isKnownNeverLogicalZero");
6542
6543 // If the value is a constant, we can obviously see if it is a zero or not.
6544 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6545 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6546 return !V.isZero();
6547 };
6548
6549 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6550 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6551 return true;
6552
6553 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6554 // some degree.
6555 switch (Op.getOpcode()) {
6556 default:
6557 break;
6558
6560 SDValue InVec = Op.getOperand(0);
6561 SDValue EltNo = Op.getOperand(1);
6562 EVT VecVT = InVec.getValueType();
6563
6564 // Skip scalable vectors or implicit extensions.
6565 if (VecVT.isScalableVector() ||
6566 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6567 break;
6568
6569 // If we know the element index, just demand that vector element, else for
6570 // an unknown element index, ignore DemandedElts and demand them all.
6571 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6572 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6573 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6574 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6575 DemandedSrcElts =
6576 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6577
6578 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6579 }
6580
6581 case ISD::OR:
6582 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6583 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6584
6585 case ISD::VSELECT:
6586 case ISD::SELECT:
6587 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6588 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6589
6590 case ISD::SHL: {
6591 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6592 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6593 KnownBits ValKnown =
6594 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6595 // 1 << X is never zero.
6596 if (ValKnown.One[0])
6597 return true;
6598 // If max shift cnt of known ones is non-zero, result is non-zero.
6599 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6600 .getMaxValue();
6601 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6602 !ValKnown.One.shl(MaxCnt).isZero())
6603 return true;
6604 break;
6605 }
6606
6607 case ISD::VECTOR_SHUFFLE: {
6608 if (Op.getValueType().isScalableVector())
6609 return false;
6610
6611 unsigned NumElts = DemandedElts.getBitWidth();
6612
6613 // All demanded elements from LHS and RHS must be known non-zero.
6614 // Demanded elements with undef shuffle mask elements are unknown.
6615
6616 APInt DemandedLHS, DemandedRHS;
6617 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6618 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6619 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6620 DemandedLHS, DemandedRHS))
6621 return false;
6622
6623 return (!DemandedLHS ||
6624 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6625 (!DemandedRHS ||
6626 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6627 }
6628
6629 case ISD::UADDSAT:
6630 case ISD::UMAX:
6631 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6632 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6633
6634 case ISD::UMIN:
6635 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6636 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6637
6638 // For smin/smax: If either operand is known negative/positive
6639 // respectively we don't need the other to be known at all.
6640 case ISD::SMAX: {
6641 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6642 if (Op1.isStrictlyPositive())
6643 return true;
6644
6645 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6646 if (Op0.isStrictlyPositive())
6647 return true;
6648
6649 if (Op1.isNonZero() && Op0.isNonZero())
6650 return true;
6651
6652 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6653 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6654 }
6655 case ISD::SMIN: {
6656 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6657 if (Op1.isNegative())
6658 return true;
6659
6660 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6661 if (Op0.isNegative())
6662 return true;
6663
6664 if (Op1.isNonZero() && Op0.isNonZero())
6665 return true;
6666
6667 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6668 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6669 }
6670
6671 case ISD::ROTL:
6672 case ISD::ROTR:
6673 case ISD::BITREVERSE:
6674 case ISD::BSWAP:
6675 case ISD::CTPOP:
6676 case ISD::ABS:
6678 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6679
6680 case ISD::SRA:
6681 case ISD::SRL: {
6682 if (Op->getFlags().hasExact())
6683 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6684 KnownBits ValKnown =
6685 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6686 if (ValKnown.isNegative())
6687 return true;
6688 // If max shift cnt of known ones is non-zero, result is non-zero.
6689 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6690 .getMaxValue();
6691 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6692 !ValKnown.One.lshr(MaxCnt).isZero())
6693 return true;
6694 break;
6695 }
6696 case ISD::UDIV:
6697 case ISD::SDIV:
6698 // div exact can only produce a zero if the dividend is zero.
6699 // TODO: For udiv this is also true if Op1 u<= Op0
6700 if (Op->getFlags().hasExact())
6701 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6702 break;
6703
6704 case ISD::ADD:
6705 if (Op->getFlags().hasNoUnsignedWrap())
6706 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6707 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6708 return true;
6709 // TODO: There are a lot more cases we can prove for add.
6710 break;
6711
6712 case ISD::SUB: {
6713 if (isNullConstant(Op.getOperand(0)))
6714 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6715
6716 std::optional<bool> ne = KnownBits::ne(
6717 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6718 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6719 return ne && *ne;
6720 }
6721
6722 case ISD::MUL:
6723 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6724 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6725 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6726 return true;
6727 break;
6728
6729 case ISD::ZERO_EXTEND:
6730 case ISD::SIGN_EXTEND:
6731 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6732 case ISD::VSCALE: {
6734 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6735 ConstantRange CR =
6736 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6737 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6738 return true;
6739 break;
6740 }
6741 }
6742
6743 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6744}
6745
6747 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6748 return !C1->isNegative();
6749
6750 switch (Op.getOpcode()) {
6751 case ISD::FABS:
6752 case ISD::FEXP:
6753 case ISD::FEXP2:
6754 case ISD::FEXP10:
6755 return true;
6756 default:
6757 return false;
6758 }
6759
6760 llvm_unreachable("covered opcode switch");
6761}
6762
6764 assert(Use.getValueType().isFloatingPoint());
6765 const SDNode *User = Use.getUser();
6766 if (User->getFlags().hasNoSignedZeros())
6767 return true;
6768
6769 unsigned OperandNo = Use.getOperandNo();
6770 // Check if this use is insensitive to the sign of zero
6771 switch (User->getOpcode()) {
6772 case ISD::SETCC:
6773 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6774 case ISD::FABS:
6775 // fabs always produces +0.0.
6776 return true;
6777 case ISD::FCOPYSIGN:
6778 // copysign overwrites the sign bit of the first operand.
6779 return OperandNo == 0;
6780 case ISD::FADD:
6781 case ISD::FSUB: {
6782 // Arithmetic with non-zero constants fixes the uncertainty around the
6783 // sign bit.
6784 SDValue Other = User->getOperand(1 - OperandNo);
6786 }
6787 case ISD::FP_TO_SINT:
6788 case ISD::FP_TO_UINT:
6789 // fp-to-int conversions normalize signed zeros.
6790 return true;
6791 default:
6792 return false;
6793 }
6794}
6795
6797 if (Op->getFlags().hasNoSignedZeros())
6798 return true;
6799 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6800 // regression. Ideally, this should be implemented as a demanded-bits
6801 // optimization that stems from the users.
6802 if (Op->use_size() > 2)
6803 return false;
6804 return all_of(Op->uses(),
6805 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6806}
6807
6809 // Check the obvious case.
6810 if (A == B) return true;
6811
6812 // For negative and positive zero.
6815 if (CA->isZero() && CB->isZero()) return true;
6816
6817 // Otherwise they may not be equal.
6818 return false;
6819}
6820
6821// Only bits set in Mask must be negated, other bits may be arbitrary.
6823 if (isBitwiseNot(V, AllowUndefs))
6824 return V.getOperand(0);
6825
6826 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6827 // bits in the non-extended part.
6828 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6829 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6830 return SDValue();
6831 SDValue ExtArg = V.getOperand(0);
6832 if (ExtArg.getScalarValueSizeInBits() >=
6833 MaskC->getAPIntValue().getActiveBits() &&
6834 isBitwiseNot(ExtArg, AllowUndefs) &&
6835 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6836 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6837 return ExtArg.getOperand(0).getOperand(0);
6838 return SDValue();
6839}
6840
6842 // Match masked merge pattern (X & ~M) op (Y & M)
6843 // Including degenerate case (X & ~M) op M
6844 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6845 SDValue Other) {
6846 if (SDValue NotOperand =
6847 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6848 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6849 NotOperand->getOpcode() == ISD::TRUNCATE)
6850 NotOperand = NotOperand->getOperand(0);
6851
6852 if (Other == NotOperand)
6853 return true;
6854 if (Other->getOpcode() == ISD::AND)
6855 return NotOperand == Other->getOperand(0) ||
6856 NotOperand == Other->getOperand(1);
6857 }
6858 return false;
6859 };
6860
6861 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6862 A = A->getOperand(0);
6863
6864 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6865 B = B->getOperand(0);
6866
6867 if (A->getOpcode() == ISD::AND)
6868 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6869 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6870 return false;
6871}
6872
6873// FIXME: unify with llvm::haveNoCommonBitsSet.
6875 assert(A.getValueType() == B.getValueType() &&
6876 "Values must have the same type");
6879 return true;
6882}
6883
6884static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6885 SelectionDAG &DAG) {
6886 if (cast<ConstantSDNode>(Step)->isZero())
6887 return DAG.getConstant(0, DL, VT);
6888
6889 return SDValue();
6890}
6891
6894 SelectionDAG &DAG) {
6895 int NumOps = Ops.size();
6896 assert(NumOps != 0 && "Can't build an empty vector!");
6897 assert(!VT.isScalableVector() &&
6898 "BUILD_VECTOR cannot be used with scalable types");
6899 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6900 "Incorrect element count in BUILD_VECTOR!");
6901
6902 // BUILD_VECTOR of UNDEFs is UNDEF.
6903 bool AllPoison = true;
6904 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6905 AllPoison &= Op.getOpcode() == ISD::POISON;
6906 return Op.isUndef();
6907 }))
6908 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6909
6910 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6911 SDValue IdentitySrc;
6912 bool IsIdentity = true;
6913 for (int i = 0; i != NumOps; ++i) {
6914 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6915 Ops[i].getOperand(0).getValueType() != VT ||
6916 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6917 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6918 Ops[i].getConstantOperandAPInt(1) != i) {
6919 IsIdentity = false;
6920 break;
6921 }
6922 IdentitySrc = Ops[i].getOperand(0);
6923 }
6924 if (IsIdentity)
6925 return IdentitySrc;
6926
6927 return SDValue();
6928}
6929
6930/// Try to simplify vector concatenation to an input value, undef, or build
6931/// vector.
6934 SelectionDAG &DAG) {
6935 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6937 [Ops](SDValue Op) {
6938 return Ops[0].getValueType() == Op.getValueType();
6939 }) &&
6940 "Concatenation of vectors with inconsistent value types!");
6941 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6942 VT.getVectorElementCount() &&
6943 "Incorrect element count in vector concatenation!");
6944
6945 if (Ops.size() == 1)
6946 return Ops[0];
6947
6948 // Concat of UNDEFs is UNDEF.
6949 bool AllPoison = true;
6950 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6951 AllPoison &= Op.getOpcode() == ISD::POISON;
6952 return Op.isUndef();
6953 }))
6954 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6955
6956 // Scan the operands and look for extract operations from a single source
6957 // that correspond to insertion at the same location via this concatenation:
6958 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
6959 SDValue IdentitySrc;
6960 bool IsIdentity = true;
6961 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
6962 SDValue Op = Ops[i];
6963 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
6964 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6965 Op.getOperand(0).getValueType() != VT ||
6966 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
6967 Op.getConstantOperandVal(1) != IdentityIndex) {
6968 IsIdentity = false;
6969 break;
6970 }
6971 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
6972 "Unexpected identity source vector for concat of extracts");
6973 IdentitySrc = Op.getOperand(0);
6974 }
6975 if (IsIdentity) {
6976 assert(IdentitySrc && "Failed to set source vector of extracts");
6977 return IdentitySrc;
6978 }
6979
6980 // The code below this point is only designed to work for fixed width
6981 // vectors, so we bail out for now.
6982 if (VT.isScalableVector())
6983 return SDValue();
6984
6985 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
6986 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
6987 // BUILD_VECTOR.
6988 // FIXME: Add support for SCALAR_TO_VECTOR as well.
6989 EVT SVT = VT.getScalarType();
6991 for (SDValue Op : Ops) {
6992 EVT OpVT = Op.getValueType();
6993 if (Op.getOpcode() == ISD::POISON)
6994 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
6995 else if (Op.getOpcode() == ISD::UNDEF)
6996 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
6997 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
6998 Elts.append(Op->op_begin(), Op->op_end());
6999 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7000 OpVT.getVectorNumElements() == 1 &&
7001 isNullConstant(Op.getOperand(2)))
7002 Elts.push_back(Op.getOperand(1));
7003 else
7004 return SDValue();
7005 }
7006
7007 // BUILD_VECTOR requires all inputs to be of the same type, find the
7008 // maximum type and extend them all.
7009 for (SDValue Op : Elts)
7010 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7011
7012 if (SVT.bitsGT(VT.getScalarType())) {
7013 for (SDValue &Op : Elts) {
7014 if (Op.getOpcode() == ISD::POISON)
7015 Op = DAG.getPOISON(SVT);
7016 else if (Op.getOpcode() == ISD::UNDEF)
7017 Op = DAG.getUNDEF(SVT);
7018 else
7019 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7020 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7021 : DAG.getSExtOrTrunc(Op, DL, SVT);
7022 }
7023 }
7024
7025 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7026 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7027 return V;
7028}
7029
7030/// Gets or creates the specified node.
7031SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7032 SDVTList VTs = getVTList(VT);
7034 AddNodeIDNode(ID, Opcode, VTs, {});
7035 void *IP = nullptr;
7036 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7037 return SDValue(E, 0);
7038
7039 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7040 CSEMap.InsertNode(N, IP);
7041
7042 InsertNode(N);
7043 SDValue V = SDValue(N, 0);
7044 NewSDValueDbgMsg(V, "Creating new node: ", this);
7045 return V;
7046}
7047
7048SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7049 SDValue N1) {
7050 SDNodeFlags Flags;
7051 if (Inserter)
7052 Flags = Inserter->getFlags();
7053 return getNode(Opcode, DL, VT, N1, Flags);
7054}
7055
7056SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7057 SDValue N1, const SDNodeFlags Flags) {
7058 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7059
7060 // Constant fold unary operations with a vector integer or float operand.
7061 switch (Opcode) {
7062 default:
7063 // FIXME: Entirely reasonable to perform folding of other unary
7064 // operations here as the need arises.
7065 break;
7066 case ISD::FNEG:
7067 case ISD::FABS:
7068 case ISD::FCEIL:
7069 case ISD::FTRUNC:
7070 case ISD::FFLOOR:
7071 case ISD::FP_EXTEND:
7072 case ISD::FP_TO_SINT:
7073 case ISD::FP_TO_UINT:
7074 case ISD::FP_TO_FP16:
7075 case ISD::FP_TO_BF16:
7076 case ISD::TRUNCATE:
7077 case ISD::ANY_EXTEND:
7078 case ISD::ZERO_EXTEND:
7079 case ISD::SIGN_EXTEND:
7080 case ISD::UINT_TO_FP:
7081 case ISD::SINT_TO_FP:
7082 case ISD::FP16_TO_FP:
7083 case ISD::BF16_TO_FP:
7084 case ISD::BITCAST:
7085 case ISD::ABS:
7087 case ISD::BITREVERSE:
7088 case ISD::BSWAP:
7089 case ISD::CTLZ:
7091 case ISD::CTTZ:
7093 case ISD::CTPOP:
7094 case ISD::CTLS:
7095 case ISD::VECREDUCE_ADD:
7100 case ISD::VECREDUCE_MUL:
7101 case ISD::VECREDUCE_AND:
7102 case ISD::VECREDUCE_OR:
7103 case ISD::VECREDUCE_XOR:
7104 case ISD::STEP_VECTOR: {
7105 SDValue Ops = {N1};
7106 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7107 return Fold;
7108 }
7109 }
7110
7111 unsigned OpOpcode = N1.getNode()->getOpcode();
7112 switch (Opcode) {
7113 case ISD::STEP_VECTOR:
7114 assert(VT.isScalableVector() &&
7115 "STEP_VECTOR can only be used with scalable types");
7116 assert(OpOpcode == ISD::TargetConstant &&
7117 VT.getVectorElementType() == N1.getValueType() &&
7118 "Unexpected step operand");
7119 break;
7120 case ISD::FREEZE:
7121 assert(VT == N1.getValueType() && "Unexpected VT!");
7123 return N1;
7124 break;
7125 case ISD::TokenFactor:
7126 case ISD::MERGE_VALUES:
7128 return N1; // Factor, merge or concat of one node? No need.
7129 case ISD::BUILD_VECTOR: {
7130 // Attempt to simplify BUILD_VECTOR.
7131 SDValue Ops[] = {N1};
7132 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7133 return V;
7134 break;
7135 }
7136 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7137 case ISD::FP_EXTEND:
7139 "Invalid FP cast!");
7140 if (N1.getValueType() == VT) return N1; // noop conversion.
7141 assert((!VT.isVector() || VT.getVectorElementCount() ==
7143 "Vector element count mismatch!");
7144 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7145 if (N1.isUndef())
7146 return getUNDEF(VT);
7147 break;
7148 case ISD::FP_TO_SINT:
7149 case ISD::FP_TO_UINT:
7150 if (N1.isUndef())
7151 return getUNDEF(VT);
7152 break;
7153 case ISD::SINT_TO_FP:
7154 case ISD::UINT_TO_FP:
7155 // [us]itofp(undef) = 0, because the result value is bounded.
7156 if (N1.isUndef())
7157 return getConstantFP(0.0, DL, VT);
7158 break;
7159 case ISD::SIGN_EXTEND:
7160 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7161 "Invalid SIGN_EXTEND!");
7162 assert(VT.isVector() == N1.getValueType().isVector() &&
7163 "SIGN_EXTEND result type type should be vector iff the operand "
7164 "type is vector!");
7165 if (N1.getValueType() == VT) return N1; // noop extension
7166 assert((!VT.isVector() || VT.getVectorElementCount() ==
7168 "Vector element count mismatch!");
7169 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7170 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7171 SDNodeFlags Flags;
7172 if (OpOpcode == ISD::ZERO_EXTEND)
7173 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7174 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7175 transferDbgValues(N1, NewVal);
7176 return NewVal;
7177 }
7178
7179 if (OpOpcode == ISD::POISON)
7180 return getPOISON(VT);
7181
7182 if (N1.isUndef())
7183 // sext(undef) = 0, because the top bits will all be the same.
7184 return getConstant(0, DL, VT);
7185
7186 // Skip unnecessary sext_inreg pattern:
7187 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7188 if (OpOpcode == ISD::TRUNCATE) {
7189 SDValue OpOp = N1.getOperand(0);
7190 if (OpOp.getValueType() == VT) {
7191 unsigned NumSignExtBits =
7193 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7194 transferDbgValues(N1, OpOp);
7195 return OpOp;
7196 }
7197 }
7198 }
7199 break;
7200 case ISD::ZERO_EXTEND:
7201 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7202 "Invalid ZERO_EXTEND!");
7203 assert(VT.isVector() == N1.getValueType().isVector() &&
7204 "ZERO_EXTEND result type type should be vector iff the operand "
7205 "type is vector!");
7206 if (N1.getValueType() == VT) return N1; // noop extension
7207 assert((!VT.isVector() || VT.getVectorElementCount() ==
7209 "Vector element count mismatch!");
7210 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7211 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7212 SDNodeFlags Flags;
7213 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7214 SDValue NewVal =
7215 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7216 transferDbgValues(N1, NewVal);
7217 return NewVal;
7218 }
7219
7220 if (OpOpcode == ISD::POISON)
7221 return getPOISON(VT);
7222
7223 if (N1.isUndef())
7224 // zext(undef) = 0, because the top bits will be zero.
7225 return getConstant(0, DL, VT);
7226
7227 // Skip unnecessary zext_inreg pattern:
7228 // (zext (trunc x)) -> x iff the upper bits are known zero.
7229 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7230 // use to recognise zext_inreg patterns.
7231 if (OpOpcode == ISD::TRUNCATE) {
7232 SDValue OpOp = N1.getOperand(0);
7233 if (OpOp.getValueType() == VT) {
7234 if (OpOp.getOpcode() != ISD::AND) {
7237 if (MaskedValueIsZero(OpOp, HiBits)) {
7238 transferDbgValues(N1, OpOp);
7239 return OpOp;
7240 }
7241 }
7242 }
7243 }
7244 break;
7245 case ISD::ANY_EXTEND:
7246 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7247 "Invalid ANY_EXTEND!");
7248 assert(VT.isVector() == N1.getValueType().isVector() &&
7249 "ANY_EXTEND result type type should be vector iff the operand "
7250 "type is vector!");
7251 if (N1.getValueType() == VT) return N1; // noop extension
7252 assert((!VT.isVector() || VT.getVectorElementCount() ==
7254 "Vector element count mismatch!");
7255 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7256
7257 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7258 OpOpcode == ISD::ANY_EXTEND) {
7259 SDNodeFlags Flags;
7260 if (OpOpcode == ISD::ZERO_EXTEND)
7261 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7262 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7263 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7264 }
7265 if (N1.isUndef())
7266 return getUNDEF(VT);
7267
7268 // (ext (trunc x)) -> x
7269 if (OpOpcode == ISD::TRUNCATE) {
7270 SDValue OpOp = N1.getOperand(0);
7271 if (OpOp.getValueType() == VT) {
7272 transferDbgValues(N1, OpOp);
7273 return OpOp;
7274 }
7275 }
7276 break;
7277 case ISD::TRUNCATE:
7278 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7279 "Invalid TRUNCATE!");
7280 assert(VT.isVector() == N1.getValueType().isVector() &&
7281 "TRUNCATE result type type should be vector iff the operand "
7282 "type is vector!");
7283 if (N1.getValueType() == VT) return N1; // noop truncate
7284 assert((!VT.isVector() || VT.getVectorElementCount() ==
7286 "Vector element count mismatch!");
7287 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7288 if (OpOpcode == ISD::TRUNCATE)
7289 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7290 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7291 OpOpcode == ISD::ANY_EXTEND) {
7292 // If the source is smaller than the dest, we still need an extend.
7294 VT.getScalarType())) {
7295 SDNodeFlags Flags;
7296 if (OpOpcode == ISD::ZERO_EXTEND)
7297 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7298 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7299 }
7300 if (N1.getOperand(0).getValueType().bitsGT(VT))
7301 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7302 return N1.getOperand(0);
7303 }
7304 if (N1.isUndef())
7305 return getUNDEF(VT);
7306 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7307 return getVScale(DL, VT,
7309 break;
7313 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7314 assert(N1.getValueType().bitsLE(VT) &&
7315 "The input must be the same size or smaller than the result.");
7318 "The destination vector type must have fewer lanes than the input.");
7319 break;
7320 case ISD::ABS:
7321 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7322 if (N1.isUndef())
7323 return getConstant(0, DL, VT);
7324 break;
7326 assert(VT.isInteger() && VT == N1.getValueType() &&
7327 "Invalid ABS_MIN_POISON!");
7328 if (N1.isUndef())
7329 return getConstant(0, DL, VT);
7330 break;
7331 case ISD::BSWAP:
7332 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7333 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7334 "BSWAP types must be a multiple of 16 bits!");
7335 if (N1.isUndef())
7336 return getUNDEF(VT);
7337 // bswap(bswap(X)) -> X.
7338 if (OpOpcode == ISD::BSWAP)
7339 return N1.getOperand(0);
7340 break;
7341 case ISD::BITREVERSE:
7342 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7343 if (N1.isUndef())
7344 return getUNDEF(VT);
7345 break;
7346 case ISD::BITCAST:
7348 "Cannot BITCAST between types of different sizes!");
7349 if (VT == N1.getValueType()) return N1; // noop conversion.
7350 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7351 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7352 if (N1.isUndef())
7353 return getUNDEF(VT);
7354 break;
7356 assert(VT.isVector() && !N1.getValueType().isVector() &&
7357 (VT.getVectorElementType() == N1.getValueType() ||
7359 N1.getValueType().isInteger() &&
7361 "Illegal SCALAR_TO_VECTOR node!");
7362 if (N1.isUndef())
7363 return getUNDEF(VT);
7364 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7365 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7367 N1.getConstantOperandVal(1) == 0 &&
7368 N1.getOperand(0).getValueType() == VT)
7369 return N1.getOperand(0);
7370 break;
7371 case ISD::FNEG:
7372 // Negation of an unknown bag of bits is still completely undefined.
7373 if (N1.isUndef())
7374 return getUNDEF(VT);
7375
7376 if (OpOpcode == ISD::FNEG) // --X -> X
7377 return N1.getOperand(0);
7378 break;
7379 case ISD::FABS:
7380 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7381 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7382 break;
7383 case ISD::VSCALE:
7384 assert(VT == N1.getValueType() && "Unexpected VT!");
7385 break;
7386 case ISD::CTPOP:
7387 if (N1.getValueType().getScalarType() == MVT::i1)
7388 return N1;
7389 break;
7390 case ISD::CTLZ:
7391 case ISD::CTTZ:
7392 if (N1.getValueType().getScalarType() == MVT::i1)
7393 return getNOT(DL, N1, N1.getValueType());
7394 break;
7395 case ISD::CTLS:
7396 if (N1.getValueType().getScalarType() == MVT::i1)
7397 return getConstant(0, DL, VT);
7398 break;
7399 case ISD::VECREDUCE_ADD:
7400 if (N1.getValueType().getScalarType() == MVT::i1)
7401 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7402 break;
7405 if (N1.getValueType().getScalarType() == MVT::i1)
7406 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7407 break;
7410 if (N1.getValueType().getScalarType() == MVT::i1)
7411 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7412 break;
7413 case ISD::SPLAT_VECTOR:
7414 assert(VT.isVector() && "Wrong return type!");
7415 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7416 // that for now.
7418 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7420 N1.getValueType().isInteger() &&
7422 "Wrong operand type!");
7423 break;
7424 }
7425
7426 SDNode *N;
7427 SDVTList VTs = getVTList(VT);
7428 SDValue Ops[] = {N1};
7429 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7431 AddNodeIDNode(ID, Opcode, VTs, Ops);
7432 void *IP = nullptr;
7433 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7434 E->intersectFlagsWith(Flags);
7435 return SDValue(E, 0);
7436 }
7437
7438 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7439 N->setFlags(Flags);
7440 createOperands(N, Ops);
7441 CSEMap.InsertNode(N, IP);
7442 } else {
7443 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7444 createOperands(N, Ops);
7445 }
7446
7447 InsertNode(N);
7448 SDValue V = SDValue(N, 0);
7449 NewSDValueDbgMsg(V, "Creating new node: ", this);
7450 return V;
7451}
7452
7453static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7454 switch (Opcode) {
7455 default:
7456 llvm_unreachable("Unexpected integer identity opcode");
7457 case ISD::ADD:
7458 case ISD::OR:
7459 case ISD::XOR:
7460 case ISD::UMAX:
7461 return APInt::getZero(BitWidth);
7462 case ISD::MUL:
7463 return APInt(BitWidth, 1);
7464 case ISD::AND:
7465 case ISD::UMIN:
7467 case ISD::SMAX:
7469 case ISD::SMIN:
7471 }
7472}
7473
7474static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7475 const APInt &C2) {
7476 switch (Opcode) {
7477 case ISD::ADD: return C1 + C2;
7478 case ISD::SUB: return C1 - C2;
7479 case ISD::MUL: return C1 * C2;
7480 case ISD::AND: return C1 & C2;
7481 case ISD::OR: return C1 | C2;
7482 case ISD::XOR: return C1 ^ C2;
7483 case ISD::SHL: return C1 << C2;
7484 case ISD::SRL: return C1.lshr(C2);
7485 case ISD::SRA: return C1.ashr(C2);
7486 case ISD::ROTL: return C1.rotl(C2);
7487 case ISD::ROTR: return C1.rotr(C2);
7488 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7489 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7490 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7491 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7492 case ISD::SADDSAT: return C1.sadd_sat(C2);
7493 case ISD::UADDSAT: return C1.uadd_sat(C2);
7494 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7495 case ISD::USUBSAT: return C1.usub_sat(C2);
7496 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7497 case ISD::USHLSAT: return C1.ushl_sat(C2);
7498 case ISD::UDIV:
7499 if (!C2.getBoolValue())
7500 break;
7501 return C1.udiv(C2);
7502 case ISD::UREM:
7503 if (!C2.getBoolValue())
7504 break;
7505 return C1.urem(C2);
7506 case ISD::SDIV:
7507 if (!C2.getBoolValue())
7508 break;
7509 return C1.sdiv(C2);
7510 case ISD::SREM:
7511 if (!C2.getBoolValue())
7512 break;
7513 return C1.srem(C2);
7514 case ISD::AVGFLOORS:
7515 return APIntOps::avgFloorS(C1, C2);
7516 case ISD::AVGFLOORU:
7517 return APIntOps::avgFloorU(C1, C2);
7518 case ISD::AVGCEILS:
7519 return APIntOps::avgCeilS(C1, C2);
7520 case ISD::AVGCEILU:
7521 return APIntOps::avgCeilU(C1, C2);
7522 case ISD::ABDS:
7523 return APIntOps::abds(C1, C2);
7524 case ISD::ABDU:
7525 return APIntOps::abdu(C1, C2);
7526 case ISD::MULHS:
7527 return APIntOps::mulhs(C1, C2);
7528 case ISD::MULHU:
7529 return APIntOps::mulhu(C1, C2);
7530 case ISD::CLMUL:
7531 return APIntOps::clmul(C1, C2);
7532 case ISD::CLMULR:
7533 return APIntOps::clmulr(C1, C2);
7534 case ISD::CLMULH:
7535 return APIntOps::clmulh(C1, C2);
7536 case ISD::PEXT:
7537 return APIntOps::pext(C1, C2);
7538 case ISD::PDEP:
7539 return APIntOps::pdep(C1, C2);
7540 }
7541 return std::nullopt;
7542}
7543// Handle constant folding with UNDEF.
7544// TODO: Handle more cases.
7545static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7546 bool IsUndef1, const APInt &C2,
7547 bool IsUndef2) {
7548 if (!(IsUndef1 || IsUndef2))
7549 return FoldValue(Opcode, C1, C2);
7550
7551 // Fold and(x, undef) -> 0
7552 // Fold mul(x, undef) -> 0
7553 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7554 return APInt::getZero(C1.getBitWidth());
7555
7556 return std::nullopt;
7557}
7558
7560 const GlobalAddressSDNode *GA,
7561 const SDNode *N2) {
7562 if (GA->getOpcode() != ISD::GlobalAddress)
7563 return SDValue();
7564 if (!TLI->isOffsetFoldingLegal(GA))
7565 return SDValue();
7566 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7567 if (!C2)
7568 return SDValue();
7569 int64_t Offset = C2->getSExtValue();
7570 switch (Opcode) {
7571 case ISD::ADD:
7572 case ISD::PTRADD:
7573 break;
7574 case ISD::SUB: Offset = -uint64_t(Offset); break;
7575 default: return SDValue();
7576 }
7577 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7578 GA->getOffset() + uint64_t(Offset));
7579}
7580
7582 switch (Opcode) {
7583 case ISD::SDIV:
7584 case ISD::UDIV:
7585 case ISD::SREM:
7586 case ISD::UREM: {
7587 // If a divisor is zero/undef or any element of a divisor vector is
7588 // zero/undef, the whole op is undef.
7589 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7590 SDValue Divisor = Ops[1];
7591 if (Divisor.isUndef() || isNullConstant(Divisor))
7592 return true;
7593
7594 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7595 llvm::any_of(Divisor->op_values(),
7596 [](SDValue V) { return V.isUndef() ||
7597 isNullConstant(V); });
7598 // TODO: Handle signed overflow.
7599 }
7600 // TODO: Handle oversized shifts.
7601 default:
7602 return false;
7603 }
7604}
7605
7608 SDNodeFlags Flags) {
7609 // If the opcode is a target-specific ISD node, there's nothing we can
7610 // do here and the operand rules may not line up with the below, so
7611 // bail early.
7612 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7613 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7614 // foldCONCAT_VECTORS in getNode before this is called.
7615 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7616 return SDValue();
7617
7618 unsigned NumOps = Ops.size();
7619 if (NumOps == 0)
7620 return SDValue();
7621
7622 if (isUndef(Opcode, Ops))
7623 return getUNDEF(VT);
7624
7625 // Handle unary special cases.
7626 if (NumOps == 1) {
7627 SDValue N1 = Ops[0];
7628
7629 // Constant fold unary operations with an integer constant operand. Even
7630 // opaque constant will be folded, because the folding of unary operations
7631 // doesn't create new constants with different values. Nevertheless, the
7632 // opaque flag is preserved during folding to prevent future folding with
7633 // other constants.
7634 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7635 const APInt &Val = C->getAPIntValue();
7636 switch (Opcode) {
7637 case ISD::SIGN_EXTEND:
7638 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7639 C->isTargetOpcode(), C->isOpaque());
7640 case ISD::TRUNCATE:
7641 if (C->isOpaque())
7642 break;
7643 [[fallthrough]];
7644 case ISD::ZERO_EXTEND:
7645 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7646 C->isTargetOpcode(), C->isOpaque());
7647 case ISD::ANY_EXTEND:
7648 // Some targets like RISCV prefer to sign extend some types.
7649 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7650 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7651 C->isTargetOpcode(), C->isOpaque());
7652 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7653 C->isTargetOpcode(), C->isOpaque());
7654 case ISD::ABS:
7655 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7656 C->isOpaque());
7658 if (Val.isMinSignedValue())
7659 return getPOISON(VT);
7660 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7661 C->isOpaque());
7662 case ISD::BITREVERSE:
7663 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7664 C->isOpaque());
7665 case ISD::BSWAP:
7666 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7667 C->isOpaque());
7668 case ISD::CTPOP:
7669 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7670 C->isOpaque());
7671 case ISD::CTLZ:
7673 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7674 C->isOpaque());
7675 case ISD::CTTZ:
7677 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7678 C->isOpaque());
7679 case ISD::CTLS:
7680 // CTLS returns the number of extra sign bits so subtract one.
7681 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7682 C->isTargetOpcode(), C->isOpaque());
7683 case ISD::UINT_TO_FP:
7684 case ISD::SINT_TO_FP: {
7686 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7688 return getConstantFP(FPV, DL, VT);
7689 }
7690 case ISD::FP16_TO_FP:
7691 case ISD::BF16_TO_FP: {
7692 bool Ignored;
7693 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7694 : APFloat::BFloat(),
7695 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7696
7697 // This can return overflow, underflow, or inexact; we don't care.
7698 // FIXME need to be more flexible about rounding mode.
7700 &Ignored);
7701 return getConstantFP(FPV, DL, VT);
7702 }
7703 case ISD::STEP_VECTOR:
7704 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7705 return V;
7706 break;
7707 case ISD::BITCAST:
7708 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7709 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7710 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7711 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7712 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7713 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7714 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7715 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7716 break;
7717 }
7718 }
7719
7720 // Constant fold unary operations with a floating point constant operand.
7721 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7722 APFloat V = C->getValueAPF(); // make copy
7723 switch (Opcode) {
7724 case ISD::FNEG:
7725 V.changeSign();
7726 return getConstantFP(V, DL, VT);
7727 case ISD::FABS:
7728 V.clearSign();
7729 return getConstantFP(V, DL, VT);
7730 case ISD::FCEIL: {
7731 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7733 return getConstantFP(V, DL, VT);
7734 return SDValue();
7735 }
7736 case ISD::FTRUNC: {
7737 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7739 return getConstantFP(V, DL, VT);
7740 return SDValue();
7741 }
7742 case ISD::FFLOOR: {
7743 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7745 return getConstantFP(V, DL, VT);
7746 return SDValue();
7747 }
7748 case ISD::FP_EXTEND: {
7749 bool ignored;
7750 // This can return overflow, underflow, or inexact; we don't care.
7751 // FIXME need to be more flexible about rounding mode.
7752 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7753 &ignored);
7754 return getConstantFP(V, DL, VT);
7755 }
7756 case ISD::FP_TO_SINT:
7757 case ISD::FP_TO_UINT: {
7758 bool ignored;
7759 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7760 // FIXME need to be more flexible about rounding mode.
7762 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7763 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7764 break;
7765 return getConstant(IntVal, DL, VT);
7766 }
7767 case ISD::FP_TO_FP16:
7768 case ISD::FP_TO_BF16: {
7769 bool Ignored;
7770 // This can return overflow, underflow, or inexact; we don't care.
7771 // FIXME need to be more flexible about rounding mode.
7772 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7773 : APFloat::BFloat(),
7775 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7776 }
7777 case ISD::BITCAST:
7778 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7779 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7780 VT);
7781 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7782 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7783 VT);
7784 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7785 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7786 VT);
7787 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7788 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7789 break;
7790 }
7791 }
7792
7793 // Early-out if we failed to constant fold a bitcast.
7794 if (Opcode == ISD::BITCAST)
7795 return SDValue();
7796
7797 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7798 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7799 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7800 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7801 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7802 Opcode == ISD::VECREDUCE_AND) &&
7804 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7805 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7806 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7807 for (SDValue Elt : N1->op_values()) {
7808 if (Elt.getOpcode() == ISD::POISON)
7809 return getPOISON(VT);
7810 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7811 return SDValue();
7812 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7813 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7814 assert(Folded &&
7815 "Expected vector reduction base opcode to be foldable");
7816 Acc = *Folded;
7817 }
7818 EVT EltVT = N1.getValueType().getScalarType();
7819 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7820 }
7821 }
7822
7823 // Handle binops special cases.
7824 if (NumOps == 2) {
7825 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7826 return CFP;
7827
7828 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7829 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7830 if (C1->isOpaque() || C2->isOpaque())
7831 return SDValue();
7832
7833 std::optional<APInt> FoldAttempt =
7834 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7835 if (!FoldAttempt)
7836 return SDValue();
7837
7838 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7839 assert((!Folded || !VT.isVector()) &&
7840 "Can't fold vectors ops with scalar operands");
7841 return Folded;
7842 }
7843 }
7844
7845 // fold (add Sym, c) -> Sym+c
7847 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7848 if (TLI->isCommutativeBinOp(Opcode))
7850 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7851
7852 // fold (sext_in_reg c1) -> c2
7853 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7854 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7855
7856 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7857 unsigned FromBits = EVT.getScalarSizeInBits();
7858 Val <<= Val.getBitWidth() - FromBits;
7859 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7860 return getConstant(Val, DL, ConstantVT);
7861 };
7862
7863 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7864 const APInt &Val = C1->getAPIntValue();
7865 return SignExtendInReg(Val, VT);
7866 }
7867
7869 SmallVector<SDValue, 8> ScalarOps;
7870 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7871 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7872 SDValue Op = Ops[0].getOperand(I);
7873 if (Op.isUndef()) {
7874 ScalarOps.push_back(getUNDEF(OpVT));
7875 continue;
7876 }
7877 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7878 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7879 }
7880 return getBuildVector(VT, DL, ScalarOps);
7881 }
7882
7883 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7884 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7885 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7886 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7887 Ops[0].getOperand(0).getValueType()));
7888 }
7889 }
7890
7891 // Handle fshl/fshr special cases.
7892 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7893 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7894 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7895 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7896
7897 if (C1 && C2 && C3) {
7898 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7899 return SDValue();
7900 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7901 &V3 = C3->getAPIntValue();
7902
7903 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7904 : APIntOps::fshr(V1, V2, V3);
7905 return getConstant(FoldedVal, DL, VT);
7906 }
7907 }
7908
7909 // Handle fma/fmad special cases.
7910 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7911 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7912 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7913 Ops[2].getValueType() == VT && "FMA types must match!");
7917 if (C1 && C2 && C3) {
7918 APFloat V1 = C1->getValueAPF();
7919 const APFloat &V2 = C2->getValueAPF();
7920 const APFloat &V3 = C3->getValueAPF();
7921 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7922 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7924 } else
7925 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7926 return getConstantFP(V1, DL, VT);
7927 }
7928 }
7929
7930 // This is for vector folding only from here on.
7931 if (!VT.isVector())
7932 return SDValue();
7933
7934 // Constant fold integer partial reductions with constant BUILD_VECTOR
7935 // operands. The reduction order is deliberately unspecified. Use the same
7936 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
7937 // lane I contributes to accumulator lane I % NumAccElts.
7938 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
7939 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
7940 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
7941 // These nodes have no scalar form, so unsupported cases must not fall
7942 // through to generic per-lane vector folding.
7943 if (!llvm::all_of(Ops, [](SDValue Op) {
7944 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
7945 }))
7946 return SDValue();
7947
7948 unsigned AccEltBits = VT.getScalarSizeInBits();
7949 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
7950 unsigned NumAccElts = VT.getVectorNumElements();
7951 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
7952 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
7953 BitVector PoisonElts(NumAccElts);
7954
7955 for (unsigned I = 0; I != NumAccElts; ++I) {
7956 SDValue Elt = Ops[0].getOperand(I);
7957 if (Elt.getOpcode() == ISD::POISON) {
7958 PoisonElts.set(I);
7959 continue;
7960 }
7961 auto *C = dyn_cast<ConstantSDNode>(Elt);
7962 if (!C || C->isOpaque())
7963 return SDValue();
7964 Results[I] = C->getAPIntValue().trunc(AccEltBits);
7965 }
7966
7967 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
7968 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
7969 for (unsigned I = 0; I != NumInputElts; ++I) {
7970 const unsigned AccIdx = I % NumAccElts;
7971 SDValue LHSElt = Ops[1].getOperand(I);
7972 SDValue RHSElt = Ops[2].getOperand(I);
7973 if (LHSElt.getOpcode() == ISD::POISON ||
7974 RHSElt.getOpcode() == ISD::POISON) {
7975 PoisonElts.set(AccIdx);
7976 continue;
7977 }
7978
7979 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
7980 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
7981 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
7982 return SDValue();
7983
7984 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
7985 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
7986 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
7987 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
7988 Results[AccIdx] += LHSVal * RHSVal;
7989 }
7990
7991 // After type legalization the vector element type may not be a legal
7992 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
7993 // promoted legal scalar type instead, matching the generic per-lane path
7994 // below. Bail out if legalization would narrow the type, since the lane
7995 // value would not fit.
7996 EVT AccEltVT = VT.getVectorElementType();
7997 EVT LegalSVT = AccEltVT;
7998 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
7999 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8000 if (LegalSVT.bitsLT(AccEltVT))
8001 return SDValue();
8002 }
8003
8004 SmallVector<SDValue, 8> ResultOps;
8005 for (unsigned I = 0; I != NumAccElts; ++I)
8006 ResultOps.push_back(
8007 PoisonElts[I] ? getPOISON(LegalSVT)
8008 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8009 DL, LegalSVT));
8010 return getBuildVector(VT, DL, ResultOps);
8011 }
8012
8013 ElementCount NumElts = VT.getVectorElementCount();
8014
8015 // See if we can fold through any bitcasted integer ops.
8016 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8017 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8018 (Ops[0].getOpcode() == ISD::BITCAST ||
8019 Ops[1].getOpcode() == ISD::BITCAST)) {
8022 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8023 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8024 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8025 N2.getValueType().isInteger()) {
8026 bool IsLE = getDataLayout().isLittleEndian();
8027 unsigned EltBits = VT.getScalarSizeInBits();
8028 SmallVector<APInt> RawBits1, RawBits2;
8029 BitVector UndefElts1, UndefElts2;
8030 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8031 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8032 SmallVector<APInt> RawBits;
8033 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8034 std::optional<APInt> Fold = FoldValueWithUndef(
8035 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8036 if (!Fold)
8037 break;
8038 RawBits.push_back(*Fold);
8039 }
8040 if (RawBits.size() == NumElts.getFixedValue()) {
8041 // We have constant folded, but we might need to cast this again back
8042 // to the original (possibly legalized) type.
8043 EVT BVVT, BVEltVT;
8044 if (N1.getValueType() == VT) {
8045 BVVT = N1.getValueType();
8046 BVEltVT = BV1->getOperand(0).getValueType();
8047 } else {
8048 BVVT = N2.getValueType();
8049 BVEltVT = BV2->getOperand(0).getValueType();
8050 }
8051 unsigned BVEltBits = BVEltVT.getSizeInBits();
8052 SmallVector<APInt> DstBits;
8053 BitVector DstUndefs;
8055 DstBits, RawBits, DstUndefs,
8056 BitVector(RawBits.size(), false));
8057 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8058 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8059 if (DstUndefs[I])
8060 continue;
8061 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8062 }
8063 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8064 }
8065 }
8066 }
8067 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8068 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8069 isa<ConstantSDNode>(N2)) {
8070 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8071 {N1, N2}, Flags))
8072 return getBitcast(VT, Res);
8073 }
8074 }
8075
8076 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8077 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8078 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8079 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8080 APInt RHSVal;
8081 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8082 APInt NewStep = Opcode == ISD::MUL
8083 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8084 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8085 return getStepVector(DL, VT, NewStep);
8086 }
8087 }
8088
8089 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8090 return !Op.getValueType().isVector() ||
8091 Op.getValueType().getVectorElementCount() == NumElts;
8092 };
8093
8094 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8095 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8096 Op.getOpcode() == ISD::BUILD_VECTOR ||
8097 Op.getOpcode() == ISD::SPLAT_VECTOR;
8098 };
8099
8100 // All operands must be vector types with the same number of elements as
8101 // the result type and must be either UNDEF or a build/splat vector
8102 // or UNDEF scalars.
8103 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8104 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8105 return SDValue();
8106
8107 // If we are comparing vectors, then the result needs to be a i1 boolean that
8108 // is then extended back to the legal result type depending on how booleans
8109 // are represented.
8110 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8111 ISD::NodeType ExtendCode =
8112 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8113 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8115
8116 // Find legal integer scalar type for constant promotion and
8117 // ensure that its scalar size is at least as large as source.
8118 EVT LegalSVT = VT.getScalarType();
8119 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8120 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8121 if (LegalSVT.bitsLT(VT.getScalarType()))
8122 return SDValue();
8123 }
8124
8125 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8126 // only have one operand to check. For fixed-length vector types we may have
8127 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8128 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8129
8130 // Constant fold each scalar lane separately.
8131 SmallVector<SDValue, 4> ScalarResults;
8132 for (unsigned I = 0; I != NumVectorElts; I++) {
8133 SmallVector<SDValue, 4> ScalarOps;
8134 for (SDValue Op : Ops) {
8135 EVT InSVT = Op.getValueType().getScalarType();
8136 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8137 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8138 if (Op.isUndef())
8139 ScalarOps.push_back(getUNDEF(InSVT));
8140 else
8141 ScalarOps.push_back(Op);
8142 continue;
8143 }
8144
8145 SDValue ScalarOp =
8146 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8147 EVT ScalarVT = ScalarOp.getValueType();
8148
8149 // Build vector (integer) scalar operands may need implicit
8150 // truncation - do this before constant folding.
8151 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8152 // Don't create illegally-typed nodes unless they're constants or undef
8153 // - if we fail to constant fold we can't guarantee the (dead) nodes
8154 // we're creating will be cleaned up before being visited for
8155 // legalization.
8156 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8157 !isa<ConstantSDNode>(ScalarOp) &&
8158 TLI->getTypeAction(*getContext(), InSVT) !=
8160 return SDValue();
8161 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8162 }
8163
8164 ScalarOps.push_back(ScalarOp);
8165 }
8166
8167 // Constant fold the scalar operands.
8168 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8169
8170 // Scalar folding only succeeded if the result is a constant or UNDEF.
8171 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8172 ScalarResult.getOpcode() != ISD::ConstantFP)
8173 return SDValue();
8174
8175 // Legalize the (integer) scalar constant if necessary. We only do
8176 // this once we know the folding succeeded, since otherwise we would
8177 // get a node with illegal type which has a user.
8178 if (LegalSVT != SVT)
8179 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8180
8181 ScalarResults.push_back(ScalarResult);
8182 }
8183
8184 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8185 : getBuildVector(VT, DL, ScalarResults);
8186 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8187 return V;
8188}
8189
8192 // TODO: Add support for unary/ternary fp opcodes.
8193 if (Ops.size() != 2)
8194 return SDValue();
8195
8196 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8197 // should. That will require dealing with a potentially non-default
8198 // rounding mode, checking the "opStatus" return value from the APFloat
8199 // math calculations, and possibly other variations.
8200 SDValue N1 = Ops[0];
8201 SDValue N2 = Ops[1];
8202 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8203 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8204 if (N1CFP && N2CFP) {
8205 APFloat C1 = N1CFP->getValueAPF(); // make copy
8206 const APFloat &C2 = N2CFP->getValueAPF();
8207 switch (Opcode) {
8208 case ISD::FADD:
8210 return getConstantFP(C1, DL, VT);
8211 case ISD::FSUB:
8213 return getConstantFP(C1, DL, VT);
8214 case ISD::FMUL:
8216 return getConstantFP(C1, DL, VT);
8217 case ISD::FDIV:
8219 return getConstantFP(C1, DL, VT);
8220 case ISD::FREM:
8221 C1.mod(C2);
8222 return getConstantFP(C1, DL, VT);
8223 case ISD::FCOPYSIGN:
8224 C1.copySign(C2);
8225 return getConstantFP(C1, DL, VT);
8226 case ISD::FMINNUM:
8227 return getConstantFP(minnum(C1, C2), DL, VT);
8228 case ISD::FMAXNUM:
8229 return getConstantFP(maxnum(C1, C2), DL, VT);
8230 case ISD::FMINIMUM:
8231 return getConstantFP(minimum(C1, C2), DL, VT);
8232 case ISD::FMAXIMUM:
8233 return getConstantFP(maximum(C1, C2), DL, VT);
8234 case ISD::FMINIMUMNUM:
8235 return getConstantFP(minimumnum(C1, C2), DL, VT);
8236 case ISD::FMAXIMUMNUM:
8237 return getConstantFP(maximumnum(C1, C2), DL, VT);
8238 default: break;
8239 }
8240 }
8241 if (N1CFP && Opcode == ISD::FP_ROUND) {
8242 APFloat C1 = N1CFP->getValueAPF(); // make copy
8243 bool Unused;
8244 // This can return overflow, underflow, or inexact; we don't care.
8245 // FIXME need to be more flexible about rounding mode.
8247 &Unused);
8248 return getConstantFP(C1, DL, VT);
8249 }
8250
8251 switch (Opcode) {
8252 case ISD::FSUB:
8253 // -0.0 - undef --> undef (consistent with "fneg undef")
8254 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8255 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8256 return getUNDEF(VT);
8257 [[fallthrough]];
8258
8259 case ISD::FADD:
8260 case ISD::FMUL:
8261 case ISD::FDIV:
8262 case ISD::FREM:
8263 // If both operands are undef, the result is undef. If 1 operand is undef,
8264 // the result is NaN. This should match the behavior of the IR optimizer.
8265 if (N1.isUndef() && N2.isUndef())
8266 return getUNDEF(VT);
8267 if (N1.isUndef() || N2.isUndef())
8269 }
8270 return SDValue();
8271}
8272
8274 const SDLoc &DL, EVT DstEltVT) {
8275 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8276
8277 // If this is already the right type, we're done.
8278 if (SrcEltVT == DstEltVT)
8279 return SDValue(BV, 0);
8280
8281 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8282 unsigned DstBitSize = DstEltVT.getSizeInBits();
8283
8284 // If this is a conversion of N elements of one type to N elements of another
8285 // type, convert each element. This handles FP<->INT cases.
8286 if (SrcBitSize == DstBitSize) {
8288 for (SDValue Op : BV->op_values()) {
8289 // If the vector element type is not legal, the BUILD_VECTOR operands
8290 // are promoted and implicitly truncated. Make that explicit here.
8291 if (Op.getValueType() != SrcEltVT)
8292 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8293 Ops.push_back(getBitcast(DstEltVT, Op));
8294 }
8295 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8297 return getBuildVector(VT, DL, Ops);
8298 }
8299
8300 // Otherwise, we're growing or shrinking the elements. To avoid having to
8301 // handle annoying details of growing/shrinking FP values, we convert them to
8302 // int first.
8303 if (SrcEltVT.isFloatingPoint()) {
8304 // Convert the input float vector to a int vector where the elements are the
8305 // same sizes.
8306 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8307 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8309 DstEltVT);
8310 return SDValue();
8311 }
8312
8313 // Now we know the input is an integer vector. If the output is a FP type,
8314 // convert to integer first, then to FP of the right size.
8315 if (DstEltVT.isFloatingPoint()) {
8316 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8317 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8319 DstEltVT);
8320 return SDValue();
8321 }
8322
8323 // Okay, we know the src/dst types are both integers of differing types.
8324 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8325
8326 // Extract the constant raw bit data.
8327 BitVector UndefElements;
8328 SmallVector<APInt> RawBits;
8329 bool IsLE = getDataLayout().isLittleEndian();
8330 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8331 return SDValue();
8332
8334 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8335 if (UndefElements[I])
8336 Ops.push_back(getUNDEF(DstEltVT));
8337 else
8338 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8339 }
8340
8341 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8342 return getBuildVector(VT, DL, Ops);
8343}
8344
8346 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8347
8348 // There's no need to assert on a byte-aligned pointer. All pointers are at
8349 // least byte aligned.
8350 if (A == Align(1))
8351 return Val;
8352
8353 SDVTList VTs = getVTList(Val.getValueType());
8355 AddNodeIDNode(ID, ISD::AssertAlign, VTs, {Val});
8356 ID.AddInteger(A.value());
8357
8358 void *IP = nullptr;
8359 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8360 return SDValue(E, 0);
8361
8362 auto *N =
8363 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8364 createOperands(N, {Val});
8365
8366 CSEMap.InsertNode(N, IP);
8367 InsertNode(N);
8368
8369 SDValue V(N, 0);
8370 NewSDValueDbgMsg(V, "Creating new node: ", this);
8371 return V;
8372}
8373
8374SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8375 SDValue N1, SDValue N2) {
8376 SDNodeFlags Flags;
8377 if (Inserter)
8378 Flags = Inserter->getFlags();
8379 return getNode(Opcode, DL, VT, N1, N2, Flags);
8380}
8381
8383 SDValue &N2) const {
8384 if (!TLI->isCommutativeBinOp(Opcode))
8385 return;
8386
8387 // Canonicalize:
8388 // binop(const, nonconst) -> binop(nonconst, const)
8391 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8392 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8393 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8394 std::swap(N1, N2);
8395
8396 // Canonicalize:
8397 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8398 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8400 std::swap(N1, N2);
8401}
8402
8403SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8404 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8406 N2.getOpcode() != ISD::DELETED_NODE &&
8407 "Operand is DELETED_NODE!");
8408
8409 canonicalizeCommutativeBinop(Opcode, N1, N2);
8410
8411 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8412 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8413
8414 // Don't allow undefs in vector splats - we might be returning N2 when folding
8415 // to zero etc.
8416 ConstantSDNode *N2CV =
8417 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8418
8419 switch (Opcode) {
8420 default: break;
8421 case ISD::TokenFactor:
8422 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8423 N2.getValueType() == MVT::Other && "Invalid token factor!");
8424 // Fold trivial token factors.
8425 if (N1.getOpcode() == ISD::EntryToken) return N2;
8426 if (N2.getOpcode() == ISD::EntryToken) return N1;
8427 if (N1 == N2) return N1;
8428 break;
8429 case ISD::BUILD_VECTOR: {
8430 // Attempt to simplify BUILD_VECTOR.
8431 SDValue Ops[] = {N1, N2};
8432 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8433 return V;
8434 break;
8435 }
8436 case ISD::CONCAT_VECTORS: {
8437 SDValue Ops[] = {N1, N2};
8438 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8439 return V;
8440 break;
8441 }
8442 case ISD::AND:
8443 assert(VT.isInteger() && "This operator does not apply to FP types!");
8444 assert(N1.getValueType() == N2.getValueType() &&
8445 N1.getValueType() == VT && "Binary operator types must match!");
8446 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8447 // worth handling here.
8448 if (N2CV && N2CV->isZero())
8449 return N2;
8450 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8451 return N1;
8452 break;
8453 case ISD::OR:
8454 case ISD::XOR:
8455 case ISD::ADD:
8456 case ISD::PTRADD:
8457 case ISD::SUB:
8458 assert(VT.isInteger() && "This operator does not apply to FP types!");
8459 assert(N1.getValueType() == N2.getValueType() &&
8460 N1.getValueType() == VT && "Binary operator types must match!");
8461 // The equal operand types requirement is unnecessarily strong for PTRADD.
8462 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8463 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8464 // logic everywhere where PTRADDs may be folded or combined to properly
8465 // support them. If/when we introduce pointer types to the SDAG, we will
8466 // need to relax this constraint.
8467
8468 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8469 // it's worth handling here.
8470 if (N2CV && N2CV->isZero())
8471 return N1;
8472 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8473 VT.getScalarType() == MVT::i1)
8474 return getNode(ISD::XOR, DL, VT, N1, N2);
8475 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8476 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8477 N2.getOpcode() == ISD::VSCALE) {
8478 const APInt &C1 = N1->getConstantOperandAPInt(0);
8479 const APInt &C2 = N2->getConstantOperandAPInt(0);
8480 return getVScale(DL, VT, C1 + C2);
8481 }
8482 break;
8483 case ISD::MUL:
8484 assert(VT.isInteger() && "This operator does not apply to FP types!");
8485 assert(N1.getValueType() == N2.getValueType() &&
8486 N1.getValueType() == VT && "Binary operator types must match!");
8487 if (VT.getScalarType() == MVT::i1)
8488 return getNode(ISD::AND, DL, VT, N1, N2);
8489 if (N2CV && N2CV->isZero())
8490 return N2;
8491 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8492 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8493 const APInt &N2CImm = N2C->getAPIntValue();
8494 return getVScale(DL, VT, MulImm * N2CImm);
8495 }
8496 break;
8497 case ISD::UDIV:
8498 case ISD::UREM:
8499 case ISD::MULHU:
8500 case ISD::MULHS:
8501 case ISD::SDIV:
8502 case ISD::SREM:
8503 case ISD::SADDSAT:
8504 case ISD::SSUBSAT:
8505 case ISD::UADDSAT:
8506 case ISD::USUBSAT:
8507 assert(VT.isInteger() && "This operator does not apply to FP types!");
8508 assert(N1.getValueType() == N2.getValueType() &&
8509 N1.getValueType() == VT && "Binary operator types must match!");
8510 if (VT.getScalarType() == MVT::i1) {
8511 // fold (add_sat x, y) -> (or x, y) for bool types.
8512 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8513 return getNode(ISD::OR, DL, VT, N1, N2);
8514 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8515 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8516 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8517 }
8518 break;
8519 case ISD::SCMP:
8520 case ISD::UCMP:
8521 assert(N1.getValueType() == N2.getValueType() &&
8522 "Types of operands of UCMP/SCMP must match");
8523 assert(N1.getValueType().isVector() == VT.isVector() &&
8524 "Operands and return type of must both be scalars or vectors");
8525 if (VT.isVector())
8528 "Result and operands must have the same number of elements");
8529 break;
8530 case ISD::AVGFLOORS:
8531 case ISD::AVGFLOORU:
8532 case ISD::AVGCEILS:
8533 case ISD::AVGCEILU:
8534 assert(VT.isInteger() && "This operator does not apply to FP types!");
8535 assert(N1.getValueType() == N2.getValueType() &&
8536 N1.getValueType() == VT && "Binary operator types must match!");
8537 break;
8538 case ISD::ABDS:
8539 case ISD::ABDU:
8540 assert(VT.isInteger() && "This operator does not apply to FP types!");
8541 assert(N1.getValueType() == N2.getValueType() &&
8542 N1.getValueType() == VT && "Binary operator types must match!");
8543 if (VT.getScalarType() == MVT::i1)
8544 return getNode(ISD::XOR, DL, VT, N1, N2);
8545 break;
8546 case ISD::SMIN:
8547 case ISD::UMAX:
8548 assert(VT.isInteger() && "This operator does not apply to FP types!");
8549 assert(N1.getValueType() == N2.getValueType() &&
8550 N1.getValueType() == VT && "Binary operator types must match!");
8551 if (VT.getScalarType() == MVT::i1)
8552 return getNode(ISD::OR, DL, VT, N1, N2);
8553 break;
8554 case ISD::SMAX:
8555 case ISD::UMIN:
8556 assert(VT.isInteger() && "This operator does not apply to FP types!");
8557 assert(N1.getValueType() == N2.getValueType() &&
8558 N1.getValueType() == VT && "Binary operator types must match!");
8559 if (VT.getScalarType() == MVT::i1)
8560 return getNode(ISD::AND, DL, VT, N1, N2);
8561 break;
8562 case ISD::FADD:
8563 case ISD::FSUB:
8564 case ISD::FMUL:
8565 case ISD::FDIV:
8566 case ISD::FREM:
8567 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8568 assert(N1.getValueType() == N2.getValueType() &&
8569 N1.getValueType() == VT && "Binary operator types must match!");
8570 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8571 return V;
8572 break;
8573 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8574 assert(N1.getValueType() == VT &&
8577 "Invalid FCOPYSIGN!");
8578 break;
8579 case ISD::SHL:
8580 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8581 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8582 const APInt &ShiftImm = N2C->getAPIntValue();
8583 return getVScale(DL, VT, MulImm << ShiftImm);
8584 }
8585 [[fallthrough]];
8586 case ISD::SRA:
8587 case ISD::SRL:
8588 if (SDValue V = simplifyShift(N1, N2))
8589 return V;
8590 [[fallthrough]];
8591 case ISD::ROTL:
8592 case ISD::ROTR:
8593 case ISD::SSHLSAT:
8594 case ISD::USHLSAT:
8595 assert(VT == N1.getValueType() &&
8596 "Shift operators return type must be the same as their first arg");
8597 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8598 "Shifts only work on integers");
8599 assert((!VT.isVector() || VT == N2.getValueType()) &&
8600 "Vector shift amounts must be in the same as their first arg");
8601 // Verify that the shift amount VT is big enough to hold valid shift
8602 // amounts. This catches things like trying to shift an i1024 value by an
8603 // i8, which is easy to fall into in generic code that uses
8604 // TLI.getShiftAmount().
8607 "Invalid use of small shift amount with oversized value!");
8608
8609 // Always fold shifts of i1 values so the code generator doesn't need to
8610 // handle them. Since we know the size of the shift has to be less than the
8611 // size of the value, the shift/rotate count is guaranteed to be zero.
8612 if (VT == MVT::i1)
8613 return N1;
8614 if (N2CV && N2CV->isZero())
8615 return N1;
8616 break;
8617 case ISD::FP_ROUND:
8619 VT.bitsLE(N1.getValueType()) && N2C &&
8620 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8621 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8622 if (N1.getValueType() == VT) return N1; // noop conversion.
8623 break;
8624 case ISD::IS_FPCLASS: {
8626 "IS_FPCLASS is used for a non-floating type");
8627 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8628 // is.fpclass(poison, mask) -> poison
8629 if (N1.getOpcode() == ISD::POISON)
8630 return getPOISON(VT);
8631 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8632 // If all tests are made, it doesn't matter what the value is.
8633 if ((Mask & fcAllFlags) == fcAllFlags)
8634 return getBoolConstant(true, DL, VT, N1.getValueType());
8635 if ((Mask & fcAllFlags) == 0)
8636 return getBoolConstant(false, DL, VT, N1.getValueType());
8637 break;
8638 }
8639 case ISD::AssertNoFPClass: {
8641 "AssertNoFPClass is used for a non-floating type");
8642 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8643 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8644 assert(llvm::to_underlying(NoFPClass) <=
8646 "FPClassTest value too large");
8647 (void)NoFPClass;
8648 break;
8649 }
8650 case ISD::AssertSext:
8651 case ISD::AssertZext: {
8652 EVT EVT = cast<VTSDNode>(N2)->getVT();
8653 assert(VT == N1.getValueType() && "Not an inreg extend!");
8654 assert(VT.isInteger() && EVT.isInteger() &&
8655 "Cannot *_EXTEND_INREG FP types");
8656 assert(!EVT.isVector() &&
8657 "AssertSExt/AssertZExt type should be the vector element type "
8658 "rather than the vector type!");
8659 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8660 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8661 break;
8662 }
8664 EVT EVT = cast<VTSDNode>(N2)->getVT();
8665 assert(VT == N1.getValueType() && "Not an inreg extend!");
8666 assert(VT.isInteger() && EVT.isInteger() &&
8667 "Cannot *_EXTEND_INREG FP types");
8668 assert(EVT.isVector() == VT.isVector() &&
8669 "SIGN_EXTEND_INREG type should be vector iff the operand "
8670 "type is vector!");
8671 assert((!EVT.isVector() ||
8673 "Vector element counts must match in SIGN_EXTEND_INREG");
8674 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8675 if (EVT == VT) return N1; // Not actually extending
8676 break;
8677 }
8679 case ISD::FP_TO_UINT_SAT: {
8680 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8681 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8682 assert(N1.getValueType().isVector() == VT.isVector() &&
8683 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8684 "vector!");
8685 assert((!VT.isVector() || VT.getVectorElementCount() ==
8687 "Vector element counts must match in FP_TO_*INT_SAT");
8688 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8689 "Type to saturate to must be a scalar.");
8690 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8691 "Not extending!");
8692 break;
8693 }
8696 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8697 element type of the vector.");
8698
8699 // Extract from an undefined value or using an undefined index is undefined.
8700 if (N1.isUndef() || N2.isUndef())
8701 return getUNDEF(VT);
8702
8703 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8704 // vectors. For scalable vectors we will provide appropriate support for
8705 // dealing with arbitrary indices.
8706 if (N2C && N1.getValueType().isFixedLengthVector() &&
8707 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8708 return getPOISON(VT);
8709
8710 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8711 // expanding copies of large vectors from registers. This only works for
8712 // fixed length vectors, since we need to know the exact number of
8713 // elements.
8714 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8716 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8717 return getExtractVectorElt(DL, VT,
8718 N1.getOperand(N2C->getZExtValue() / Factor),
8719 N2C->getZExtValue() % Factor);
8720 }
8721
8722 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8723 // lowering is expanding large vector constants.
8724 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8725 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8728 "BUILD_VECTOR used for scalable vectors");
8729 unsigned Index =
8730 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8731 SDValue Elt = N1.getOperand(Index);
8732
8733 if (VT != Elt.getValueType())
8734 // If the vector element type is not legal, the BUILD_VECTOR operands
8735 // are promoted and implicitly truncated, and the result implicitly
8736 // extended. Make that explicit here.
8737 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8738
8739 return Elt;
8740 }
8741
8742 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8743 // operations are lowered to scalars.
8744 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8745 // If the indices are the same, return the inserted element else
8746 // if the indices are known different, extract the element from
8747 // the original vector.
8748 SDValue N1Op2 = N1.getOperand(2);
8750
8751 if (N1Op2C && N2C) {
8752 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8753 if (VT == N1.getOperand(1).getValueType())
8754 return N1.getOperand(1);
8755 if (VT.isFloatingPoint()) {
8757 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8758 }
8759 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8760 }
8761 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8762 }
8763 }
8764
8765 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8766 // when vector types are scalarized and v1iX is legal.
8767 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8768 // Here we are completely ignoring the extract element index (N2),
8769 // which is fine for fixed width vectors, since any index other than 0
8770 // is undefined anyway. However, this cannot be ignored for scalable
8771 // vectors - in theory we could support this, but we don't want to do this
8772 // without a profitability check.
8773 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8775 N1.getValueType().getVectorNumElements() == 1) {
8776 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8777 N1.getOperand(1));
8778 }
8779 break;
8781 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8782 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8783 (N1.getValueType().isInteger() == VT.isInteger()) &&
8784 N1.getValueType() != VT &&
8785 "Wrong types for EXTRACT_ELEMENT!");
8786
8787 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8788 // 64-bit integers into 32-bit parts. Instead of building the extract of
8789 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8790 if (N1.getOpcode() == ISD::BUILD_PAIR)
8791 return N1.getOperand(N2C->getZExtValue());
8792
8793 // EXTRACT_ELEMENT of a constant int is also very common.
8794 if (N1C) {
8795 unsigned ElementSize = VT.getSizeInBits();
8796 unsigned Shift = ElementSize * N2C->getZExtValue();
8797 const APInt &Val = N1C->getAPIntValue();
8798 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8799 }
8800 break;
8802 EVT N1VT = N1.getValueType();
8803 assert(VT.isVector() && N1VT.isVector() &&
8804 "Extract subvector VTs must be vectors!");
8806 "Extract subvector VTs must have the same element type!");
8807 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8808 "Cannot extract a scalable vector from a fixed length vector!");
8809 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8811 "Extract subvector must be from larger vector to smaller vector!");
8812 assert(N2C && "Extract subvector index must be a constant");
8813 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8814 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8815 N1VT.getVectorMinNumElements()) &&
8816 "Extract subvector overflow!");
8817 assert(N2C->getAPIntValue().getBitWidth() ==
8818 TLI->getVectorIdxWidth(getDataLayout()) &&
8819 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8820 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8821 "Extract index is not a multiple of the output vector length");
8822
8823 // Trivial extraction.
8824 if (VT == N1VT)
8825 return N1;
8826
8827 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8828 if (N1.isUndef())
8829 return getUNDEF(VT);
8830
8831 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8832 // the concat have the same type as the extract.
8833 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8834 VT == N1.getOperand(0).getValueType()) {
8835 unsigned Factor = VT.getVectorMinNumElements();
8836 return N1.getOperand(N2C->getZExtValue() / Factor);
8837 }
8838
8839 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8840 // during shuffle legalization.
8841 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8842 VT == N1.getOperand(1).getValueType())
8843 return N1.getOperand(1);
8844 break;
8845 }
8846 }
8847
8848 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8849 switch (Opcode) {
8850 case ISD::XOR:
8851 case ISD::ADD:
8852 case ISD::PTRADD:
8853 case ISD::SUB:
8855 case ISD::UDIV:
8856 case ISD::SDIV:
8857 case ISD::UREM:
8858 case ISD::SREM:
8859 case ISD::MUL:
8860 case ISD::AND:
8861 case ISD::SSUBSAT:
8862 case ISD::USUBSAT:
8863 case ISD::UMIN:
8864 case ISD::OR:
8865 case ISD::SADDSAT:
8866 case ISD::UADDSAT:
8867 case ISD::UMAX:
8868 case ISD::SMAX:
8869 case ISD::SMIN:
8870 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8871 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8872 }
8873 }
8874
8875 // Canonicalize an UNDEF to the RHS, even over a constant.
8876 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8877 if (TLI->isCommutativeBinOp(Opcode)) {
8878 std::swap(N1, N2);
8879 } else {
8880 switch (Opcode) {
8881 case ISD::PTRADD:
8882 case ISD::SUB:
8883 // fold op(undef, non_undef_arg2) -> undef.
8884 return N1;
8886 case ISD::UDIV:
8887 case ISD::SDIV:
8888 case ISD::UREM:
8889 case ISD::SREM:
8890 case ISD::SSUBSAT:
8891 case ISD::USUBSAT:
8892 // fold op(undef, non_undef_arg2) -> 0.
8893 return getConstant(0, DL, VT);
8894 }
8895 }
8896 }
8897
8898 // Fold a bunch of operators when the RHS is undef.
8899 if (N2.getOpcode() == ISD::UNDEF) {
8900 switch (Opcode) {
8901 case ISD::XOR:
8902 if (N1.getOpcode() == ISD::UNDEF)
8903 // Handle undef ^ undef -> 0 special case. This is a common
8904 // idiom (misuse).
8905 return getConstant(0, DL, VT);
8906 [[fallthrough]];
8907 case ISD::ADD:
8908 case ISD::PTRADD:
8909 case ISD::SUB:
8910 // fold op(arg1, undef) -> undef.
8911 return N2;
8912 case ISD::UDIV:
8913 case ISD::SDIV:
8914 case ISD::UREM:
8915 case ISD::SREM:
8916 // fold op(arg1, undef) -> poison.
8917 return getPOISON(VT);
8918 case ISD::MUL:
8919 case ISD::AND:
8920 case ISD::SSUBSAT:
8921 case ISD::USUBSAT:
8922 case ISD::UMIN:
8923 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8924 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8925 case ISD::OR:
8926 case ISD::SADDSAT:
8927 case ISD::UADDSAT:
8928 case ISD::UMAX:
8929 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8930 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8931 case ISD::SMAX:
8932 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8933 return N1.getOpcode() == ISD::UNDEF
8934 ? N2
8935 : getConstant(
8937 VT);
8938 case ISD::SMIN:
8939 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8940 return N1.getOpcode() == ISD::UNDEF
8941 ? N2
8942 : getConstant(
8944 VT);
8945 }
8946 }
8947
8948 // Perform trivial constant folding.
8949 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
8950 return SV;
8951
8952 // Memoize this node if possible.
8953 SDNode *N;
8954 SDVTList VTs = getVTList(VT);
8955 SDValue Ops[] = {N1, N2};
8956 if (VT != MVT::Glue) {
8958 AddNodeIDNode(ID, Opcode, VTs, Ops);
8959 void *IP = nullptr;
8960 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8961 E->intersectFlagsWith(Flags);
8962 return SDValue(E, 0);
8963 }
8964
8965 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8966 N->setFlags(Flags);
8967 createOperands(N, Ops);
8968 CSEMap.InsertNode(N, IP);
8969 } else {
8970 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8971 createOperands(N, Ops);
8972 }
8973
8974 InsertNode(N);
8975 SDValue V = SDValue(N, 0);
8976 NewSDValueDbgMsg(V, "Creating new node: ", this);
8977 return V;
8978}
8979
8980SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8981 SDValue N1, SDValue N2, SDValue N3) {
8982 SDNodeFlags Flags;
8983 if (Inserter)
8984 Flags = Inserter->getFlags();
8985 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
8986}
8987
8988SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8989 SDValue N1, SDValue N2, SDValue N3,
8990 const SDNodeFlags Flags) {
8992 N2.getOpcode() != ISD::DELETED_NODE &&
8993 N3.getOpcode() != ISD::DELETED_NODE &&
8994 "Operand is DELETED_NODE!");
8995 // Perform various simplifications.
8996 switch (Opcode) {
8997 case ISD::BUILD_VECTOR: {
8998 // Attempt to simplify BUILD_VECTOR.
8999 SDValue Ops[] = {N1, N2, N3};
9000 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9001 return V;
9002 break;
9003 }
9004 case ISD::CONCAT_VECTORS: {
9005 SDValue Ops[] = {N1, N2, N3};
9006 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9007 return V;
9008 break;
9009 }
9010 case ISD::SETCC: {
9011 assert(VT.isInteger() && "SETCC result type must be an integer!");
9012 assert(N1.getValueType() == N2.getValueType() &&
9013 "SETCC operands must have the same type!");
9014 assert(VT.isVector() == N1.getValueType().isVector() &&
9015 "SETCC type should be vector iff the operand type is vector!");
9016 assert((!VT.isVector() || VT.getVectorElementCount() ==
9018 "SETCC vector element counts must match!");
9019 // Use FoldSetCC to simplify SETCC's.
9020 if (SDValue V =
9021 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9022 return V;
9023 break;
9024 }
9025 case ISD::SELECT:
9026 case ISD::VSELECT:
9027 if (SDValue V = simplifySelect(N1, N2, N3))
9028 return V;
9029 break;
9031 llvm_unreachable("should use getVectorShuffle constructor!");
9033 if (isNullConstant(N3))
9034 return N1;
9035 break;
9037 if (isNullConstant(N3))
9038 return N2;
9039 break;
9041 assert(VT.isVector() && VT == N1.getValueType() &&
9042 "INSERT_VECTOR_ELT vector type mismatch");
9044 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9045 assert((!VT.isFloatingPoint() ||
9046 VT.getVectorElementType() == N2.getValueType()) &&
9047 "INSERT_VECTOR_ELT fp scalar type mismatch");
9048 assert((!VT.isInteger() ||
9050 "INSERT_VECTOR_ELT int scalar size mismatch");
9051
9052 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9053 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9054 // for scalable vectors where we will generate appropriate code to
9055 // deal with out-of-bounds cases correctly.
9056 if (N3C && VT.isFixedLengthVector() &&
9057 N3C->getZExtValue() >= VT.getVectorNumElements())
9058 return getUNDEF(VT);
9059
9060 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9061 if (N3.isUndef())
9062 return getUNDEF(VT);
9063
9064 // If inserting poison, just use the input vector.
9065 if (N2.getOpcode() == ISD::POISON)
9066 return N1;
9067
9068 // Inserting undef into undef/poison is still undef.
9069 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9070 return getUNDEF(VT);
9071
9072 // If the inserted element is an UNDEF, just use the input vector.
9073 // But not if skipping the insert could make the result more poisonous.
9074 if (N2.isUndef()) {
9075 if (N3C && VT.isFixedLengthVector()) {
9076 APInt EltMask =
9077 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9078 if (isGuaranteedNotToBePoison(N1, EltMask))
9079 return N1;
9080 } else if (isGuaranteedNotToBePoison(N1))
9081 return N1;
9082 }
9083 break;
9084 }
9085 case ISD::INSERT_SUBVECTOR: {
9086 // If inserting poison, just use the input vector,
9087 if (N2.getOpcode() == ISD::POISON)
9088 return N1;
9089
9090 // Inserting undef into undef/poison is still undef.
9091 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9092 return getUNDEF(VT);
9093
9094 EVT N2VT = N2.getValueType();
9095 assert(VT == N1.getValueType() &&
9096 "Dest and insert subvector source types must match!");
9097 assert(VT.isVector() && N2VT.isVector() &&
9098 "Insert subvector VTs must be vectors!");
9100 "Insert subvector VTs must have the same element type!");
9101 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9102 "Cannot insert a scalable vector into a fixed length vector!");
9103 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9105 "Insert subvector must be from smaller vector to larger vector!");
9107 "Insert subvector index must be constant");
9108 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9109 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9111 "Insert subvector overflow!");
9113 TLI->getVectorIdxWidth(getDataLayout()) &&
9114 "Constant index for INSERT_SUBVECTOR has an invalid size");
9115
9116 // Trivial insertion.
9117 if (VT == N2VT)
9118 return N2;
9119
9120 // If this is an insert of an extracted vector into an undef/poison vector,
9121 // we can just use the input to the extract. But not if skipping the
9122 // extract+insert could make the result more poisonous.
9123 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9124 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9125 if (N1.getOpcode() == ISD::POISON)
9126 return N2.getOperand(0);
9127 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9128 unsigned LoBit = N3->getAsZExtVal();
9129 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9130 APInt EltMask =
9131 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9132 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9133 return N2.getOperand(0);
9134 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9135 return N2.getOperand(0);
9136 }
9137
9138 // If the inserted subvector is UNDEF, just use the input vector.
9139 // But not if skipping the insert could make the result more poisonous.
9140 if (N2.isUndef()) {
9141 if (VT.isFixedLengthVector()) {
9142 unsigned LoBit = N3->getAsZExtVal();
9143 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9144 APInt EltMask =
9145 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9146 if (isGuaranteedNotToBePoison(N1, EltMask))
9147 return N1;
9148 } else if (isGuaranteedNotToBePoison(N1))
9149 return N1;
9150 }
9151 break;
9152 }
9153 case ISD::BITCAST:
9154 // Fold bit_convert nodes from a type to themselves.
9155 if (N1.getValueType() == VT)
9156 return N1;
9157 break;
9158 case ISD::VECTOR_COMPRESS: {
9159 [[maybe_unused]] EVT VecVT = N1.getValueType();
9160 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9161 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9162 assert(VT == VecVT && "Vector and result type don't match.");
9163 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9164 "All inputs must be vectors.");
9165 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9167 "Vector and mask must have same number of elements.");
9168
9169 if (N1.isUndef() || N2.isUndef())
9170 return N3;
9171
9172 break;
9173 }
9178 [[maybe_unused]] EVT AccVT = N1.getValueType();
9179 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9180 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9181 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9182 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9183 "node to have the same type!");
9184 assert(VT.isVector() && VT == AccVT &&
9185 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9186 "the same type as its result!");
9188 AccVT.getVectorElementCount()) &&
9189 "Expected the element count of the second and third operands of the "
9190 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9191 "element count of the first operand and the result!");
9193 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9194 "node to have an element type which is the same as or smaller than "
9195 "the element type of the first operand and result!");
9196 break;
9197 }
9198 }
9199
9200 // Perform trivial constant folding for arithmetic operators.
9201 switch (Opcode) {
9205 case ISD::FMA:
9206 case ISD::FMAD:
9207 case ISD::SETCC:
9208 case ISD::FSHL:
9209 case ISD::FSHR:
9210 if (SDValue SV =
9211 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9212 return SV;
9213 break;
9214 }
9215
9216 // Memoize node if it doesn't produce a glue result.
9217 SDNode *N;
9218 SDVTList VTs = getVTList(VT);
9219 SDValue Ops[] = {N1, N2, N3};
9220 if (VT != MVT::Glue) {
9222 AddNodeIDNode(ID, Opcode, VTs, Ops);
9223 void *IP = nullptr;
9224 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9225 E->intersectFlagsWith(Flags);
9226 return SDValue(E, 0);
9227 }
9228
9229 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9230 N->setFlags(Flags);
9231 createOperands(N, Ops);
9232 CSEMap.InsertNode(N, IP);
9233 } else {
9234 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9235 createOperands(N, Ops);
9236 }
9237
9238 InsertNode(N);
9239 SDValue V = SDValue(N, 0);
9240 NewSDValueDbgMsg(V, "Creating new node: ", this);
9241 return V;
9242}
9243
9244SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9245 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9246 const SDNodeFlags Flags) {
9247 SDValue Ops[] = { N1, N2, N3, N4 };
9248 return getNode(Opcode, DL, VT, Ops, Flags);
9249}
9250
9251SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9252 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9253 SDNodeFlags Flags;
9254 if (Inserter)
9255 Flags = Inserter->getFlags();
9256 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9257}
9258
9259SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9260 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9261 SDValue N5, const SDNodeFlags Flags) {
9262 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9263 return getNode(Opcode, DL, VT, Ops, Flags);
9264}
9265
9266SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9267 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9268 SDValue N5) {
9269 SDNodeFlags Flags;
9270 if (Inserter)
9271 Flags = Inserter->getFlags();
9272 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9273}
9274
9275/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9276/// the incoming stack arguments to be loaded from the stack.
9278 SmallVector<SDValue, 8> ArgChains;
9279
9280 // Include the original chain at the beginning of the list. When this is
9281 // used by target LowerCall hooks, this helps legalize find the
9282 // CALLSEQ_BEGIN node.
9283 ArgChains.push_back(Chain);
9284
9285 // Add a chain value for each stack argument.
9286 for (SDNode *U : getEntryNode().getNode()->users())
9287 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9288 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9289 if (FI->getIndex() < 0)
9290 ArgChains.push_back(SDValue(L, 1));
9291
9292 // Build a tokenfactor for all the chains.
9293 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9294}
9295
9296/// getMemsetValue - Vectorized representation of the memset value
9297/// operand.
9299 const SDLoc &dl) {
9300 assert(!Value.isUndef());
9301
9302 unsigned NumBits = VT.getScalarSizeInBits();
9304 assert(C->getAPIntValue().getBitWidth() == 8);
9305 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9306 if (VT.isInteger()) {
9307 bool IsOpaque = VT.getSizeInBits() > 64 ||
9308 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9309 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9310 }
9311 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9312 }
9313
9314 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9315 EVT IntVT = VT.getScalarType();
9316 if (!IntVT.isInteger())
9317 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9318
9319 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9320 if (NumBits > 8) {
9321 // Use a multiplication with 0x010101... to extend the input to the
9322 // required length.
9323 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9324 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9325 DAG.getConstant(Magic, dl, IntVT));
9326 }
9327
9328 if (VT != Value.getValueType() && !VT.isInteger())
9329 Value = DAG.getBitcast(VT.getScalarType(), Value);
9330 if (VT != Value.getValueType())
9331 Value = DAG.getSplatBuildVector(VT, dl, Value);
9332
9333 return Value;
9334}
9335
9336/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9337/// used when a memcpy is turned into a memset when the source is a constant
9338/// string ptr.
9340 const TargetLowering &TLI,
9341 const ConstantDataArraySlice &Slice) {
9342 // Handle vector with all elements zero.
9343 if (Slice.Array == nullptr) {
9344 if (VT.isInteger())
9345 return DAG.getConstant(0, dl, VT);
9346 return DAG.getNode(ISD::BITCAST, dl, VT,
9347 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9348 }
9349
9350 assert(!VT.isVector() && "Can't handle vector type here!");
9351 unsigned NumVTBits = VT.getSizeInBits();
9352 unsigned NumVTBytes = NumVTBits / 8;
9353 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9354
9355 APInt Val(NumVTBits, 0);
9356 if (DAG.getDataLayout().isLittleEndian()) {
9357 for (unsigned i = 0; i != NumBytes; ++i)
9358 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9359 } else {
9360 for (unsigned i = 0; i != NumBytes; ++i)
9361 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9362 }
9363
9364 // If the "cost" of materializing the integer immediate is less than the cost
9365 // of a load, then it is cost effective to turn the load into the immediate.
9366 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9367 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9368 return DAG.getConstant(Val, dl, VT);
9369 return SDValue();
9370}
9371
9373 const SDLoc &DL,
9374 const SDNodeFlags Flags) {
9375 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9376 return getMemBasePlusOffset(Base, Index, DL, Flags);
9377}
9378
9380 const SDLoc &DL,
9381 const SDNodeFlags Flags) {
9382 assert(Offset.getValueType().isInteger());
9383 EVT BasePtrVT = Ptr.getValueType();
9384 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9385 BasePtrVT))
9386 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9387 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9388 SDNodeFlags AddFlags = Flags;
9389 AddFlags.setInBounds(false);
9390 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9391}
9392
9393/// Returns true if memcpy source is constant data.
9395 uint64_t SrcDelta = 0;
9396 GlobalAddressSDNode *G = nullptr;
9397 if (Src.getOpcode() == ISD::GlobalAddress)
9399 else if (Src->isAnyAdd() &&
9400 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9401 Src.getOperand(1).getOpcode() == ISD::Constant) {
9402 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9403 SrcDelta = Src.getConstantOperandVal(1);
9404 }
9405 if (!G)
9406 return false;
9407
9408 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9409 SrcDelta + G->getOffset());
9410}
9411
9413 SelectionDAG &DAG) {
9414 // On Darwin, -Os means optimize for size without hurting performance, so
9415 // only really optimize for size when -Oz (MinSize) is used.
9417 return MF.getFunction().hasMinSize();
9418 return DAG.shouldOptForSize();
9419}
9420
9422 SmallVector<SDValue, 32> &OutChains, unsigned From,
9423 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9424 SmallVector<SDValue, 16> &OutStoreChains) {
9425 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9426 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9427 SmallVector<SDValue, 16> GluedLoadChains;
9428 for (unsigned i = From; i < To; ++i) {
9429 OutChains.push_back(OutLoadChains[i]);
9430 GluedLoadChains.push_back(OutLoadChains[i]);
9431 }
9432
9433 // Chain for all loads.
9434 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9435 GluedLoadChains);
9436
9437 for (unsigned i = From; i < To; ++i) {
9438 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9439 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9440 ST->getBasePtr(), ST->getMemoryVT(),
9441 ST->getMemOperand());
9442 OutChains.push_back(NewStore);
9443 }
9444}
9445
9446static SDValue
9448 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9449 Align SrcAlign, bool isVol, bool AlwaysInline,
9450 MachinePointerInfo DstPtrInfo,
9451 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9452 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9453 const MDNode *SrcMemCacheHint) {
9454 // Turn a memcpy of undef to nop.
9455 // FIXME: We need to honor volatile even is Src is undef.
9456 if (Src.isUndef())
9457 return Chain;
9458
9459 // Expand memcpy to a series of load and store ops if the size operand falls
9460 // below a certain threshold.
9461 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9462 // rather than maybe a humongous number of loads and stores.
9463 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9464 const DataLayout &DL = DAG.getDataLayout();
9465 LLVMContext &C = *DAG.getContext();
9466 std::vector<EVT> MemOps;
9467 bool DstAlignCanChange = false;
9469 MachineFrameInfo &MFI = MF.getFrameInfo();
9470 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9472 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9473 DstAlignCanChange = true;
9474 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9476 // If marked as volatile, perform a copy even when marked as constant.
9477 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9478 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9479 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9480 const MemOp Op = isZeroConstant
9481 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9482 /*IsZeroMemset*/ true, isVol)
9483 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9484 SrcAlign, isVol, CopyFromConstant);
9485 if (!TLI.findOptimalMemOpLowering(
9486 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9487 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9488 return SDValue();
9489
9490 if (DstAlignCanChange) {
9491 Type *Ty = MemOps[0].getTypeForEVT(C);
9492 Align NewDstAlign = DL.getABITypeAlign(Ty);
9493
9494 // Don't promote to an alignment that would require dynamic stack
9495 // realignment which may conflict with optimizations such as tail call
9496 // optimization.
9498 if (!TRI->hasStackRealignment(MF))
9499 if (MaybeAlign StackAlign = DL.getStackAlignment())
9500 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9501
9502 if (NewDstAlign > DstAlign) {
9503 // Give the stack frame object a larger alignment if needed.
9504 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9505 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9506 DstAlign = NewDstAlign;
9507 }
9508 }
9509
9510 // Prepare AAInfo for loads/stores after lowering this memcpy.
9511 AAMDNodes NewAAInfo = AAInfo;
9512 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9513
9514 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9515 bool isConstant =
9516 BatchAA && SrcVal &&
9517 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9518
9519 MachineMemOperand::Flags MMOFlags =
9521 SmallVector<SDValue, 16> OutLoadChains;
9522 SmallVector<SDValue, 16> OutStoreChains;
9523 SmallVector<SDValue, 32> OutChains;
9524 unsigned NumMemOps = MemOps.size();
9525 uint64_t SrcOff = 0, DstOff = 0;
9526 for (unsigned i = 0; i != NumMemOps; ++i) {
9527 EVT VT = MemOps[i];
9528 unsigned VTSize = VT.getSizeInBits() / 8;
9530
9531 if (VTSize > Size) {
9532 // Issuing an unaligned load / store pair that overlaps with the previous
9533 // pair. Adjust the offset accordingly.
9534 assert(i == NumMemOps-1 && i != 0);
9535 SrcOff -= VTSize - Size;
9536 DstOff -= VTSize - Size;
9537 }
9538
9539 if (CopyFromConstant &&
9540 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9541 // It's unlikely a store of a vector immediate can be done in a single
9542 // instruction. It would require a load from a constantpool first.
9543 // We only handle zero vectors here.
9544 // FIXME: Handle other cases where store of vector immediate is done in
9545 // a single instruction.
9546 ConstantDataArraySlice SubSlice;
9547 if (SrcOff < Slice.Length) {
9548 SubSlice = Slice;
9549 SubSlice.move(SrcOff);
9550 } else {
9551 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9552 SubSlice.Array = nullptr;
9553 SubSlice.Offset = 0;
9554 SubSlice.Length = VTSize;
9555 }
9556 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9557 if (Value.getNode()) {
9558 Store = DAG.getStore(
9559 Chain, dl, Value,
9560 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9561 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9562 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9563 OutChains.push_back(Store);
9564 }
9565 }
9566
9567 if (!Store.getNode()) {
9568 // The type might not be legal for the target. This should only happen
9569 // if the type is smaller than a legal type, as on PPC, so the right
9570 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9571 // to Load/Store if NVT==VT.
9572 // FIXME does the case above also need this?
9573 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9574 assert(NVT.bitsGE(VT));
9575
9576 bool isDereferenceable =
9577 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9578 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9579 if (isDereferenceable)
9581 if (isConstant)
9582 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9583
9584 Value = DAG.getExtLoad(
9585 ISD::EXTLOAD, dl, NVT, Chain,
9586 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9587 SrcPtrInfo.getWithOffset(SrcOff), VT,
9588 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9589 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9590 OutLoadChains.push_back(Value.getValue(1));
9591
9592 Store = DAG.getTruncStore(
9593 Chain, dl, Value,
9594 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9595 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9596 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9597 OutStoreChains.push_back(Store);
9598 }
9599 SrcOff += VTSize;
9600 DstOff += VTSize;
9601 Size -= VTSize;
9602 }
9603
9604 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9606 unsigned NumLdStInMemcpy = OutStoreChains.size();
9607
9608 if (NumLdStInMemcpy) {
9609 // It may be that memcpy might be converted to memset if it's memcpy
9610 // of constants. In such a case, we won't have loads and stores, but
9611 // just stores. In the absence of loads, there is nothing to gang up.
9612 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9613 // If target does not care, just leave as it.
9614 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9615 OutChains.push_back(OutLoadChains[i]);
9616 OutChains.push_back(OutStoreChains[i]);
9617 }
9618 } else {
9619 // Ld/St less than/equal limit set by target.
9620 if (NumLdStInMemcpy <= GluedLdStLimit) {
9621 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9622 NumLdStInMemcpy, OutLoadChains,
9623 OutStoreChains);
9624 } else {
9625 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9626 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9627 unsigned GlueIter = 0;
9628
9629 // Residual ld/st.
9630 if (RemainingLdStInMemcpy) {
9632 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9633 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9634 }
9635
9636 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9637 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9638 GlueIter - GluedLdStLimit;
9639 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9640 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9641 OutLoadChains, OutStoreChains);
9642 GlueIter += GluedLdStLimit;
9643 }
9644 }
9645 }
9646 }
9647 return DAG.getTokenFactor(dl, OutChains);
9648}
9649
9651 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9652 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9653 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9654 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9655 // Turn a memmove of undef to nop.
9656 // FIXME: We need to honor volatile even is Src is undef.
9657 if (Src.isUndef())
9658 return Chain;
9659
9660 // Expand memmove to a series of load and store ops if the size operand falls
9661 // below a certain threshold.
9662 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9663 const DataLayout &DL = DAG.getDataLayout();
9664 LLVMContext &C = *DAG.getContext();
9665 std::vector<EVT> MemOps;
9666 bool DstAlignCanChange = false;
9668 MachineFrameInfo &MFI = MF.getFrameInfo();
9669 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9671 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9672 DstAlignCanChange = true;
9673 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9674 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9675 if (!TLI.findOptimalMemOpLowering(
9676 C, MemOps, Limit,
9677 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9678 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9679 MF.getFunction().getAttributes(), nullptr))
9680 return SDValue();
9681
9682 if (DstAlignCanChange) {
9683 Type *Ty = MemOps[0].getTypeForEVT(C);
9684 Align NewDstAlign = DL.getABITypeAlign(Ty);
9685
9686 // Don't promote to an alignment that would require dynamic stack
9687 // realignment which may conflict with optimizations such as tail call
9688 // optimization.
9690 if (!TRI->hasStackRealignment(MF))
9691 if (MaybeAlign StackAlign = DL.getStackAlignment())
9692 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9693
9694 if (NewDstAlign > DstAlign) {
9695 // Give the stack frame object a larger alignment if needed.
9696 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9697 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9698 DstAlign = NewDstAlign;
9699 }
9700 }
9701
9702 // Prepare AAInfo for loads/stores after lowering this memmove.
9703 AAMDNodes NewAAInfo = AAInfo;
9704 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9705
9706 MachineMemOperand::Flags MMOFlags =
9708 uint64_t SrcOff = 0;
9709 SmallVector<SDValue, 8> LoadValues;
9710 SmallVector<SDValue, 8> LoadChains;
9711 SmallVector<SDValue, 8> OutChains;
9712 unsigned NumMemOps = MemOps.size();
9713 for (unsigned i = 0; i < NumMemOps; i++) {
9714 EVT VT = MemOps[i];
9715 unsigned VTSize = VT.getSizeInBits() / 8;
9716 SDValue Value;
9717 bool IsOverlapping = false;
9718
9719 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9720 // Issuing an unaligned load / store pair that overlaps with the previous
9721 // pair. Adjust the offset accordingly.
9722 SrcOff = Size - VTSize;
9723 IsOverlapping = true;
9724 }
9725
9726 // Calculate the actual alignment at the current offset. The alignment at
9727 // SrcOff may be lower than the base alignment, especially when using
9728 // overlapping loads.
9729 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9730 if (IsOverlapping) {
9731 // Verify that the target allows misaligned memory accesses at the
9732 // adjusted offset when using overlapping loads.
9733 unsigned Fast;
9734 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9735 SrcAlignAtOffset, MMOFlags,
9736 &Fast) ||
9737 !Fast) {
9738 // This should have been caught by findOptimalMemOpLowering, but verify
9739 // here for safety.
9740 return SDValue();
9741 }
9742 }
9743
9744 bool isDereferenceable =
9745 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9746 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9747 if (isDereferenceable)
9749 Value =
9750 DAG.getLoad(VT, dl, Chain,
9751 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9752 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9753 SrcMMOFlags, NewAAInfo);
9754 LoadValues.push_back(Value);
9755 LoadChains.push_back(Value.getValue(1));
9756 SrcOff += VTSize;
9757 }
9758 Chain = DAG.getTokenFactor(dl, LoadChains);
9759 OutChains.clear();
9760 uint64_t DstOff = 0;
9761 for (unsigned i = 0; i < NumMemOps; i++) {
9762 EVT VT = MemOps[i];
9763 unsigned VTSize = VT.getSizeInBits() / 8;
9764 SDValue Store;
9765 bool IsOverlapping = false;
9766
9767 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9768 // Issuing an unaligned load / store pair that overlaps with the previous
9769 // pair. Adjust the offset accordingly.
9770 DstOff = Size - VTSize;
9771 IsOverlapping = true;
9772 }
9773
9774 // Calculate the actual alignment at the current offset. The alignment at
9775 // DstOff may be lower than the base alignment, especially when using
9776 // overlapping stores.
9777 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9778 if (IsOverlapping) {
9779 // Verify that the target allows misaligned memory accesses at the
9780 // adjusted offset when using overlapping stores.
9781 unsigned Fast;
9782 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9783 DstAlignAtOffset, MMOFlags,
9784 &Fast) ||
9785 !Fast) {
9786 // This should have been caught by findOptimalMemOpLowering, but verify
9787 // here for safety.
9788 return SDValue();
9789 }
9790 }
9791 Store = DAG.getStore(
9792 Chain, dl, LoadValues[i],
9793 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9794 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9795 NewAAInfo);
9796 OutChains.push_back(Store);
9797 DstOff += VTSize;
9798 }
9799
9800 return DAG.getTokenFactor(dl, OutChains);
9801}
9802
9803/// Lower the call to 'memset' intrinsic function into a series of store
9804/// operations.
9805///
9806/// \param DAG Selection DAG where lowered code is placed.
9807/// \param dl Link to corresponding IR location.
9808/// \param Chain Control flow dependency.
9809/// \param Dst Pointer to destination memory location.
9810/// \param Src Value of byte to write into the memory.
9811/// \param Size Number of bytes to write.
9812/// \param Alignment Alignment of the destination in bytes.
9813/// \param isVol True if destination is volatile.
9814/// \param AlwaysInline Makes sure no function call is generated.
9815/// \param DstPtrInfo IR information on the memory pointer.
9816/// \returns New head in the control flow, if lowering was successful, empty
9817/// SDValue otherwise.
9818///
9819/// The function tries to replace 'llvm.memset' intrinsic with several store
9820/// operations and value calculation code. This is usually profitable for small
9821/// memory size or when the semantic requires inlining.
9823 SDValue Chain, SDValue Dst, SDValue Src,
9824 uint64_t Size, Align Alignment, bool isVol,
9825 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9826 const AAMDNodes &AAInfo) {
9827 // Turn a memset of undef to nop.
9828 // FIXME: We need to honor volatile even is Src is undef.
9829 if (Src.isUndef())
9830 return Chain;
9831
9832 // Expand memset to a series of load/store ops if the size operand
9833 // falls below a certain threshold.
9834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9835 std::vector<EVT> MemOps;
9836 bool DstAlignCanChange = false;
9837 LLVMContext &C = *DAG.getContext();
9839 MachineFrameInfo &MFI = MF.getFrameInfo();
9840 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9842 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9843 DstAlignCanChange = true;
9844 bool IsZeroVal = isNullConstant(Src);
9845 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9846
9847 EVT LargestVT;
9848 if (!TLI.findOptimalMemOpLowering(
9849 C, MemOps, Limit,
9850 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9851 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
9852 &LargestVT))
9853 return SDValue();
9854
9855 if (DstAlignCanChange) {
9856 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9857 const DataLayout &DL = DAG.getDataLayout();
9858 Align NewAlign = DL.getABITypeAlign(Ty);
9859
9860 // Don't promote to an alignment that would require dynamic stack
9861 // realignment which may conflict with optimizations such as tail call
9862 // optimization.
9864 if (!TRI->hasStackRealignment(MF))
9865 if (MaybeAlign StackAlign = DL.getStackAlignment())
9866 NewAlign = std::min(NewAlign, *StackAlign);
9867
9868 if (NewAlign > Alignment) {
9869 // Give the stack frame object a larger alignment if needed.
9870 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9871 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9872 Alignment = NewAlign;
9873 }
9874 }
9875
9876 SmallVector<SDValue, 8> OutChains;
9877 uint64_t DstOff = 0;
9878 unsigned NumMemOps = MemOps.size();
9879
9880 // Find the largest store and generate the bit pattern for it.
9881 // If target didn't set LargestVT, compute it from MemOps.
9882 if (!LargestVT.isSimple()) {
9883 LargestVT = MemOps[0];
9884 for (unsigned i = 1; i < NumMemOps; i++)
9885 if (MemOps[i].bitsGT(LargestVT))
9886 LargestVT = MemOps[i];
9887 }
9888 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9889
9890 // Prepare AAInfo for loads/stores after lowering this memset.
9891 AAMDNodes NewAAInfo = AAInfo;
9892 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9893
9894 for (unsigned i = 0; i < NumMemOps; i++) {
9895 EVT VT = MemOps[i];
9896 unsigned VTSize = VT.getSizeInBits() / 8;
9897 // The target should specify store types that exactly cover the memset size
9898 // (with the last store potentially being oversized for overlapping stores).
9899 assert(Size > 0 && "Target specified more stores than needed in "
9900 "findOptimalMemOpLowering");
9901 if (VTSize > Size) {
9902 // Issuing an unaligned load / store pair that overlaps with the previous
9903 // pair. Adjust the offset accordingly.
9904 assert(i == NumMemOps-1 && i != 0);
9905 DstOff -= VTSize - Size;
9906 }
9907
9908 // If this store is smaller than the largest store see whether we can get
9909 // the smaller value for free with a truncate or extract vector element and
9910 // then store.
9911 SDValue Value = MemSetValue;
9912 if (VT.bitsLT(LargestVT)) {
9913 unsigned Index;
9914 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9915 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9916 if (!LargestVT.isVector() && !VT.isVector() &&
9917 TLI.isTruncateFree(LargestVT, VT))
9918 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9919 else if (LargestVT.isVector() && !VT.isVector() &&
9921 LargestVT.getTypeForEVT(*DAG.getContext()),
9922 VT.getSizeInBits(), Index) &&
9923 TLI.isTypeLegal(SVT) &&
9924 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9925 // Target which can combine store(extractelement VectorTy, Idx) can get
9926 // the smaller value for free.
9927 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9928 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9929 } else
9930 Value = getMemsetValue(Src, VT, DAG, dl);
9931 }
9932 assert(Value.getValueType() == VT && "Value with wrong type.");
9933 SDValue Store = DAG.getStore(
9934 Chain, dl, Value,
9935 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9936 DstPtrInfo.getWithOffset(DstOff), Alignment,
9938 NewAAInfo);
9939 OutChains.push_back(Store);
9940 DstOff += VT.getSizeInBits() / 8;
9941 // For oversized overlapping stores, only subtract the remaining bytes.
9942 // For normal stores, subtract the full store size.
9943 if (VTSize > Size) {
9944 Size = 0;
9945 } else {
9946 Size -= VTSize;
9947 }
9948 }
9949
9950 // After processing all stores, Size should be exactly 0. Any remaining bytes
9951 // indicate a bug in the target's findOptimalMemOpLowering implementation.
9952 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
9953 "stores that exactly cover the memset size");
9954
9955 return DAG.getTokenFactor(dl, OutChains);
9956}
9957
9959 unsigned AS) {
9960 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
9961 // pointer operands can be losslessly bitcasted to pointers of address space 0
9962 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
9963 report_fatal_error("cannot lower memory intrinsic in address space " +
9964 Twine(AS));
9965 }
9966}
9967
9969 const SelectionDAG *SelDAG,
9970 bool AllowReturnsFirstArg) {
9971 if (!CI || !CI->isTailCall())
9972 return false;
9973 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
9974 // helper symbol we lower to.
9975 return isInTailCallPosition(*CI, SelDAG->getTarget(),
9976 AllowReturnsFirstArg &&
9978}
9979
9980static std::pair<SDValue, SDValue>
9983 const CallInst *CI, RTLIB::Libcall Call,
9984 SelectionDAG *DAG, const TargetLowering *TLI) {
9985 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
9986
9987 if (LCImpl == RTLIB::Unsupported)
9988 return {};
9989
9991 bool IsTailCall =
9992 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
9993 // Lowering doesn't support tail calling inside a function with
9994 // a swifterror argument yet.
9995 !DAG->hasSwiftErrorArg();
9996 SDValue Callee =
9997 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
9998
9999 CLI.setDebugLoc(dl)
10000 .setChain(Chain)
10002 CI->getType(), Callee, std::move(Args))
10003 .setTailCall(IsTailCall);
10004
10005 return TLI->LowerCallTo(CLI);
10006}
10007
10008std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10009 const SDLoc &dl, SDValue S1,
10010 SDValue S2,
10011 const CallInst *CI) {
10013 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10014 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10015 RTLIB::STRCMP, this, TLI);
10016}
10017
10018std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10019 const SDLoc &dl, SDValue S1,
10020 SDValue S2,
10021 const CallInst *CI) {
10023 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10024 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10025 RTLIB::STRSTR, this, TLI);
10026}
10027
10028std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10029 const SDLoc &dl,
10030 SDValue Dst, SDValue Src,
10032 const CallInst *CI) {
10034
10036 {Dst, PT},
10037 {Src, PT},
10040 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10041 RTLIB::MEMCCPY, this, TLI);
10042}
10043
10044std::pair<SDValue, SDValue>
10046 SDValue Mem1, SDValue Size, const CallInst *CI) {
10049 {Mem0, PT},
10050 {Mem1, PT},
10052 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10053 RTLIB::MEMCMP, this, TLI);
10054}
10055
10056std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10057 const SDLoc &dl,
10058 SDValue Dst, SDValue Src,
10059 const CallInst *CI) {
10061 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10062 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10063 RTLIB::STRCPY, this, TLI);
10064}
10065
10066std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10067 const SDLoc &dl,
10068 SDValue Src,
10069 const CallInst *CI) {
10070 // Emit a library call.
10073 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10074 RTLIB::STRLEN, this, TLI);
10075}
10076
10078 return TLI->supportSwiftError() &&
10079 MF->getFunction().getAttributes().hasAttrSomewhere(
10080 Attribute::SwiftError);
10081}
10082
10084 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10085 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10086 const CallInst *CI, std::optional<bool> OverrideTailCall,
10087 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10088 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10089 // Check to see if we should lower the memcpy to loads and stores first.
10090 // For cases within the target-specified limits, this is the best choice.
10091 const MDNode *DstMemCacheHint =
10092 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10093 const MDNode *SrcMemCacheHint =
10094 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10095
10097 if (ConstantSize) {
10098 // Memcpy with size zero? Just return the original chain.
10099 if (ConstantSize->isZero())
10100 return Chain;
10101
10103 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10104 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10105 DstMemCacheHint, SrcMemCacheHint);
10106 if (Result.getNode())
10107 return Result;
10108 }
10109
10110 // Then check to see if we should lower the memcpy with target-specific
10111 // code. If the target chooses to do this, this is the next best.
10112 if (TSI) {
10113 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10114 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10115 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10116 if (Result.getNode())
10117 return Result;
10118 }
10119
10120 // If we really need inline code and the target declined to provide it,
10121 // use a (potentially long) sequence of loads and stores.
10122 if (AlwaysInline) {
10123 assert(ConstantSize && "AlwaysInline requires a constant size!");
10125 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10126 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10127 DstMemCacheHint, SrcMemCacheHint);
10128 }
10129
10132
10133 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10134 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10135 // respect volatile, so they may do things like read or write memory
10136 // beyond the given memory regions. But fixing this isn't easy, and most
10137 // people don't care.
10138
10139 // Emit a library call.
10142 Args.emplace_back(Dst, PtrTy);
10143 Args.emplace_back(Src, PtrTy);
10144 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10145 // FIXME: pass in SDLoc
10147 bool IsTailCall = false;
10148 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10149
10150 if (OverrideTailCall.has_value()) {
10151 IsTailCall = *OverrideTailCall;
10152 } else {
10153 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10154 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10155 }
10156 // Lowering doesn't support tail calling inside a function with a
10157 // swifterror argument yet.
10158 IsTailCall &= !hasSwiftErrorArg();
10159
10160 CLI.setDebugLoc(dl)
10161 .setChain(Chain)
10162 .setLibCallee(
10163 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10164 Dst.getValueType().getTypeForEVT(*getContext()),
10165 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10166 std::move(Args))
10168 .setTailCall(IsTailCall);
10169
10170 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10171 return CallResult.second;
10172}
10173
10175 SDValue Dst, SDValue Src, SDValue Size,
10176 Type *SizeTy, unsigned ElemSz,
10177 bool isTailCall,
10178 MachinePointerInfo DstPtrInfo,
10179 MachinePointerInfo SrcPtrInfo) {
10180 // Lowering doesn't support tail calling inside a function with a
10181 // swifterror argument yet.
10182 isTailCall &= !hasSwiftErrorArg();
10183
10184 // Emit a library call.
10187 Args.emplace_back(Dst, ArgTy);
10188 Args.emplace_back(Src, ArgTy);
10189 Args.emplace_back(Size, SizeTy);
10190
10191 RTLIB::Libcall LibraryCall =
10193 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10194 if (LibcallImpl == RTLIB::Unsupported)
10195 report_fatal_error("Unsupported element size");
10196
10198 CLI.setDebugLoc(dl)
10199 .setChain(Chain)
10200 .setLibCallee(
10201 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10203 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10204 std::move(Args))
10206 .setTailCall(isTailCall);
10207
10208 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10209 return CallResult.second;
10210}
10211
10213 SDValue Src, SDValue Size, Align DstAlign,
10214 Align SrcAlign, bool isVol, const CallInst *CI,
10215 std::optional<bool> OverrideTailCall,
10216 MachinePointerInfo DstPtrInfo,
10217 MachinePointerInfo SrcPtrInfo,
10218 const AAMDNodes &AAInfo,
10219 BatchAAResults *BatchAA) {
10220 // Check to see if we should lower the memmove to loads and stores first.
10221 // For cases within the target-specified limits, this is the best choice.
10223 if (ConstantSize) {
10224 // Memmove with size zero? Just return the original chain.
10225 if (ConstantSize->isZero())
10226 return Chain;
10227
10229 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10230 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10231 if (Result.getNode())
10232 return Result;
10233 }
10234
10235 // Then check to see if we should lower the memmove with target-specific
10236 // code. If the target chooses to do this, this is the next best.
10237 if (TSI) {
10238 SDValue Result = TSI->EmitTargetCodeForMemmove(
10239 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10240 SrcPtrInfo);
10241 if (Result.getNode())
10242 return Result;
10243 }
10244
10247
10248 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10249 // not be safe. See memcpy above for more details.
10250
10251 // Emit a library call.
10254 Args.emplace_back(Dst, PtrTy);
10255 Args.emplace_back(Src, PtrTy);
10256 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10257 // FIXME: pass in SDLoc
10259
10260 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10261
10262 bool IsTailCall = false;
10263 if (OverrideTailCall.has_value()) {
10264 IsTailCall = *OverrideTailCall;
10265 } else {
10266 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10267 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10268 }
10269 // Lowering doesn't support tail calling inside a function with a
10270 // swifterror argument yet.
10271 IsTailCall &= !hasSwiftErrorArg();
10272
10273 CLI.setDebugLoc(dl)
10274 .setChain(Chain)
10275 .setLibCallee(
10276 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10277 Dst.getValueType().getTypeForEVT(*getContext()),
10278 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10279 std::move(Args))
10281 .setTailCall(IsTailCall);
10282
10283 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10284 return CallResult.second;
10285}
10286
10288 SDValue Dst, SDValue Src, SDValue Size,
10289 Type *SizeTy, unsigned ElemSz,
10290 bool isTailCall,
10291 MachinePointerInfo DstPtrInfo,
10292 MachinePointerInfo SrcPtrInfo) {
10293 // Lowering doesn't support tail calling inside a function with a
10294 // swifterror argument yet.
10295 isTailCall &= !hasSwiftErrorArg();
10296
10297 // Emit a library call.
10300 Args.emplace_back(Dst, IntPtrTy);
10301 Args.emplace_back(Src, IntPtrTy);
10302 Args.emplace_back(Size, SizeTy);
10303
10304 RTLIB::Libcall LibraryCall =
10306 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10307 if (LibcallImpl == RTLIB::Unsupported)
10308 report_fatal_error("Unsupported element size");
10309
10311 CLI.setDebugLoc(dl)
10312 .setChain(Chain)
10313 .setLibCallee(
10314 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10316 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10317 std::move(Args))
10319 .setTailCall(isTailCall);
10320
10321 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10322 return CallResult.second;
10323}
10324
10326 SDValue Src, SDValue Size, Align Alignment,
10327 bool isVol, bool AlwaysInline,
10328 const CallInst *CI,
10329 MachinePointerInfo DstPtrInfo,
10330 const AAMDNodes &AAInfo) {
10331 // Check to see if we should lower the memset to stores first.
10332 // For cases within the target-specified limits, this is the best choice.
10334 if (ConstantSize) {
10335 // Memset with size zero? Just return the original chain.
10336 if (ConstantSize->isZero())
10337 return Chain;
10338
10339 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10340 ConstantSize->getZExtValue(), Alignment,
10341 isVol, false, DstPtrInfo, AAInfo);
10342
10343 if (Result.getNode())
10344 return Result;
10345 }
10346
10347 // Then check to see if we should lower the memset with target-specific
10348 // code. If the target chooses to do this, this is the next best.
10349 if (TSI) {
10350 SDValue Result = TSI->EmitTargetCodeForMemset(
10351 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10352 if (Result.getNode())
10353 return Result;
10354 }
10355
10356 // If we really need inline code and the target declined to provide it,
10357 // use a (potentially long) sequence of loads and stores.
10358 if (AlwaysInline) {
10359 assert(ConstantSize && "AlwaysInline requires a constant size!");
10360 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10361 ConstantSize->getZExtValue(), Alignment,
10362 isVol, true, DstPtrInfo, AAInfo);
10363 assert(Result &&
10364 "getMemsetStores must return a valid sequence when AlwaysInline");
10365 return Result;
10366 }
10367
10369
10370 // Emit a library call.
10371 auto &Ctx = *getContext();
10372 const auto& DL = getDataLayout();
10373
10375 // FIXME: pass in SDLoc
10376 CLI.setDebugLoc(dl).setChain(Chain);
10377
10378 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10379 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10380
10381 // If zeroing out and bzero is present, use it.
10382 if (UseBZero) {
10384 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10385 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10386 CLI.setLibCallee(
10387 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10388 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10389 } else {
10390 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10391
10393 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10394 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
10395 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10396 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10397 Dst.getValueType().getTypeForEVT(Ctx),
10398 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10399 std::move(Args));
10400 }
10401
10402 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10403 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10404
10405 // If we're going to use bzero, make sure not to tail call unless the
10406 // subsequent return doesn't need a value, as bzero doesn't return the first
10407 // arg unlike memset.
10408 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10409 bool IsTailCall = CI && CI->isTailCall() &&
10411 ReturnsFirstArg && LowersToMemset) &&
10412 // Lowering doesn't support tail calling inside a function
10413 // with a swifterror argument yet.
10415 CLI.setDiscardResult().setTailCall(IsTailCall);
10416
10417 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10418 return CallResult.second;
10419}
10420
10423 Type *SizeTy, unsigned ElemSz,
10424 bool isTailCall,
10425 MachinePointerInfo DstPtrInfo) {
10426 // Lowering doesn't support tail calling inside a function with a
10427 // swifterror argument yet.
10428 isTailCall &= !hasSwiftErrorArg();
10429
10430 // Emit a library call.
10432 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10433 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
10434 Args.emplace_back(Size, SizeTy);
10435
10436 RTLIB::Libcall LibraryCall =
10438 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10439 if (LibcallImpl == RTLIB::Unsupported)
10440 report_fatal_error("Unsupported element size");
10441
10443 CLI.setDebugLoc(dl)
10444 .setChain(Chain)
10445 .setLibCallee(
10446 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10448 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10449 std::move(Args))
10451 .setTailCall(isTailCall);
10452
10453 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10454 return CallResult.second;
10455}
10456
10457SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10459 MachineMemOperand *MMO,
10460 ISD::LoadExtType ExtType) {
10462 AddNodeIDNode(ID, Opcode, VTList, Ops);
10463 ID.AddInteger(MemVT.getRawBits());
10464 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10465 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10466 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10467 ID.AddInteger(MMO->getFlags());
10468 void* IP = nullptr;
10469 if (auto *E = cast_or_null<AtomicSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10470 E->refineAlignment(MMO);
10471 E->refineMMOMetadata(MMO);
10472 return SDValue(E, 0);
10473 }
10474
10475 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10476 VTList, MemVT, MMO, ExtType);
10477 createOperands(N, Ops);
10478
10479 CSEMap.InsertNode(N, IP);
10480 InsertNode(N);
10481 SDValue V(N, 0);
10482 NewSDValueDbgMsg(V, "Creating new node: ", this);
10483 return V;
10484}
10485
10487 EVT MemVT, SDVTList VTs, SDValue Chain,
10488 SDValue Ptr, SDValue Cmp, SDValue Swp,
10489 MachineMemOperand *MMO) {
10490 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10492 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10493
10494 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10495 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10496}
10497
10498SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10499 SDValue Chain, SDValue Ptr, SDValue Val,
10500 MachineMemOperand *MMO) {
10501 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10502 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10503 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10504 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10505 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10506 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10507 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10508 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10509 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10510 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10511 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10512 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10513 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10514 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10515 Opcode == ISD::ATOMIC_STORE) &&
10516 "Invalid Atomic Op");
10517
10518 EVT VT = Val.getValueType();
10519
10520 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10521 getVTList(VT, MVT::Other);
10522 SDValue Ops[] = {Chain, Ptr, Val};
10523 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10524}
10525
10527 EVT MemVT, EVT VT, SDValue Chain,
10528 SDValue Ptr, MachineMemOperand *MMO) {
10529 SDVTList VTs = getVTList(VT, MVT::Other);
10530 SDValue Ops[] = {Chain, Ptr};
10531 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10532}
10533
10534/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10536 if (Ops.size() == 1)
10537 return Ops[0];
10538
10540 VTs.reserve(Ops.size());
10541 for (const SDValue &Op : Ops)
10542 VTs.push_back(Op.getValueType());
10543 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10544}
10545
10547 SDValue Chain, const SDLoc &dl) {
10548 SmallVector<SDValue, 4> RetValues;
10549 RetValues.reserve(ResultTypes.size());
10550 for (EVT VT : ResultTypes)
10551 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10552 return getMergeValues(RetValues, dl);
10553}
10554
10556 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10557 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10559 const AAMDNodes &AAInfo) {
10560 if (Size.hasValue() && !Size.getValue())
10562
10564 MachineMemOperand *MMO =
10565 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10566
10567 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10568}
10569
10571 SDVTList VTList,
10572 ArrayRef<SDValue> Ops, EVT MemVT,
10573 MachineMemOperand *MMO) {
10574 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10575}
10576
10578 SDVTList VTList,
10579 ArrayRef<SDValue> Ops, EVT MemVT,
10581 assert(!MMOs.empty() && "Must have at least one MMO");
10582 assert(
10583 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10584 Opcode == ISD::PREFETCH ||
10585 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10586 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10587 "Opcode is not a memory-accessing opcode!");
10588
10590 if (MMOs.size() == 1) {
10591 MemRefs = MMOs[0];
10592 } else {
10593 // Allocate: [size_t count][MMO*][MMO*]...
10594 size_t AllocSize =
10595 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10596 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10597 size_t *CountPtr = static_cast<size_t *>(Buffer);
10598 *CountPtr = MMOs.size();
10599 MachineMemOperand **Array =
10600 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10601 llvm::copy(MMOs, Array);
10602 MemRefs = Array;
10603 }
10604
10605 // Memoize the node unless it returns a glue result.
10607 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10609 AddNodeIDNode(ID, Opcode, VTList, Ops);
10610 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10611 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10612 ID.AddInteger(MemVT.getRawBits());
10613 for (const MachineMemOperand *MMO : MMOs) {
10614 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10615 ID.AddInteger(MMO->getFlags());
10616 }
10617 void *IP = nullptr;
10618 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10619 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10620 return SDValue(E, 0);
10621 }
10622
10623 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10624 VTList, MemVT, MemRefs);
10625 createOperands(N, Ops);
10626 CSEMap.InsertNode(N, IP);
10627 } else {
10628 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10629 VTList, MemVT, MemRefs);
10630 createOperands(N, Ops);
10631 }
10632 InsertNode(N);
10633 SDValue V(N, 0);
10634 NewSDValueDbgMsg(V, "Creating new node: ", this);
10635 return V;
10636}
10637
10639 SDValue Chain, int FrameIndex) {
10640 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10641 const auto VTs = getVTList(MVT::Other);
10642 SDValue Ops[2] = {
10643 Chain,
10644 getFrameIndex(FrameIndex,
10645 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10646 true)};
10647
10649 AddNodeIDNode(ID, Opcode, VTs, Ops);
10650 ID.AddInteger(FrameIndex);
10651 void *IP = nullptr;
10652 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10653 return SDValue(E, 0);
10654
10655 LifetimeSDNode *N =
10656 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10657 createOperands(N, Ops);
10658 CSEMap.InsertNode(N, IP);
10659 InsertNode(N);
10660 SDValue V(N, 0);
10661 NewSDValueDbgMsg(V, "Creating new node: ", this);
10662 return V;
10663}
10664
10666 uint64_t Guid, uint64_t Index,
10667 uint32_t Attr) {
10668 const unsigned Opcode = ISD::PSEUDO_PROBE;
10669 const auto VTs = getVTList(MVT::Other);
10670 SDValue Ops[] = {Chain};
10672 AddNodeIDNode(ID, Opcode, VTs, Ops);
10673 ID.AddInteger(Guid);
10674 ID.AddInteger(Index);
10675 void *IP = nullptr;
10676 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
10677 return SDValue(E, 0);
10678
10679 auto *N = newSDNode<PseudoProbeSDNode>(
10680 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10681 createOperands(N, Ops);
10682 CSEMap.InsertNode(N, IP);
10683 InsertNode(N);
10684 SDValue V(N, 0);
10685 NewSDValueDbgMsg(V, "Creating new node: ", this);
10686 return V;
10687}
10688
10689/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10690/// MachinePointerInfo record from it. This is particularly useful because the
10691/// code generator has many cases where it doesn't bother passing in a
10692/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10694 SelectionDAG &DAG, SDValue Ptr,
10695 int64_t Offset = 0) {
10696 // If this is FI+Offset, we can model it.
10697 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10699 FI->getIndex(), Offset);
10700
10701 // If this is (FI+Offset1)+Offset2, we can model it.
10702 if (Ptr.getOpcode() != ISD::ADD ||
10705 return Info;
10706
10707 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10709 DAG.getMachineFunction(), FI,
10710 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10711}
10712
10713/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10714/// MachinePointerInfo record from it. This is particularly useful because the
10715/// code generator has many cases where it doesn't bother passing in a
10716/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10718 SelectionDAG &DAG, SDValue Ptr,
10719 SDValue OffsetOp) {
10720 // If the 'Offset' value isn't a constant, we can't handle this.
10722 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10723 if (OffsetOp.isUndef())
10724 return InferPointerInfo(Info, DAG, Ptr);
10725 return Info;
10726}
10727
10729 EVT VT, const SDLoc &dl, SDValue Chain,
10730 SDValue Ptr, SDValue Offset,
10731 MachinePointerInfo PtrInfo, EVT MemVT,
10732 Align Alignment,
10733 MachineMemOperand::Flags MMOFlags,
10734 const MMOMetadata &Metadata) {
10735 assert(Chain.getValueType() == MVT::Other &&
10736 "Invalid chain type");
10737
10738 MMOFlags |= MachineMemOperand::MOLoad;
10739 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10740 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10741 // clients.
10742 if (PtrInfo.V.isNull())
10743 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10744
10745 TypeSize Size = MemVT.getStoreSize();
10747 MachineMemOperand *MMO =
10748 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10749 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10750}
10751
10753 EVT VT, const SDLoc &dl, SDValue Chain,
10754 SDValue Ptr, SDValue Offset, EVT MemVT,
10755 MachineMemOperand *MMO) {
10756 if (VT == MemVT) {
10757 ExtType = ISD::NON_EXTLOAD;
10758 } else if (ExtType == ISD::NON_EXTLOAD) {
10759 assert(VT == MemVT && "Non-extending load from different memory type!");
10760 } else {
10761 // Extending load.
10762 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10763 "Should only be an extending load, not truncating!");
10764 assert(VT.isInteger() == MemVT.isInteger() &&
10765 "Cannot convert from FP to Int or Int -> FP!");
10766 assert(VT.isVector() == MemVT.isVector() &&
10767 "Cannot use an ext load to convert to or from a vector!");
10768 assert((!VT.isVector() ||
10770 "Cannot use an ext load to change the number of vector elements!");
10771 }
10772
10773 assert((!MMO->getRanges() ||
10775 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10776 MemVT.isInteger())) &&
10777 "Range metadata and load type must match!");
10778
10779 bool Indexed = AM != ISD::UNINDEXED;
10780 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10781 "Unindexed load with an offset!");
10782
10783 SDVTList VTs = Indexed ?
10784 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10785 SDValue Ops[] = { Chain, Ptr, Offset };
10787 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
10788 ID.AddInteger(MemVT.getRawBits());
10789 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
10790 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
10791 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10792 ID.AddInteger(MMO->getFlags());
10793 void *IP = nullptr;
10794 if (auto *E = cast_or_null<LoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10795 E->refineAlignment(MMO);
10796 E->refineMMOMetadata(MMO);
10797 return SDValue(E, 0);
10798 }
10799 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10800 ExtType, MemVT, MMO);
10801 createOperands(N, Ops);
10802
10803 CSEMap.InsertNode(N, IP);
10804 InsertNode(N);
10805 SDValue V(N, 0);
10806 NewSDValueDbgMsg(V, "Creating new node: ", this);
10807 return V;
10808}
10809
10811 SDValue Ptr, MachinePointerInfo PtrInfo,
10812 MaybeAlign Alignment,
10813 MachineMemOperand::Flags MMOFlags,
10814 const MMOMetadata &Metadata) {
10816 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10817 PtrInfo, VT, Alignment, MMOFlags, Metadata);
10818}
10819
10821 SDValue Ptr, MachineMemOperand *MMO) {
10823 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10824 VT, MMO);
10825}
10826
10828 EVT VT, SDValue Chain, SDValue Ptr,
10829 MachinePointerInfo PtrInfo, EVT MemVT,
10830 MaybeAlign Alignment,
10831 MachineMemOperand::Flags MMOFlags,
10832 const MMOMetadata &Metadata) {
10834 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
10835 MemVT, Alignment, MMOFlags, Metadata);
10836}
10837
10839 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
10840 MachineMemOperand *MMO) {
10842 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
10843 MemVT, MMO);
10844}
10845
10849 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
10850 assert(LD->getOffset().getOpcode() == ISD::POISON &&
10851 "Load is already a indexed load!");
10852 // Don't propagate the invariant or dereferenceable flags.
10853 auto MMOFlags =
10854 LD->getMemOperand()->getFlags() &
10856 return getLoad(
10857 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
10858 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
10859 MMOFlags,
10860 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
10861}
10862
10864 SDValue Ptr, MachinePointerInfo PtrInfo,
10865 Align Alignment,
10866 MachineMemOperand::Flags MMOFlags,
10867 const MMOMetadata &Metadata) {
10868 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10869
10870 MMOFlags |= MachineMemOperand::MOStore;
10871 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10872 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10873
10874 if (PtrInfo.V.isNull())
10875 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10876
10879 MachineMemOperand *MMO =
10880 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10881 return getStore(Chain, dl, Val, Ptr, MMO);
10882}
10883
10885 SDValue Ptr, MachineMemOperand *MMO) {
10887 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
10889}
10890
10892 SDValue Ptr, SDValue Offset, EVT SVT,
10894 bool IsTruncating) {
10895 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10896 EVT VT = Val.getValueType();
10897 if (VT == SVT) {
10898 IsTruncating = false;
10899 } else if (!IsTruncating) {
10900 assert(VT == SVT && "No-truncating store from different memory type!");
10901 } else {
10903 "Should only be a truncating store, not extending!");
10904 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10905 assert(VT.isVector() == SVT.isVector() &&
10906 "Cannot use trunc store to convert to or from a vector!");
10907 assert((!VT.isVector() ||
10909 "Cannot use trunc store to change the number of vector elements!");
10910 }
10911
10912 bool Indexed = AM != ISD::UNINDEXED;
10913 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10914 "Unindexed store with an offset!");
10915 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10916 : getVTList(MVT::Other);
10917 SDValue Ops[] = {Chain, Val, Ptr, Offset};
10919 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
10920 ID.AddInteger(SVT.getRawBits());
10921 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
10922 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
10923 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10924 ID.AddInteger(MMO->getFlags());
10925 void *IP = nullptr;
10926 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10927 cast<StoreSDNode>(E)->refineAlignment(MMO);
10928 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
10929 return SDValue(E, 0);
10930 }
10931 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10932 IsTruncating, SVT, MMO);
10933 createOperands(N, Ops);
10934
10935 CSEMap.InsertNode(N, IP);
10936 InsertNode(N);
10937 SDValue V(N, 0);
10938 NewSDValueDbgMsg(V, "Creating new node: ", this);
10939 return V;
10940}
10941
10943 SDValue Ptr, SDValue Offset,
10944 MachinePointerInfo PtrInfo, EVT SVT,
10945 Align Alignment,
10946 MachineMemOperand::Flags MMOFlags,
10947 const MMOMetadata &Metadata) {
10948 assert(Chain.getValueType() == MVT::Other &&
10949 "Invalid chain type");
10950
10951 MMOFlags |= MachineMemOperand::MOStore;
10952 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10953 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10954
10955 if (PtrInfo.V.isNull())
10956 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10957
10959 MachineMemOperand *MMO = MF.getMachineMemOperand(
10960 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
10961 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
10962}
10963
10965 SDValue Ptr, MachinePointerInfo PtrInfo,
10966 EVT SVT, Align Alignment,
10967 MachineMemOperand::Flags MMOFlags,
10968 const MMOMetadata &Metadata) {
10969 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
10970 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
10971}
10972
10974 SDValue Ptr, SDValue Offset, EVT SVT,
10975 MachineMemOperand *MMO) {
10976 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
10977}
10978
10980 SDValue Ptr, EVT SVT,
10981 MachineMemOperand *MMO) {
10982 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
10983 ISD::UNINDEXED, true);
10984}
10985
10989 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
10990 assert(ST->getOffset().getOpcode() == ISD::POISON &&
10991 "Store is already a indexed store!");
10992 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10993 ST->getMemoryVT(), ST->getMemOperand(), AM,
10994 ST->isTruncatingStore());
10995}
10996
10998 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
10999 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11000 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11001 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11002 const MDNode *Ranges, bool IsExpanding) {
11003 MMOFlags |= MachineMemOperand::MOLoad;
11004 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11005 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11006 // clients.
11007 if (PtrInfo.V.isNull())
11008 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11009
11010 TypeSize Size = MemVT.getStoreSize();
11012 MachineMemOperand *MMO = MF.getMachineMemOperand(
11013 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11014 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11015 MMO, IsExpanding);
11016}
11017
11019 ISD::LoadExtType ExtType, EVT VT,
11020 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11021 SDValue Offset, SDValue Mask, SDValue EVL,
11022 EVT MemVT, MachineMemOperand *MMO,
11023 bool IsExpanding) {
11024 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11025 assert(Mask.getValueType().getVectorElementCount() ==
11026 VT.getVectorElementCount() &&
11027 "Vector width mismatch between mask and data");
11028
11029 bool Indexed = AM != ISD::UNINDEXED;
11030 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11031 "Unindexed load with an offset!");
11032
11033 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11034 : getVTList(VT, MVT::Other);
11035 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11037 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
11038 ID.AddInteger(MemVT.getRawBits());
11039 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11040 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11041 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11042 ID.AddInteger(MMO->getFlags());
11043 void *IP = nullptr;
11044 if (auto *E = cast_or_null<VPLoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
11045 E->refineAlignment(MMO);
11046 E->refineMMOMetadata(MMO);
11047 return SDValue(E, 0);
11048 }
11049 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11050 ExtType, IsExpanding, MemVT, MMO);
11051 createOperands(N, Ops);
11052
11053 CSEMap.InsertNode(N, IP);
11054 InsertNode(N);
11055 SDValue V(N, 0);
11056 NewSDValueDbgMsg(V, "Creating new node: ", this);
11057 return V;
11058}
11059
11061 SDValue Ptr, SDValue Mask, SDValue EVL,
11062 MachinePointerInfo PtrInfo,
11063 MaybeAlign Alignment,
11064 MachineMemOperand::Flags MMOFlags,
11065 const AAMDNodes &AAInfo, const MDNode *Ranges,
11066 bool IsExpanding) {
11068 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11069 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11070 IsExpanding);
11071}
11072
11074 SDValue Ptr, SDValue Mask, SDValue EVL,
11075 MachineMemOperand *MMO, bool IsExpanding) {
11077 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11078 Mask, EVL, VT, MMO, IsExpanding);
11079}
11080
11082 EVT VT, SDValue Chain, SDValue Ptr,
11083 SDValue Mask, SDValue EVL,
11084 MachinePointerInfo PtrInfo, EVT MemVT,
11085 MaybeAlign Alignment,
11086 MachineMemOperand::Flags MMOFlags,
11087 const AAMDNodes &AAInfo, bool IsExpanding) {
11089 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11090 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11091 IsExpanding);
11092}
11093
11095 EVT VT, SDValue Chain, SDValue Ptr,
11096 SDValue Mask, SDValue EVL, EVT MemVT,
11097 MachineMemOperand *MMO, bool IsExpanding) {
11099 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11100 EVL, MemVT, MMO, IsExpanding);
11101}
11102
11106 auto *LD = cast<VPLoadSDNode>(OrigLoad);
11107 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11108 "Load is already a indexed load!");
11109 // Don't propagate the invariant or dereferenceable flags.
11110 auto MMOFlags =
11111 LD->getMemOperand()->getFlags() &
11113 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
11114 LD->getChain(), Base, Offset, LD->getMask(),
11115 LD->getVectorLength(), LD->getPointerInfo(),
11116 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
11117 nullptr, LD->isExpandingLoad());
11118}
11119
11121 SDValue Ptr, SDValue Offset, SDValue Mask,
11122 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11123 ISD::MemIndexedMode AM, bool IsTruncating,
11124 bool IsCompressing) {
11125 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11126 assert(Mask.getValueType().getVectorElementCount() ==
11128 "Vector width mismatch between mask and data");
11129
11130 bool Indexed = AM != ISD::UNINDEXED;
11131 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11132 "Unindexed vp_store with an offset!");
11133 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11134 : getVTList(MVT::Other);
11135 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11137 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11138 ID.AddInteger(MemVT.getRawBits());
11139 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11140 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11141 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11142 ID.AddInteger(MMO->getFlags());
11143 void *IP = nullptr;
11144 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11145 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11146 return SDValue(E, 0);
11147 }
11148 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11149 IsTruncating, IsCompressing, MemVT, MMO);
11150 createOperands(N, Ops);
11151
11152 CSEMap.InsertNode(N, IP);
11153 InsertNode(N);
11154 SDValue V(N, 0);
11155 NewSDValueDbgMsg(V, "Creating new node: ", this);
11156 return V;
11157}
11158
11160 SDValue Val, SDValue Ptr, SDValue Mask,
11161 SDValue EVL, MachinePointerInfo PtrInfo,
11162 EVT SVT, Align Alignment,
11163 MachineMemOperand::Flags MMOFlags,
11164 const AAMDNodes &AAInfo,
11165 bool IsCompressing) {
11166 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11167
11168 MMOFlags |= MachineMemOperand::MOStore;
11169 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11170
11171 if (PtrInfo.V.isNull())
11172 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11173
11175 MachineMemOperand *MMO = MF.getMachineMemOperand(
11176 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11177 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11178 IsCompressing);
11179}
11180
11182 SDValue Val, SDValue Ptr, SDValue Mask,
11183 SDValue EVL, EVT SVT,
11184 MachineMemOperand *MMO,
11185 bool IsCompressing) {
11186 EVT VT = Val.getValueType();
11187
11188 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11189 if (VT == SVT)
11190 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11191 EVL, VT, MMO, ISD::UNINDEXED,
11192 /*IsTruncating*/ false, IsCompressing);
11193
11195 "Should only be a truncating store, not extending!");
11196 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11197 assert(VT.isVector() == SVT.isVector() &&
11198 "Cannot use trunc store to convert to or from a vector!");
11199 assert((!VT.isVector() ||
11201 "Cannot use trunc store to change the number of vector elements!");
11202
11203 SDVTList VTs = getVTList(MVT::Other);
11205 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11207 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11208 ID.AddInteger(SVT.getRawBits());
11209 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11210 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11211 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11212 ID.AddInteger(MMO->getFlags());
11213 void *IP = nullptr;
11214 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11215 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11216 return SDValue(E, 0);
11217 }
11218 auto *N =
11219 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11220 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11221 createOperands(N, Ops);
11222
11223 CSEMap.InsertNode(N, IP);
11224 InsertNode(N);
11225 SDValue V(N, 0);
11226 NewSDValueDbgMsg(V, "Creating new node: ", this);
11227 return V;
11228}
11229
11233 auto *ST = cast<VPStoreSDNode>(OrigStore);
11234 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11235 "Store is already an indexed store!");
11236 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
11237 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
11238 Offset, ST->getMask(), ST->getVectorLength()};
11240 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11241 ID.AddInteger(ST->getMemoryVT().getRawBits());
11242 ID.AddInteger(ST->getRawSubclassData());
11243 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
11244 ID.AddInteger(ST->getMemOperand()->getFlags());
11245 void *IP = nullptr;
11246 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11247 return SDValue(E, 0);
11248
11249 auto *N = newSDNode<VPStoreSDNode>(
11250 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
11251 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
11252 createOperands(N, Ops);
11253
11254 CSEMap.InsertNode(N, IP);
11255 InsertNode(N);
11256 SDValue V(N, 0);
11257 NewSDValueDbgMsg(V, "Creating new node: ", this);
11258 return V;
11259}
11260
11262 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11263 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11264 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11265 bool Indexed = AM != ISD::UNINDEXED;
11266 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11267 "Unindexed load with an offset!");
11268
11269 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11270 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11271 : getVTList(VT, MVT::Other);
11273 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11274 ID.AddInteger(VT.getRawBits());
11275 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11276 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11277 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11278
11279 void *IP = nullptr;
11280 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11281 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11282 return SDValue(E, 0);
11283 }
11284
11285 auto *N =
11286 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11287 ExtType, IsExpanding, MemVT, MMO);
11288 createOperands(N, Ops);
11289 CSEMap.InsertNode(N, IP);
11290 InsertNode(N);
11291 SDValue V(N, 0);
11292 NewSDValueDbgMsg(V, "Creating new node: ", this);
11293 return V;
11294}
11295
11297 SDValue Ptr, SDValue Stride,
11298 SDValue Mask, SDValue EVL,
11299 MachineMemOperand *MMO,
11300 bool IsExpanding) {
11302 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11303 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11304}
11305
11307 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11308 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11309 MachineMemOperand *MMO, bool IsExpanding) {
11311 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11312 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11313}
11314
11316 SDValue Val, SDValue Ptr,
11317 SDValue Offset, SDValue Stride,
11318 SDValue Mask, SDValue EVL, EVT MemVT,
11319 MachineMemOperand *MMO,
11321 bool IsTruncating, bool IsCompressing) {
11322 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11323 bool Indexed = AM != ISD::UNINDEXED;
11324 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11325 "Unindexed vp_store with an offset!");
11326 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11327 : getVTList(MVT::Other);
11328 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11330 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11331 ID.AddInteger(MemVT.getRawBits());
11332 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11333 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11334 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11335 void *IP = nullptr;
11336 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11337 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11338 return SDValue(E, 0);
11339 }
11340 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11341 VTs, AM, IsTruncating,
11342 IsCompressing, MemVT, MMO);
11343 createOperands(N, Ops);
11344
11345 CSEMap.InsertNode(N, IP);
11346 InsertNode(N);
11347 SDValue V(N, 0);
11348 NewSDValueDbgMsg(V, "Creating new node: ", this);
11349 return V;
11350}
11351
11353 SDValue Val, SDValue Ptr,
11354 SDValue Stride, SDValue Mask,
11355 SDValue EVL, EVT SVT,
11356 MachineMemOperand *MMO,
11357 bool IsCompressing) {
11358 EVT VT = Val.getValueType();
11359
11360 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11361 if (VT == SVT)
11362 return getStridedStoreVP(Chain, DL, Val, Ptr, getPOISON(Ptr.getValueType()),
11363 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
11364 /*IsTruncating*/ false, IsCompressing);
11365
11367 "Should only be a truncating store, not extending!");
11368 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11369 assert(VT.isVector() == SVT.isVector() &&
11370 "Cannot use trunc store to convert to or from a vector!");
11371 assert((!VT.isVector() ||
11373 "Cannot use trunc store to change the number of vector elements!");
11374
11375 SDVTList VTs = getVTList(MVT::Other);
11377 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
11379 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11380 ID.AddInteger(SVT.getRawBits());
11381 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11382 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11383 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11384 void *IP = nullptr;
11385 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11386 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11387 return SDValue(E, 0);
11388 }
11389 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11390 VTs, ISD::UNINDEXED, true,
11391 IsCompressing, SVT, MMO);
11392 createOperands(N, Ops);
11393
11394 CSEMap.InsertNode(N, IP);
11395 InsertNode(N);
11396 SDValue V(N, 0);
11397 NewSDValueDbgMsg(V, "Creating new node: ", this);
11398 return V;
11399}
11400
11403 ISD::MemIndexType IndexType) {
11404 assert(Ops.size() == 6 && "Incompatible number of operands");
11405
11407 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
11408 ID.AddInteger(VT.getRawBits());
11409 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11410 dl.getIROrder(), VTs, VT, MMO, IndexType));
11411 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11412 ID.AddInteger(MMO->getFlags());
11413 void *IP = nullptr;
11414 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11415 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11416 return SDValue(E, 0);
11417 }
11418
11419 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11420 VT, MMO, IndexType);
11421 createOperands(N, Ops);
11422
11423 assert(N->getMask().getValueType().getVectorElementCount() ==
11424 N->getValueType(0).getVectorElementCount() &&
11425 "Vector width mismatch between mask and data");
11426 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11427 N->getValueType(0).getVectorElementCount().isScalable() &&
11428 "Scalable flags of index and data do not match");
11430 N->getIndex().getValueType().getVectorElementCount(),
11431 N->getValueType(0).getVectorElementCount()) &&
11432 "Vector width mismatch between index and data");
11433 assert(isa<ConstantSDNode>(N->getScale()) &&
11434 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11435 "Scale should be a constant power of 2");
11436
11437 CSEMap.InsertNode(N, IP);
11438 InsertNode(N);
11439 SDValue V(N, 0);
11440 NewSDValueDbgMsg(V, "Creating new node: ", this);
11441 return V;
11442}
11443
11446 MachineMemOperand *MMO,
11447 ISD::MemIndexType IndexType) {
11448 assert(Ops.size() == 7 && "Incompatible number of operands");
11449
11451 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
11452 ID.AddInteger(VT.getRawBits());
11453 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11454 dl.getIROrder(), VTs, VT, MMO, IndexType));
11455 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11456 ID.AddInteger(MMO->getFlags());
11457 void *IP = nullptr;
11458 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11459 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11460 return SDValue(E, 0);
11461 }
11462 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11463 VT, MMO, IndexType);
11464 createOperands(N, Ops);
11465
11466 assert(N->getMask().getValueType().getVectorElementCount() ==
11467 N->getValue().getValueType().getVectorElementCount() &&
11468 "Vector width mismatch between mask and data");
11469 assert(
11470 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11471 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11472 "Scalable flags of index and data do not match");
11474 N->getIndex().getValueType().getVectorElementCount(),
11475 N->getValue().getValueType().getVectorElementCount()) &&
11476 "Vector width mismatch between index and data");
11477 assert(isa<ConstantSDNode>(N->getScale()) &&
11478 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11479 "Scale should be a constant power of 2");
11480
11481 CSEMap.InsertNode(N, IP);
11482 InsertNode(N);
11483 SDValue V(N, 0);
11484 NewSDValueDbgMsg(V, "Creating new node: ", this);
11485 return V;
11486}
11487
11490 SDValue PassThru, EVT MemVT,
11491 MachineMemOperand *MMO,
11493 ISD::LoadExtType ExtTy, bool isExpanding) {
11494 bool Indexed = AM != ISD::UNINDEXED;
11495 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11496 "Unindexed masked load with an offset!");
11497 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11498 : getVTList(VT, MVT::Other);
11499 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11501 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
11502 ID.AddInteger(MemVT.getRawBits());
11503 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11504 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11505 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11506 ID.AddInteger(MMO->getFlags());
11507 void *IP = nullptr;
11508 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11509 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11510 return SDValue(E, 0);
11511 }
11512 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11513 AM, ExtTy, isExpanding, MemVT, MMO);
11514 createOperands(N, Ops);
11515
11516 CSEMap.InsertNode(N, IP);
11517 InsertNode(N);
11518 SDValue V(N, 0);
11519 NewSDValueDbgMsg(V, "Creating new node: ", this);
11520 return V;
11521}
11522
11527 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11528 "Masked load is already a indexed load!");
11529 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11530 Offset, LD->getMask(), LD->getPassThru(),
11531 LD->getMemoryVT(), LD->getMemOperand(), AM,
11532 LD->getExtensionType(), LD->isExpandingLoad());
11533}
11534
11537 SDValue Mask, EVT MemVT,
11538 MachineMemOperand *MMO,
11539 ISD::MemIndexedMode AM, bool IsTruncating,
11540 bool IsCompressing) {
11541 assert(Chain.getValueType() == MVT::Other &&
11542 "Invalid chain type");
11543 bool Indexed = AM != ISD::UNINDEXED;
11544 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11545 "Unindexed masked store with an offset!");
11546 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11547 : getVTList(MVT::Other);
11548 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11550 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
11551 ID.AddInteger(MemVT.getRawBits());
11552 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11553 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11554 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11555 ID.AddInteger(MMO->getFlags());
11556 void *IP = nullptr;
11557 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11558 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11559 return SDValue(E, 0);
11560 }
11561 auto *N =
11562 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11563 IsTruncating, IsCompressing, MemVT, MMO);
11564 createOperands(N, Ops);
11565
11566 CSEMap.InsertNode(N, IP);
11567 InsertNode(N);
11568 SDValue V(N, 0);
11569 NewSDValueDbgMsg(V, "Creating new node: ", this);
11570 return V;
11571}
11572
11577 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11578 "Masked store is already a indexed store!");
11579 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11580 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11581 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11582}
11583
11586 MachineMemOperand *MMO,
11587 ISD::MemIndexType IndexType,
11588 ISD::LoadExtType ExtTy) {
11589 assert(Ops.size() == 6 && "Incompatible number of operands");
11590
11592 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
11593 ID.AddInteger(MemVT.getRawBits());
11594 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11595 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11596 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11597 ID.AddInteger(MMO->getFlags());
11598 void *IP = nullptr;
11599 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11600 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11601 return SDValue(E, 0);
11602 }
11603
11604 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11605 VTs, MemVT, MMO, IndexType, ExtTy);
11606 createOperands(N, Ops);
11607
11608 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11609 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11610 assert(N->getMask().getValueType().getVectorElementCount() ==
11611 N->getValueType(0).getVectorElementCount() &&
11612 "Vector width mismatch between mask and data");
11613 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11614 N->getValueType(0).getVectorElementCount().isScalable() &&
11615 "Scalable flags of index and data do not match");
11617 N->getIndex().getValueType().getVectorElementCount(),
11618 N->getValueType(0).getVectorElementCount()) &&
11619 "Vector width mismatch between index and data");
11620 assert(isa<ConstantSDNode>(N->getScale()) &&
11621 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11622 "Scale should be a constant power of 2");
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
11633 MachineMemOperand *MMO,
11634 ISD::MemIndexType IndexType,
11635 bool IsTrunc) {
11636 assert(Ops.size() == 6 && "Incompatible number of operands");
11637
11639 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
11640 ID.AddInteger(MemVT.getRawBits());
11641 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11642 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11643 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11644 ID.AddInteger(MMO->getFlags());
11645 void *IP = nullptr;
11646 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11647 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11648 return SDValue(E, 0);
11649 }
11650
11651 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11652 VTs, MemVT, MMO, IndexType, IsTrunc);
11653 createOperands(N, Ops);
11654
11655 assert(N->getMask().getValueType().getVectorElementCount() ==
11656 N->getValue().getValueType().getVectorElementCount() &&
11657 "Vector width mismatch between mask and data");
11658 assert(
11659 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11660 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11661 "Scalable flags of index and data do not match");
11663 N->getIndex().getValueType().getVectorElementCount(),
11664 N->getValue().getValueType().getVectorElementCount()) &&
11665 "Vector width mismatch between index and data");
11666 assert(isa<ConstantSDNode>(N->getScale()) &&
11667 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11668 "Scale should be a constant power of 2");
11669
11670 CSEMap.InsertNode(N, IP);
11671 InsertNode(N);
11672 SDValue V(N, 0);
11673 NewSDValueDbgMsg(V, "Creating new node: ", this);
11674 return V;
11675}
11676
11678 const SDLoc &dl, ArrayRef<SDValue> Ops,
11679 MachineMemOperand *MMO,
11680 ISD::MemIndexType IndexType) {
11681 assert(Ops.size() == 7 && "Incompatible number of operands");
11682
11685 ID.AddInteger(MemVT.getRawBits());
11686 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11687 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11688 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11689 ID.AddInteger(MMO->getFlags());
11690 void *IP = nullptr;
11691 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11692 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11693 return SDValue(E, 0);
11694 }
11695
11696 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11697 VTs, MemVT, MMO, IndexType);
11698 createOperands(N, Ops);
11699
11700 assert(N->getMask().getValueType().getVectorElementCount() ==
11701 N->getIndex().getValueType().getVectorElementCount() &&
11702 "Vector width mismatch between mask and data");
11703 assert(isa<ConstantSDNode>(N->getScale()) &&
11704 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11705 "Scale should be a constant power of 2");
11706 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11707
11708 CSEMap.InsertNode(N, IP);
11709 InsertNode(N);
11710 SDValue V(N, 0);
11711 NewSDValueDbgMsg(V, "Creating new node: ", this);
11712 return V;
11713}
11714
11716 SDValue Ptr, SDValue Mask, SDValue EVL,
11717 MachineMemOperand *MMO) {
11718 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11719 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11721 AddNodeIDNode(ID, ISD::VP_LOAD_FF, VTs, Ops);
11722 ID.AddInteger(VT.getRawBits());
11723 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11724 VTs, VT, MMO));
11725 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11726 ID.AddInteger(MMO->getFlags());
11727 void *IP = nullptr;
11728 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11729 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11730 return SDValue(E, 0);
11731 }
11732 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11733 VT, MMO);
11734 createOperands(N, Ops);
11735
11736 CSEMap.InsertNode(N, IP);
11737 InsertNode(N);
11738 SDValue V(N, 0);
11739 NewSDValueDbgMsg(V, "Creating new node: ", this);
11740 return V;
11741}
11742
11744 EVT MemVT, MachineMemOperand *MMO) {
11745 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11746 SDVTList VTs = getVTList(MVT::Other);
11747 SDValue Ops[] = {Chain, Ptr};
11750 ID.AddInteger(MemVT.getRawBits());
11751 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11752 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11753 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11754 ID.AddInteger(MMO->getFlags());
11755 void *IP = nullptr;
11756 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11757 return SDValue(E, 0);
11758
11759 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11760 dl.getDebugLoc(), VTs, MemVT, MMO);
11761 createOperands(N, Ops);
11762
11763 CSEMap.InsertNode(N, IP);
11764 InsertNode(N);
11765 SDValue V(N, 0);
11766 NewSDValueDbgMsg(V, "Creating new node: ", this);
11767 return V;
11768}
11769
11771 EVT MemVT, MachineMemOperand *MMO) {
11772 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11773 SDVTList VTs = getVTList(MVT::Other);
11774 SDValue Ops[] = {Chain, Ptr};
11777 ID.AddInteger(MemVT.getRawBits());
11778 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11779 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11780 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11781 ID.AddInteger(MMO->getFlags());
11782 void *IP = nullptr;
11783 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11784 return SDValue(E, 0);
11785
11786 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11787 dl.getDebugLoc(), VTs, MemVT, MMO);
11788 createOperands(N, Ops);
11789
11790 CSEMap.InsertNode(N, IP);
11791 InsertNode(N);
11792 SDValue V(N, 0);
11793 NewSDValueDbgMsg(V, "Creating new node: ", this);
11794 return V;
11795}
11796
11798 // select undef, T, F --> T (if T is a constant), otherwise F
11799 // select, ?, undef, F --> F
11800 // select, ?, T, undef --> T
11801 if (Cond.isUndef())
11802 return isConstantValueOfAnyType(T) ? T : F;
11803 if (T.isUndef())
11805 if (F.isUndef())
11807
11808 // select true, T, F --> T
11809 // select false, T, F --> F
11810 if (auto C = isBoolConstant(Cond))
11811 return *C ? T : F;
11812
11813 // select ?, T, T --> T
11814 if (T == F)
11815 return T;
11816
11817 return SDValue();
11818}
11819
11821 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11822 if (X.isUndef())
11823 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11824 // shift X, undef --> undef (because it may shift by the bitwidth)
11825 if (Y.isUndef())
11826 return getUNDEF(X.getValueType());
11827
11828 // shift 0, Y --> 0
11829 // shift X, 0 --> X
11831 return X;
11832
11833 // shift X, C >= bitwidth(X) --> undef
11834 // All vector elements must be too big (or undef) to avoid partial undefs.
11835 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11836 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11837 };
11838 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11839 return getUNDEF(X.getValueType());
11840
11841 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11842 if (X.getValueType().getScalarType() == MVT::i1)
11843 return X;
11844
11845 return SDValue();
11846}
11847
11849 SDNodeFlags Flags) {
11850 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11851 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11852 // operation is poison. That result can be relaxed to undef.
11853 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11854 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11855 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11856 (YC && YC->getValueAPF().isNaN());
11857 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11858 (YC && YC->getValueAPF().isInfinity());
11859
11860 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11861 return getUNDEF(X.getValueType());
11862
11863 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11864 return getUNDEF(X.getValueType());
11865
11866 if (!YC)
11867 return SDValue();
11868
11869 // X + -0.0 --> X
11870 if (Opcode == ISD::FADD)
11871 if (YC->getValueAPF().isNegZero())
11872 return X;
11873
11874 // X - +0.0 --> X
11875 if (Opcode == ISD::FSUB)
11876 if (YC->getValueAPF().isPosZero())
11877 return X;
11878
11879 // X * 1.0 --> X
11880 // X / 1.0 --> X
11881 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11882 if (YC->getValueAPF().isOne())
11883 return X;
11884
11885 // X * 0.0 --> 0.0
11886 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11887 if (YC->getValueAPF().isZero())
11888 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11889
11890 return SDValue();
11891}
11892
11894 SDValue Ptr, SDValue SV, unsigned Align) {
11895 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11896 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11897}
11898
11899SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11901 switch (Ops.size()) {
11902 case 0: return getNode(Opcode, DL, VT);
11903 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
11904 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
11905 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
11906 default: break;
11907 }
11908
11909 // Copy from an SDUse array into an SDValue array for use with
11910 // the regular getNode logic.
11912 return getNode(Opcode, DL, VT, NewOps);
11913}
11914
11915SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11917 SDNodeFlags Flags;
11918 if (Inserter)
11919 Flags = Inserter->getFlags();
11920 return getNode(Opcode, DL, VT, Ops, Flags);
11921}
11922
11923SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11924 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11925 unsigned NumOps = Ops.size();
11926 switch (NumOps) {
11927 case 0: return getNode(Opcode, DL, VT);
11928 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
11929 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
11930 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
11931 default: break;
11932 }
11933
11934#ifndef NDEBUG
11935 for (const auto &Op : Ops)
11936 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11937 "Operand is DELETED_NODE!");
11938#endif
11939
11940 switch (Opcode) {
11941 default: break;
11942 case ISD::BUILD_VECTOR:
11943 // Attempt to simplify BUILD_VECTOR.
11944 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
11945 return V;
11946 break;
11948 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
11949 return V;
11950 break;
11951 case ISD::SELECT_CC:
11952 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
11953 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
11954 "LHS and RHS of condition must have same type!");
11955 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11956 "True and False arms of SelectCC must have same type!");
11957 assert(Ops[2].getValueType() == VT &&
11958 "select_cc node must be of same type as true and false value!");
11959 assert((!Ops[0].getValueType().isVector() ||
11960 Ops[0].getValueType().getVectorElementCount() ==
11961 VT.getVectorElementCount()) &&
11962 "Expected select_cc with vector result to have the same sized "
11963 "comparison type!");
11964 break;
11965 case ISD::BR_CC:
11966 assert(NumOps == 5 && "BR_CC takes 5 operands!");
11967 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11968 "LHS/RHS of comparison should match types!");
11969 break;
11970 case ISD::VP_REDUCE_MUL:
11971 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
11972 if (VT == MVT::i1)
11973 Opcode = ISD::VP_REDUCE_AND;
11974 break;
11975 case ISD::VP_REDUCE_ADD:
11976 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
11977 if (VT == MVT::i1)
11978 Opcode = ISD::VP_REDUCE_XOR;
11979 break;
11980 case ISD::VP_REDUCE_SMAX:
11981 case ISD::VP_REDUCE_UMIN:
11982 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
11983 // VP_REDUCE_AND.
11984 if (VT == MVT::i1)
11985 Opcode = ISD::VP_REDUCE_AND;
11986 break;
11987 case ISD::VP_REDUCE_SMIN:
11988 case ISD::VP_REDUCE_UMAX:
11989 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
11990 // VP_REDUCE_OR.
11991 if (VT == MVT::i1)
11992 Opcode = ISD::VP_REDUCE_OR;
11993 break;
11994 }
11995
11996 // Memoize nodes.
11997 SDNode *N;
11998 SDVTList VTs = getVTList(VT);
11999
12000 if (VT != MVT::Glue) {
12002 AddNodeIDNode(ID, Opcode, VTs, Ops);
12003 void *IP = nullptr;
12004
12005 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12006 E->intersectFlagsWith(Flags);
12007 return SDValue(E, 0);
12008 }
12009
12010 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12011 createOperands(N, Ops);
12012
12013 CSEMap.InsertNode(N, IP);
12014 } else {
12015 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12016 createOperands(N, Ops);
12017 }
12018
12019 N->setFlags(Flags);
12020 InsertNode(N);
12021 SDValue V(N, 0);
12022 NewSDValueDbgMsg(V, "Creating new node: ", this);
12023 return V;
12024}
12025
12026SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12027 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12028 SDNodeFlags Flags;
12029 if (Inserter)
12030 Flags = Inserter->getFlags();
12031 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12032}
12033
12034SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12036 const SDNodeFlags Flags) {
12037 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12038}
12039
12040SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12042 SDNodeFlags Flags;
12043 if (Inserter)
12044 Flags = Inserter->getFlags();
12045 return getNode(Opcode, DL, VTList, Ops, Flags);
12046}
12047
12048SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12049 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12050 if (VTList.NumVTs == 1)
12051 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12052
12053#ifndef NDEBUG
12054 for (const auto &Op : Ops)
12055 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12056 "Operand is DELETED_NODE!");
12057#endif
12058
12059 switch (Opcode) {
12060 case ISD::SADDO:
12061 case ISD::UADDO:
12062 case ISD::SSUBO:
12063 case ISD::USUBO: {
12064 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12065 "Invalid add/sub overflow op!");
12066 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12067 Ops[0].getValueType() == Ops[1].getValueType() &&
12068 Ops[0].getValueType() == VTList.VTs[0] &&
12069 "Binary operator types must match!");
12070 SDValue N1 = Ops[0], N2 = Ops[1];
12071 canonicalizeCommutativeBinop(Opcode, N1, N2);
12072
12073 // (X +- 0) -> X with zero-overflow.
12074 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12075 /*AllowTruncation*/ true);
12076 if (N2CV && N2CV->isZero()) {
12077 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12078 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12079 }
12080
12081 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12082 VTList.VTs[1].getScalarType() == MVT::i1) {
12083 SDValue F1 = getFreeze(N1);
12084 SDValue F2 = getFreeze(N2);
12085 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12086 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12087 return getNode(ISD::MERGE_VALUES, DL, VTList,
12088 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12089 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12090 Flags);
12091 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12092 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12093 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12094 return getNode(ISD::MERGE_VALUES, DL, VTList,
12095 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12096 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12097 Flags);
12098 }
12099 }
12100 break;
12101 }
12102 case ISD::SADDO_CARRY:
12103 case ISD::UADDO_CARRY:
12104 case ISD::SSUBO_CARRY:
12105 case ISD::USUBO_CARRY:
12106 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12107 "Invalid add/sub overflow op!");
12108 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12109 Ops[0].getValueType() == Ops[1].getValueType() &&
12110 Ops[0].getValueType() == VTList.VTs[0] &&
12111 Ops[2].getValueType() == VTList.VTs[1] &&
12112 "Binary operator types must match!");
12113 break;
12114 case ISD::SMUL_LOHI:
12115 case ISD::UMUL_LOHI: {
12116 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12117 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12118 VTList.VTs[0] == Ops[0].getValueType() &&
12119 VTList.VTs[0] == Ops[1].getValueType() &&
12120 "Binary operator types must match!");
12121 // Constant fold.
12124 if (LHS && RHS) {
12125 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12126 unsigned OutWidth = Width * 2;
12127 APInt Val = LHS->getAPIntValue();
12128 APInt Mul = RHS->getAPIntValue();
12129 if (Opcode == ISD::SMUL_LOHI) {
12130 Val = Val.sext(OutWidth);
12131 Mul = Mul.sext(OutWidth);
12132 } else {
12133 Val = Val.zext(OutWidth);
12134 Mul = Mul.zext(OutWidth);
12135 }
12136 Val *= Mul;
12137
12138 SDValue Hi =
12139 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12140 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12141 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12142 }
12143 break;
12144 }
12145 case ISD::FFREXP: {
12146 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12147 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12148 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12149
12151 int FrexpExp;
12152 APFloat FrexpMant =
12153 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12154 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12155 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12156 DL, VTList.VTs[1]);
12157 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12158 }
12159
12160 break;
12161 }
12163 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12164 "Invalid STRICT_FP_EXTEND!");
12165 assert(VTList.VTs[0].isFloatingPoint() &&
12166 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12167 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12168 "STRICT_FP_EXTEND result type should be vector iff the operand "
12169 "type is vector!");
12170 assert((!VTList.VTs[0].isVector() ||
12171 VTList.VTs[0].getVectorElementCount() ==
12172 Ops[1].getValueType().getVectorElementCount()) &&
12173 "Vector element count mismatch!");
12174 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12175 "Invalid fpext node, dst <= src!");
12176 break;
12178 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12179 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12180 "STRICT_FP_ROUND result type should be vector iff the operand "
12181 "type is vector!");
12182 assert((!VTList.VTs[0].isVector() ||
12183 VTList.VTs[0].getVectorElementCount() ==
12184 Ops[1].getValueType().getVectorElementCount()) &&
12185 "Vector element count mismatch!");
12186 assert(VTList.VTs[0].isFloatingPoint() &&
12187 Ops[1].getValueType().isFloatingPoint() &&
12188 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12189 Ops[2].getOpcode() == ISD::TargetConstant &&
12190 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12191 "Invalid STRICT_FP_ROUND!");
12192 break;
12193 }
12194
12195 // Memoize the node unless it returns a glue result.
12196 SDNode *N;
12197 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12199 AddNodeIDNode(ID, Opcode, VTList, Ops);
12200 void *IP = nullptr;
12201 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12202 E->intersectFlagsWith(Flags);
12203 return SDValue(E, 0);
12204 }
12205
12206 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12207 createOperands(N, Ops);
12208 CSEMap.InsertNode(N, IP);
12209 } else {
12210 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12211 createOperands(N, Ops);
12212 }
12213
12214 N->setFlags(Flags);
12215 InsertNode(N);
12216 SDValue V(N, 0);
12217 NewSDValueDbgMsg(V, "Creating new node: ", this);
12218 return V;
12219}
12220
12221SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12222 SDVTList VTList) {
12223 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12224}
12225
12226SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12227 SDValue N1) {
12228 SDValue Ops[] = { N1 };
12229 return getNode(Opcode, DL, VTList, Ops);
12230}
12231
12232SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12233 SDValue N1, SDValue N2) {
12234 SDValue Ops[] = { N1, N2 };
12235 return getNode(Opcode, DL, VTList, Ops);
12236}
12237
12238SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12239 SDValue N1, SDValue N2, SDValue N3) {
12240 SDValue Ops[] = { N1, N2, N3 };
12241 return getNode(Opcode, DL, VTList, Ops);
12242}
12243
12244SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12245 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12246 SDValue Ops[] = { N1, N2, N3, N4 };
12247 return getNode(Opcode, DL, VTList, Ops);
12248}
12249
12250SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12251 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12252 SDValue N5) {
12253 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12254 return getNode(Opcode, DL, VTList, Ops);
12255}
12256
12258 if (!VT.isExtended())
12259 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12260
12261 return makeVTList(&(*EVTs.insert(VT).first), 1);
12262}
12263
12266 ID.AddInteger(2U);
12267 ID.AddInteger(VT1.getRawBits());
12268 ID.AddInteger(VT2.getRawBits());
12269
12270 void *IP = nullptr;
12271 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12272 if (!Result) {
12273 EVT *Array = Allocator.Allocate<EVT>(2);
12274 Array[0] = VT1;
12275 Array[1] = VT2;
12276 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
12277 VTListMap.InsertNode(Result, IP);
12278 }
12279 return Result->getSDVTList();
12280}
12281
12284 ID.AddInteger(3U);
12285 ID.AddInteger(VT1.getRawBits());
12286 ID.AddInteger(VT2.getRawBits());
12287 ID.AddInteger(VT3.getRawBits());
12288
12289 void *IP = nullptr;
12290 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12291 if (!Result) {
12292 EVT *Array = Allocator.Allocate<EVT>(3);
12293 Array[0] = VT1;
12294 Array[1] = VT2;
12295 Array[2] = VT3;
12296 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
12297 VTListMap.InsertNode(Result, IP);
12298 }
12299 return Result->getSDVTList();
12300}
12301
12304 ID.AddInteger(4U);
12305 ID.AddInteger(VT1.getRawBits());
12306 ID.AddInteger(VT2.getRawBits());
12307 ID.AddInteger(VT3.getRawBits());
12308 ID.AddInteger(VT4.getRawBits());
12309
12310 void *IP = nullptr;
12311 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12312 if (!Result) {
12313 EVT *Array = Allocator.Allocate<EVT>(4);
12314 Array[0] = VT1;
12315 Array[1] = VT2;
12316 Array[2] = VT3;
12317 Array[3] = VT4;
12318 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
12319 VTListMap.InsertNode(Result, IP);
12320 }
12321 return Result->getSDVTList();
12322}
12323
12325 unsigned NumVTs = VTs.size();
12327 ID.AddInteger(NumVTs);
12328 for (unsigned index = 0; index < NumVTs; index++) {
12329 ID.AddInteger(VTs[index].getRawBits());
12330 }
12331
12332 void *IP = nullptr;
12333 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12334 if (!Result) {
12335 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
12336 llvm::copy(VTs, Array);
12337 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
12338 VTListMap.InsertNode(Result, IP);
12339 }
12340 return Result->getSDVTList();
12341}
12342
12343
12344/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12345/// specified operands. If the resultant node already exists in the DAG,
12346/// this does not modify the specified node, instead it returns the node that
12347/// already exists. If the resultant node does not exist in the DAG, the
12348/// input node is returned. As a degenerate case, if you specify the same
12349/// input operands as the node already has, the input node is returned.
12351 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12352
12353 // Check to see if there is no change.
12354 if (Op == N->getOperand(0)) return N;
12355
12356 // See if the modified node already exists.
12357 void *InsertPos = nullptr;
12358 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
12359 return Existing;
12360
12361 // Nope it doesn't. Remove the node from its current place in the maps.
12362 if (InsertPos)
12363 if (!RemoveNodeFromCSEMaps(N))
12364 InsertPos = nullptr;
12365
12366 // Now we update the operands.
12367 N->OperandList[0].set(Op);
12368
12370 // If this gets put into a CSE map, add it.
12371 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12372 return N;
12373}
12374
12376 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12377
12378 // Check to see if there is no change.
12379 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12380 return N; // No operands changed, just return the input node.
12381
12382 // See if the modified node already exists.
12383 void *InsertPos = nullptr;
12384 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
12385 return Existing;
12386
12387 // Nope it doesn't. Remove the node from its current place in the maps.
12388 if (InsertPos)
12389 if (!RemoveNodeFromCSEMaps(N))
12390 InsertPos = nullptr;
12391
12392 // Now we update the operands.
12393 if (N->OperandList[0] != Op1)
12394 N->OperandList[0].set(Op1);
12395 if (N->OperandList[1] != Op2)
12396 N->OperandList[1].set(Op2);
12397
12399 // If this gets put into a CSE map, add it.
12400 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12401 return N;
12402}
12403
12406 SDValue Ops[] = { Op1, Op2, Op3 };
12407 return UpdateNodeOperands(N, Ops);
12408}
12409
12412 SDValue Op3, SDValue Op4) {
12413 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12414 return UpdateNodeOperands(N, Ops);
12415}
12416
12419 SDValue Op3, SDValue Op4, SDValue Op5) {
12420 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12421 return UpdateNodeOperands(N, Ops);
12422}
12423
12426 unsigned NumOps = Ops.size();
12427 assert(N->getNumOperands() == NumOps &&
12428 "Update with wrong number of operands");
12429
12430 // If no operands changed just return the input node.
12431 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12432 return N;
12433
12434 // See if the modified node already exists.
12435 void *InsertPos = nullptr;
12436 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
12437 return Existing;
12438
12439 // Nope it doesn't. Remove the node from its current place in the maps.
12440 if (InsertPos)
12441 if (!RemoveNodeFromCSEMaps(N))
12442 InsertPos = nullptr;
12443
12444 // Now we update the operands.
12445 for (unsigned i = 0; i != NumOps; ++i)
12446 if (N->OperandList[i] != Ops[i])
12447 N->OperandList[i].set(Ops[i]);
12448
12450 // If this gets put into a CSE map, add it.
12451 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12452 return N;
12453}
12454
12455/// DropOperands - Release the operands and set this node to have
12456/// zero operands.
12458 // Unlike the code in MorphNodeTo that does this, we don't need to
12459 // watch for dead nodes here.
12460 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12461 SDUse &Use = *I++;
12462 Use.set(SDValue());
12463 }
12464}
12465
12467 ArrayRef<MachineMemOperand *> NewMemRefs) {
12468 if (NewMemRefs.empty()) {
12469 N->clearMemRefs();
12470 return;
12471 }
12472
12473 // Check if we can avoid allocating by storing a single reference directly.
12474 if (NewMemRefs.size() == 1) {
12475 N->MemRefs = NewMemRefs[0];
12476 N->NumMemRefs = 1;
12477 return;
12478 }
12479
12480 MachineMemOperand **MemRefsBuffer =
12481 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12482 llvm::copy(NewMemRefs, MemRefsBuffer);
12483 N->MemRefs = MemRefsBuffer;
12484 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12485}
12486
12487/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12488/// machine opcode.
12489///
12491 EVT VT) {
12492 SDVTList VTs = getVTList(VT);
12493 return SelectNodeTo(N, MachineOpc, VTs, {});
12494}
12495
12497 EVT VT, SDValue Op1) {
12498 SDVTList VTs = getVTList(VT);
12499 SDValue Ops[] = { Op1 };
12500 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12501}
12502
12504 EVT VT, SDValue Op1,
12505 SDValue Op2) {
12506 SDVTList VTs = getVTList(VT);
12507 SDValue Ops[] = { Op1, Op2 };
12508 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12509}
12510
12512 EVT VT, SDValue Op1,
12513 SDValue Op2, SDValue Op3) {
12514 SDVTList VTs = getVTList(VT);
12515 SDValue Ops[] = { Op1, Op2, Op3 };
12516 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12517}
12518
12521 SDVTList VTs = getVTList(VT);
12522 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12523}
12524
12526 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12527 SDVTList VTs = getVTList(VT1, VT2);
12528 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12529}
12530
12532 EVT VT1, EVT VT2) {
12533 SDVTList VTs = getVTList(VT1, VT2);
12534 return SelectNodeTo(N, MachineOpc, VTs, {});
12535}
12536
12538 EVT VT1, EVT VT2, EVT VT3,
12540 SDVTList VTs = getVTList(VT1, VT2, VT3);
12541 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12542}
12543
12545 EVT VT1, EVT VT2,
12546 SDValue Op1, SDValue Op2) {
12547 SDVTList VTs = getVTList(VT1, VT2);
12548 SDValue Ops[] = { Op1, Op2 };
12549 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12550}
12551
12554 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12555 // Reset the NodeID to -1.
12556 New->setNodeId(-1);
12557 if (New != N) {
12558 ReplaceAllUsesWith(N, New);
12560 }
12561 return New;
12562}
12563
12564/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12565/// the line number information on the merged node since it is not possible to
12566/// preserve the information that operation is associated with multiple lines.
12567/// This will make the debugger working better at -O0, were there is a higher
12568/// probability having other instructions associated with that line.
12569///
12570/// For IROrder, we keep the smaller of the two
12571SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12572 DebugLoc NLoc = N->getDebugLoc();
12573 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12574 N->setDebugLoc(DebugLoc());
12575 }
12576 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12577 N->setIROrder(Order);
12578 return N;
12579}
12580
12581/// MorphNodeTo - This *mutates* the specified node to have the specified
12582/// return type, opcode, and operands.
12583///
12584/// Note that MorphNodeTo returns the resultant node. If there is already a
12585/// node of the specified opcode and operands, it returns that node instead of
12586/// the current one. Note that the SDLoc need not be the same.
12587///
12588/// Using MorphNodeTo is faster than creating a new node and swapping it in
12589/// with ReplaceAllUsesWith both because it often avoids allocating a new
12590/// node, and because it doesn't require CSE recalculation for any of
12591/// the node's users.
12592///
12593/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12594/// As a consequence it isn't appropriate to use from within the DAG combiner or
12595/// the legalizer which maintain worklists that would need to be updated when
12596/// deleting things.
12599 // If an identical node already exists, use it.
12600 void *IP = nullptr;
12601 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12603 AddNodeIDNode(ID, Opc, VTs, Ops);
12604 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
12605 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12606 }
12607
12608 if (!RemoveNodeFromCSEMaps(N))
12609 IP = nullptr;
12610
12611 // Start the morphing.
12612 N->NodeType = Opc;
12613 N->ValueList = VTs.VTs;
12614 N->NumValues = VTs.NumVTs;
12615
12616 // Clear the operands list, updating used nodes to remove this from their
12617 // use list. Keep track of any operands that become dead as a result.
12618 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12619 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12620 SDUse &Use = *I++;
12621 SDNode *Used = Use.getNode();
12622 Use.set(SDValue());
12623 if (Used->use_empty())
12624 DeadNodeSet.insert(Used);
12625 }
12626
12627 // For MachineNode, initialize the memory references information.
12629 MN->clearMemRefs();
12630
12631 // Swap for an appropriately sized array from the recycler.
12632 removeOperands(N);
12633 createOperands(N, Ops);
12634
12635 // Delete any nodes that are still dead after adding the uses for the
12636 // new operands.
12637 if (!DeadNodeSet.empty()) {
12638 SmallVector<SDNode *, 16> DeadNodes;
12639 for (SDNode *N : DeadNodeSet)
12640 if (N->use_empty())
12641 DeadNodes.push_back(N);
12642 RemoveDeadNodes(DeadNodes);
12643 }
12644
12645 if (IP)
12646 CSEMap.InsertNode(N, IP); // Memoize the new node.
12647 return N;
12648}
12649
12651 unsigned OrigOpc = Node->getOpcode();
12652 unsigned NewOpc;
12653 switch (OrigOpc) {
12654 default:
12655 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12656#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12657 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12658#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12659 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12660#include "llvm/IR/ConstrainedOps.def"
12661 }
12662
12663 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12664
12665 // We're taking this node out of the chain, so we need to re-link things.
12666 SDValue InputChain = Node->getOperand(0);
12667 SDValue OutputChain = SDValue(Node, 1);
12668 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12669
12671 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12672 Ops.push_back(Node->getOperand(i));
12673
12674 SDVTList VTs = getVTList(Node->getValueType(0));
12675 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12676
12677 // MorphNodeTo can operate in two ways: if an existing node with the
12678 // specified operands exists, it can just return it. Otherwise, it
12679 // updates the node in place to have the requested operands.
12680 if (Res == Node) {
12681 // If we updated the node in place, reset the node ID. To the isel,
12682 // this should be just like a newly allocated machine node.
12683 Res->setNodeId(-1);
12684 } else {
12687 }
12688
12689 return Res;
12690}
12691
12692/// getMachineNode - These are used for target selectors to create a new node
12693/// with specified return type(s), MachineInstr opcode, and operands.
12694///
12695/// Note that getMachineNode returns the resultant node. If there is already a
12696/// node of the specified opcode and operands, it returns that node instead of
12697/// the current one.
12699 EVT VT) {
12700 SDVTList VTs = getVTList(VT);
12701 return getMachineNode(Opcode, dl, VTs, {});
12702}
12703
12705 EVT VT, SDValue Op1) {
12706 SDVTList VTs = getVTList(VT);
12707 SDValue Ops[] = { Op1 };
12708 return getMachineNode(Opcode, dl, VTs, Ops);
12709}
12710
12712 EVT VT, SDValue Op1, SDValue Op2) {
12713 SDVTList VTs = getVTList(VT);
12714 SDValue Ops[] = { Op1, Op2 };
12715 return getMachineNode(Opcode, dl, VTs, Ops);
12716}
12717
12719 EVT VT, SDValue Op1, SDValue Op2,
12720 SDValue Op3) {
12721 SDVTList VTs = getVTList(VT);
12722 SDValue Ops[] = { Op1, Op2, Op3 };
12723 return getMachineNode(Opcode, dl, VTs, Ops);
12724}
12725
12728 SDVTList VTs = getVTList(VT);
12729 return getMachineNode(Opcode, dl, VTs, Ops);
12730}
12731
12733 EVT VT1, EVT VT2, SDValue Op1,
12734 SDValue Op2) {
12735 SDVTList VTs = getVTList(VT1, VT2);
12736 SDValue Ops[] = { Op1, Op2 };
12737 return getMachineNode(Opcode, dl, VTs, Ops);
12738}
12739
12741 EVT VT1, EVT VT2, SDValue Op1,
12742 SDValue Op2, SDValue Op3) {
12743 SDVTList VTs = getVTList(VT1, VT2);
12744 SDValue Ops[] = { Op1, Op2, Op3 };
12745 return getMachineNode(Opcode, dl, VTs, Ops);
12746}
12747
12749 EVT VT1, EVT VT2,
12751 SDVTList VTs = getVTList(VT1, VT2);
12752 return getMachineNode(Opcode, dl, VTs, Ops);
12753}
12754
12756 EVT VT1, EVT VT2, EVT VT3,
12757 SDValue Op1, SDValue Op2) {
12758 SDVTList VTs = getVTList(VT1, VT2, VT3);
12759 SDValue Ops[] = { Op1, Op2 };
12760 return getMachineNode(Opcode, dl, VTs, Ops);
12761}
12762
12764 EVT VT1, EVT VT2, EVT VT3,
12765 SDValue Op1, SDValue Op2,
12766 SDValue Op3) {
12767 SDVTList VTs = getVTList(VT1, VT2, VT3);
12768 SDValue Ops[] = { Op1, Op2, Op3 };
12769 return getMachineNode(Opcode, dl, VTs, Ops);
12770}
12771
12773 EVT VT1, EVT VT2, EVT VT3,
12775 SDVTList VTs = getVTList(VT1, VT2, VT3);
12776 return getMachineNode(Opcode, dl, VTs, Ops);
12777}
12778
12780 ArrayRef<EVT> ResultTys,
12782 SDVTList VTs = getVTList(ResultTys);
12783 return getMachineNode(Opcode, dl, VTs, Ops);
12784}
12785
12787 SDVTList VTs,
12789 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12791 void *IP = nullptr;
12792
12793 if (DoCSE) {
12795 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
12796 IP = nullptr;
12797 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12798 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12799 }
12800 }
12801
12802 // Allocate a new MachineSDNode.
12803 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12804 createOperands(N, Ops);
12805
12806 if (DoCSE)
12807 CSEMap.InsertNode(N, IP);
12808
12809 InsertNode(N);
12810 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12811 return N;
12812}
12813
12814/// getTargetExtractSubreg - A convenience function for creating
12815/// TargetOpcode::EXTRACT_SUBREG nodes.
12817 SDValue Operand) {
12818 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12819 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12820 VT, Operand, SRIdxVal);
12821 return SDValue(Subreg, 0);
12822}
12823
12824/// getTargetInsertSubreg - A convenience function for creating
12825/// TargetOpcode::INSERT_SUBREG nodes.
12827 SDValue Operand, SDValue Subreg) {
12828 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12829 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12830 VT, Operand, Subreg, SRIdxVal);
12831 return SDValue(Result, 0);
12832}
12833
12834/// getNodeIfExists - Get the specified node if it's already available, or
12835/// else return NULL.
12838 bool AllowCommute) {
12839 SDNodeFlags Flags;
12840 if (Inserter)
12841 Flags = Inserter->getFlags();
12842 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12843}
12844
12847 const SDNodeFlags Flags,
12848 bool AllowCommute) {
12849 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12850 return nullptr;
12851
12852 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12854 AddNodeIDNode(ID, Opcode, VTList, LookupOps);
12855 void *IP = nullptr;
12856 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) {
12857 E->intersectFlagsWith(Flags);
12858 return E;
12859 }
12860 return nullptr;
12861 };
12862
12863 if (SDNode *Existing = Lookup(Ops))
12864 return Existing;
12865
12866 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12867 return Lookup({Ops[1], Ops[0]});
12868
12869 return nullptr;
12870}
12871
12872/// doesNodeExist - Check if a node exists without modifying its flags.
12873bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12875 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12877 AddNodeIDNode(ID, Opcode, VTList, Ops);
12878 void *IP = nullptr;
12879 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
12880 return true;
12881 }
12882 return false;
12883}
12884
12885/// getDbgValue - Creates a SDDbgValue node.
12886///
12887/// SDNode
12889 SDNode *N, unsigned R, bool IsIndirect,
12890 const DebugLoc &DL, unsigned O) {
12891 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12892 "Expected inlined-at fields to agree");
12893 return new (DbgInfo->getAlloc())
12894 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12895 {}, IsIndirect, DL, O,
12896 /*IsVariadic=*/false);
12897}
12898
12899/// Constant
12901 DIExpression *Expr,
12902 const Value *C,
12903 const DebugLoc &DL, unsigned O) {
12904 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12905 "Expected inlined-at fields to agree");
12906 return new (DbgInfo->getAlloc())
12907 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12908 /*IsIndirect=*/false, DL, O,
12909 /*IsVariadic=*/false);
12910}
12911
12912/// FrameIndex
12914 DIExpression *Expr, unsigned FI,
12915 bool IsIndirect,
12916 const DebugLoc &DL,
12917 unsigned O) {
12918 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12919 "Expected inlined-at fields to agree");
12920 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12921}
12922
12923/// FrameIndex with dependencies
12925 DIExpression *Expr, unsigned FI,
12926 ArrayRef<SDNode *> Dependencies,
12927 bool IsIndirect,
12928 const DebugLoc &DL,
12929 unsigned O) {
12930 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12931 "Expected inlined-at fields to agree");
12932 return new (DbgInfo->getAlloc())
12933 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
12934 Dependencies, IsIndirect, DL, O,
12935 /*IsVariadic=*/false);
12936}
12937
12938/// VReg
12940 Register VReg, bool IsIndirect,
12941 const DebugLoc &DL, unsigned O) {
12942 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12943 "Expected inlined-at fields to agree");
12944 return new (DbgInfo->getAlloc())
12945 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
12946 {}, IsIndirect, DL, O,
12947 /*IsVariadic=*/false);
12948}
12949
12952 ArrayRef<SDNode *> Dependencies,
12953 bool IsIndirect, const DebugLoc &DL,
12954 unsigned O, bool IsVariadic) {
12955 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12956 "Expected inlined-at fields to agree");
12957 return new (DbgInfo->getAlloc())
12958 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
12959 DL, O, IsVariadic);
12960}
12961
12963 unsigned OffsetInBits, unsigned SizeInBits,
12964 bool InvalidateDbg) {
12965 SDNode *FromNode = From.getNode();
12966 SDNode *ToNode = To.getNode();
12967 assert(FromNode && ToNode && "Can't modify dbg values");
12968
12969 // PR35338
12970 // TODO: assert(From != To && "Redundant dbg value transfer");
12971 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
12972 if (From == To || FromNode == ToNode)
12973 return;
12974
12975 if (!FromNode->getHasDebugValue())
12976 return;
12977
12978 SDDbgOperand FromLocOp =
12979 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
12981
12983 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
12984 if (Dbg->isInvalidated())
12985 continue;
12986
12987 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
12988
12989 // Create a new location ops vector that is equal to the old vector, but
12990 // with each instance of FromLocOp replaced with ToLocOp.
12991 bool Changed = false;
12992 auto NewLocOps = Dbg->copyLocationOps();
12993 std::replace_if(
12994 NewLocOps.begin(), NewLocOps.end(),
12995 [&Changed, FromLocOp](const SDDbgOperand &Op) {
12996 bool Match = Op == FromLocOp;
12997 Changed |= Match;
12998 return Match;
12999 },
13000 ToLocOp);
13001 // Ignore this SDDbgValue if we didn't find a matching location.
13002 if (!Changed)
13003 continue;
13004
13005 DIVariable *Var = Dbg->getVariable();
13006 auto *Expr = Dbg->getExpression();
13007 // If a fragment is requested, update the expression.
13008 if (SizeInBits) {
13009 // When splitting a larger (e.g., sign-extended) value whose
13010 // lower bits are described with an SDDbgValue, do not attempt
13011 // to transfer the SDDbgValue to the upper bits.
13012 if (auto FI = Expr->getFragmentInfo())
13013 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13014 continue;
13015 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13016 SizeInBits);
13017 if (!Fragment)
13018 continue;
13019 Expr = *Fragment;
13020 }
13021
13022 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13023 // Clone the SDDbgValue and move it to To.
13024 SDDbgValue *Clone = getDbgValueList(
13025 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13026 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13027 Dbg->isVariadic());
13028 ClonedDVs.push_back(Clone);
13029
13030 if (InvalidateDbg) {
13031 // Invalidate value and indicate the SDDbgValue should not be emitted.
13032 Dbg->setIsInvalidated();
13033 Dbg->setIsEmitted();
13034 }
13035 }
13036
13037 for (SDDbgValue *Dbg : ClonedDVs) {
13038 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13039 "Transferred DbgValues should depend on the new SDNode");
13040 AddDbgValue(Dbg, false);
13041 }
13042}
13043
13045 if (!N.getHasDebugValue())
13046 return;
13047
13048 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13049 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13050 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13051 return SDDbgOperand::fromNode(Node, ResNo);
13052 };
13053
13055 for (auto *DV : GetDbgValues(&N)) {
13056 if (DV->isInvalidated())
13057 continue;
13058 switch (N.getOpcode()) {
13059 default:
13060 break;
13061 case ISD::ADD: {
13062 SDValue N0 = N.getOperand(0);
13063 SDValue N1 = N.getOperand(1);
13064 if (!isa<ConstantSDNode>(N0)) {
13065 bool RHSConstant = isa<ConstantSDNode>(N1);
13066 uint64_t Offset;
13067 if (RHSConstant)
13068 Offset = N.getConstantOperandVal(1);
13069 // We are not allowed to turn indirect debug values variadic, so
13070 // don't salvage those.
13071 if (!RHSConstant && DV->isIndirect())
13072 continue;
13073
13074 // Rewrite an ADD constant node into a DIExpression. Since we are
13075 // performing arithmetic to compute the variable's *value* in the
13076 // DIExpression, we need to mark the expression with a
13077 // DW_OP_stack_value.
13078 auto *DIExpr = DV->getExpression();
13079 auto NewLocOps = DV->copyLocationOps();
13080 bool Changed = false;
13081 size_t OrigLocOpsSize = NewLocOps.size();
13082 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13083 // We're not given a ResNo to compare against because the whole
13084 // node is going away. We know that any ISD::ADD only has one
13085 // result, so we can assume any node match is using the result.
13086 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13087 NewLocOps[i].getSDNode() != &N)
13088 continue;
13089 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13090 if (RHSConstant) {
13093 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13094 } else {
13095 // Convert to a variadic expression (if not already).
13096 // convertToVariadicExpression() returns a const pointer, so we use
13097 // a temporary const variable here.
13098 const auto *TmpDIExpr =
13102 ExprOps.push_back(NewLocOps.size());
13103 ExprOps.push_back(dwarf::DW_OP_plus);
13104 SDDbgOperand RHS =
13106 NewLocOps.push_back(RHS);
13107 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13108 }
13109 Changed = true;
13110 }
13111 (void)Changed;
13112 assert(Changed && "Salvage target doesn't use N");
13113
13114 bool IsVariadic =
13115 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13116
13117 auto AdditionalDependencies = DV->getAdditionalDependencies();
13118 SDDbgValue *Clone = getDbgValueList(
13119 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13120 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13121 ClonedDVs.push_back(Clone);
13122 DV->setIsInvalidated();
13123 DV->setIsEmitted();
13124 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13125 N0.getNode()->dumprFull(this);
13126 dbgs() << " into " << *DIExpr << '\n');
13127 }
13128 break;
13129 }
13130 case ISD::TRUNCATE: {
13131 SDValue N0 = N.getOperand(0);
13132 TypeSize FromSize = N0.getValueSizeInBits();
13133 TypeSize ToSize = N.getValueSizeInBits(0);
13134
13135 DIExpression *DbgExpression = DV->getExpression();
13136 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13137 auto NewLocOps = DV->copyLocationOps();
13138 bool Changed = false;
13139 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13140 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13141 NewLocOps[i].getSDNode() != &N)
13142 continue;
13143
13144 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13145 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13146 Changed = true;
13147 }
13148 assert(Changed && "Salvage target doesn't use N");
13149 (void)Changed;
13150
13151 SDDbgValue *Clone =
13152 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13153 DV->getAdditionalDependencies(), DV->isIndirect(),
13154 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13155
13156 ClonedDVs.push_back(Clone);
13157 DV->setIsInvalidated();
13158 DV->setIsEmitted();
13159 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13160 dbgs() << " into " << *DbgExpression << '\n');
13161 break;
13162 }
13163 }
13164 }
13165
13166 for (SDDbgValue *Dbg : ClonedDVs) {
13167 assert((!Dbg->getSDNodes().empty() ||
13168 llvm::any_of(Dbg->getLocationOps(),
13169 [&](const SDDbgOperand &Op) {
13170 return Op.getKind() == SDDbgOperand::FRAMEIX;
13171 })) &&
13172 "Salvaged DbgValue should depend on a new SDNode");
13173 AddDbgValue(Dbg, false);
13174 }
13175}
13176
13177/// Creates a SDDbgLabel node.
13179 const DebugLoc &DL, unsigned O) {
13180 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13181 "Expected inlined-at fields to agree");
13182 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13183}
13184
13185namespace {
13186
13187/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13188/// pointed to by a use iterator is deleted, increment the use iterator
13189/// so that it doesn't dangle.
13190///
13191class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13194
13195 void NodeDeleted(SDNode *N, SDNode *E) override {
13196 // Increment the iterator as needed.
13197 while (UI != UE && N == UI->getUser())
13198 ++UI;
13199 }
13200
13201public:
13202 RAUWUpdateListener(SelectionDAG &d,
13205 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13206};
13207
13208} // end anonymous namespace
13209
13210/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13211/// This can cause recursive merging of nodes in the DAG.
13212///
13213/// This version assumes From has a single result value.
13214///
13216 SDNode *From = FromN.getNode();
13217 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13218 "Cannot replace with this method!");
13219 assert(From != To.getNode() && "Cannot replace uses of with self");
13220
13221 // Preserve Debug Values
13222 transferDbgValues(FromN, To);
13223 // Preserve extra info.
13224 copyExtraInfo(From, To.getNode());
13225
13226 // Iterate over all the existing uses of From. New uses will be added
13227 // to the beginning of the use list, which we avoid visiting.
13228 // This specifically avoids visiting uses of From that arise while the
13229 // replacement is happening, because any such uses would be the result
13230 // of CSE: If an existing node looks like From after one of its operands
13231 // is replaced by To, we don't want to replace of all its users with To
13232 // too. See PR3018 for more info.
13233 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13234 RAUWUpdateListener Listener(*this, UI, UE);
13235 while (UI != UE) {
13236 SDNode *User = UI->getUser();
13237
13238 // This node is about to morph, remove its old self from the CSE maps.
13239 RemoveNodeFromCSEMaps(User);
13240
13241 // A user can appear in a use list multiple times, and when this
13242 // happens the uses are usually next to each other in the list.
13243 // To help reduce the number of CSE recomputations, process all
13244 // the uses of this user that we can find this way.
13245 do {
13246 SDUse &Use = *UI;
13247 ++UI;
13248 Use.set(To);
13249 if (To->isDivergent() != From->isDivergent())
13251 } while (UI != UE && UI->getUser() == User);
13252 // Now that we have modified User, add it back to the CSE maps. If it
13253 // already exists there, recursively merge the results together.
13254 AddModifiedNodeToCSEMaps(User);
13255 }
13256
13257 // If we just RAUW'd the root, take note.
13258 if (FromN == getRoot())
13259 setRoot(To);
13260}
13261
13262/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13263/// This can cause recursive merging of nodes in the DAG.
13264///
13265/// This version assumes that for each value of From, there is a
13266/// corresponding value in To in the same position with the same type.
13267///
13269#ifndef NDEBUG
13270 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13271 assert((!From->hasAnyUseOfValue(i) ||
13272 From->getValueType(i) == To->getValueType(i)) &&
13273 "Cannot use this version of ReplaceAllUsesWith!");
13274#endif
13275
13276 // Handle the trivial case.
13277 if (From == To)
13278 return;
13279
13280 // Preserve Debug Info. Only do this if there's a use.
13281 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13282 if (From->hasAnyUseOfValue(i)) {
13283 assert((i < To->getNumValues()) && "Invalid To location");
13284 transferDbgValues(SDValue(From, i), SDValue(To, i));
13285 }
13286 // Preserve extra info.
13287 copyExtraInfo(From, To);
13288
13289 // Iterate over just the existing users of From. See the comments in
13290 // the ReplaceAllUsesWith above.
13291 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13292 RAUWUpdateListener Listener(*this, UI, UE);
13293 while (UI != UE) {
13294 SDNode *User = UI->getUser();
13295
13296 // This node is about to morph, remove its old self from the CSE maps.
13297 RemoveNodeFromCSEMaps(User);
13298
13299 // A user can appear in a use list multiple times, and when this
13300 // happens the uses are usually next to each other in the list.
13301 // To help reduce the number of CSE recomputations, process all
13302 // the uses of this user that we can find this way.
13303 do {
13304 SDUse &Use = *UI;
13305 ++UI;
13306 Use.setNode(To);
13307 if (To->isDivergent() != From->isDivergent())
13309 } while (UI != UE && UI->getUser() == User);
13310
13311 // Now that we have modified User, add it back to the CSE maps. If it
13312 // already exists there, recursively merge the results together.
13313 AddModifiedNodeToCSEMaps(User);
13314 }
13315
13316 // If we just RAUW'd the root, take note.
13317 if (From == getRoot().getNode())
13318 setRoot(SDValue(To, getRoot().getResNo()));
13319}
13320
13321/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13322/// This can cause recursive merging of nodes in the DAG.
13323///
13324/// This version can replace From with any result values. To must match the
13325/// number and types of values returned by From.
13327 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13328 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13329
13330 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13331 // Preserve Debug Info.
13332 transferDbgValues(SDValue(From, i), To[i]);
13333 // Preserve extra info.
13334 copyExtraInfo(From, To[i].getNode());
13335 }
13336
13337 // Iterate over just the existing users of From. See the comments in
13338 // the ReplaceAllUsesWith above.
13339 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13340 RAUWUpdateListener Listener(*this, UI, UE);
13341 while (UI != UE) {
13342 SDNode *User = UI->getUser();
13343
13344 // This node is about to morph, remove its old self from the CSE maps.
13345 RemoveNodeFromCSEMaps(User);
13346
13347 // A user can appear in a use list multiple times, and when this happens the
13348 // uses are usually next to each other in the list. To help reduce the
13349 // number of CSE and divergence recomputations, process all the uses of this
13350 // user that we can find this way.
13351 bool To_IsDivergent = false;
13352 do {
13353 SDUse &Use = *UI;
13354 const SDValue &ToOp = To[Use.getResNo()];
13355 ++UI;
13356 Use.set(ToOp);
13357 if (ToOp.getValueType() != MVT::Other)
13358 To_IsDivergent |= ToOp->isDivergent();
13359 } while (UI != UE && UI->getUser() == User);
13360
13361 if (To_IsDivergent != From->isDivergent())
13363
13364 // Now that we have modified User, add it back to the CSE maps. If it
13365 // already exists there, recursively merge the results together.
13366 AddModifiedNodeToCSEMaps(User);
13367 }
13368
13369 // If we just RAUW'd the root, take note.
13370 if (From == getRoot().getNode())
13371 setRoot(SDValue(To[getRoot().getResNo()]));
13372}
13373
13374/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13375/// uses of other values produced by From.getNode() alone. The Deleted
13376/// vector is handled the same way as for ReplaceAllUsesWith.
13378 // Handle the really simple, really trivial case efficiently.
13379 if (From == To) return;
13380
13381 // Handle the simple, trivial, case efficiently.
13382 if (From.getNode()->getNumValues() == 1) {
13383 ReplaceAllUsesWith(From, To);
13384 return;
13385 }
13386
13387 // Preserve Debug Info.
13388 transferDbgValues(From, To);
13389 copyExtraInfo(From.getNode(), To.getNode());
13390
13391 // Iterate over just the existing users of From. See the comments in
13392 // the ReplaceAllUsesWith above.
13393 SDNode::use_iterator UI = From.getNode()->use_begin(),
13394 UE = From.getNode()->use_end();
13395 RAUWUpdateListener Listener(*this, UI, UE);
13396 while (UI != UE) {
13397 SDNode *User = UI->getUser();
13398 bool UserRemovedFromCSEMaps = false;
13399
13400 // A user can appear in a use list multiple times, and when this
13401 // happens the uses are usually next to each other in the list.
13402 // To help reduce the number of CSE recomputations, process all
13403 // the uses of this user that we can find this way.
13404 do {
13405 SDUse &Use = *UI;
13406
13407 // Skip uses of different values from the same node.
13408 if (Use.getResNo() != From.getResNo()) {
13409 ++UI;
13410 continue;
13411 }
13412
13413 // If this node hasn't been modified yet, it's still in the CSE maps,
13414 // so remove its old self from the CSE maps.
13415 if (!UserRemovedFromCSEMaps) {
13416 RemoveNodeFromCSEMaps(User);
13417 UserRemovedFromCSEMaps = true;
13418 }
13419
13420 ++UI;
13421 Use.set(To);
13422 if (To->isDivergent() != From->isDivergent())
13424 } while (UI != UE && UI->getUser() == User);
13425 // We are iterating over all uses of the From node, so if a use
13426 // doesn't use the specific value, no changes are made.
13427 if (!UserRemovedFromCSEMaps)
13428 continue;
13429
13430 // Now that we have modified User, add it back to the CSE maps. If it
13431 // already exists there, recursively merge the results together.
13432 AddModifiedNodeToCSEMaps(User);
13433 }
13434
13435 // If we just RAUW'd the root, take note.
13436 if (From == getRoot())
13437 setRoot(To);
13438}
13439
13440namespace {
13441
13442/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13443/// to record information about a use.
13444struct UseMemo {
13445 SDNode *User;
13446 unsigned Index;
13447 SDUse *Use;
13448};
13449
13450/// operator< - Sort Memos by User.
13451bool operator<(const UseMemo &L, const UseMemo &R) {
13452 return (intptr_t)L.User < (intptr_t)R.User;
13453}
13454
13455/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13456/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13457/// the node already has been taken care of recursively.
13458class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13459 SmallVectorImpl<UseMemo> &Uses;
13460
13461 void NodeDeleted(SDNode *N, SDNode *E) override {
13462 for (UseMemo &Memo : Uses)
13463 if (Memo.User == N)
13464 Memo.User = nullptr;
13465 }
13466
13467public:
13468 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13469 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13470};
13471
13472} // end anonymous namespace
13473
13474/// Return true if a glue output should propagate divergence information.
13476 switch (Node->getOpcode()) {
13477 case ISD::CopyFromReg:
13478 case ISD::CopyToReg:
13479 return false;
13480 default:
13481 return true;
13482 }
13483
13484 llvm_unreachable("covered opcode switch");
13485}
13486
13488 if (TLI->isSDNodeAlwaysUniform(N)) {
13489 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13490 "Conflicting divergence information!");
13491 return false;
13492 }
13493 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13494 return true;
13495 for (const auto &Op : N->ops()) {
13496 EVT VT = Op.getValueType();
13497
13498 // Skip Chain. It does not carry divergence.
13499 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13500 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13501 return true;
13502 }
13503 return false;
13504}
13505
13507 SmallVector<SDNode *, 16> Worklist(1, N);
13508 do {
13509 N = Worklist.pop_back_val();
13510 bool IsDivergent = calculateDivergence(N);
13511 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13512 N->SDNodeBits.IsDivergent = IsDivergent;
13513 llvm::append_range(Worklist, N->users());
13514 }
13515 } while (!Worklist.empty());
13516}
13517
13518void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13520 Order.reserve(AllNodes.size());
13521 for (auto &N : allnodes()) {
13522 unsigned NOps = N.getNumOperands();
13523 Degree[&N] = NOps;
13524 if (0 == NOps)
13525 Order.push_back(&N);
13526 }
13527 for (size_t I = 0; I != Order.size(); ++I) {
13528 SDNode *N = Order[I];
13529 for (auto *U : N->users()) {
13530 unsigned &UnsortedOps = Degree[U];
13531 if (0 == --UnsortedOps)
13532 Order.push_back(U);
13533 }
13534 }
13535}
13536
13537#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13538void SelectionDAG::VerifyDAGDivergence() {
13539 std::vector<SDNode *> TopoOrder;
13540 CreateTopologicalOrder(TopoOrder);
13541 for (auto *N : TopoOrder) {
13542 assert(calculateDivergence(N) == N->isDivergent() &&
13543 "Divergence bit inconsistency detected");
13544 }
13545}
13546#endif
13547
13548/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13549/// uses of other values produced by From.getNode() alone. The same value
13550/// may appear in both the From and To list. The Deleted vector is
13551/// handled the same way as for ReplaceAllUsesWith.
13553 const SDValue *To,
13554 unsigned Num){
13555 // Handle the simple, trivial case efficiently.
13556 if (Num == 1)
13557 return ReplaceAllUsesOfValueWith(*From, *To);
13558
13559 transferDbgValues(*From, *To);
13560 copyExtraInfo(From->getNode(), To->getNode());
13561
13562 // Read up all the uses and make records of them. This helps
13563 // processing new uses that are introduced during the
13564 // replacement process.
13566 for (unsigned i = 0; i != Num; ++i) {
13567 unsigned FromResNo = From[i].getResNo();
13568 SDNode *FromNode = From[i].getNode();
13569 for (SDUse &Use : FromNode->uses()) {
13570 if (Use.getResNo() == FromResNo) {
13571 UseMemo Memo = {Use.getUser(), i, &Use};
13572 Uses.push_back(Memo);
13573 }
13574 }
13575 }
13576
13577 // Sort the uses, so that all the uses from a given User are together.
13579 RAUOVWUpdateListener Listener(*this, Uses);
13580
13581 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13582 UseIndex != UseIndexEnd; ) {
13583 // We know that this user uses some value of From. If it is the right
13584 // value, update it.
13585 SDNode *User = Uses[UseIndex].User;
13586 // If the node has been deleted by recursive CSE updates when updating
13587 // another node, then just skip this entry.
13588 if (User == nullptr) {
13589 ++UseIndex;
13590 continue;
13591 }
13592
13593 // This node is about to morph, remove its old self from the CSE maps.
13594 RemoveNodeFromCSEMaps(User);
13595
13596 // The Uses array is sorted, so all the uses for a given User
13597 // are next to each other in the list.
13598 // To help reduce the number of CSE recomputations, process all
13599 // the uses of this user that we can find this way.
13600 do {
13601 unsigned i = Uses[UseIndex].Index;
13602 SDUse &Use = *Uses[UseIndex].Use;
13603 ++UseIndex;
13604
13605 Use.set(To[i]);
13606 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13607
13608 // Now that we have modified User, add it back to the CSE maps. If it
13609 // already exists there, recursively merge the results together.
13610 AddModifiedNodeToCSEMaps(User);
13611 }
13612}
13613
13614/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13615/// based on their topological order. It returns the maximum id and a vector
13616/// of the SDNodes* in assigned order by reference.
13618 unsigned DAGSize = 0;
13619
13620 // SortedPos tracks the progress of the algorithm. Nodes before it are
13621 // sorted, nodes after it are unsorted. When the algorithm completes
13622 // it is at the end of the list.
13623 allnodes_iterator SortedPos = allnodes_begin();
13624
13625 // Visit all the nodes. Move nodes with no operands to the front of
13626 // the list immediately. Annotate nodes that do have operands with their
13627 // operand count. Before we do this, the Node Id fields of the nodes
13628 // may contain arbitrary values. After, the Node Id fields for nodes
13629 // before SortedPos will contain the topological sort index, and the
13630 // Node Id fields for nodes At SortedPos and after will contain the
13631 // count of outstanding operands.
13633 checkForCycles(&N, this);
13634 unsigned Degree = N.getNumOperands();
13635 if (Degree == 0) {
13636 // A node with no uses, add it to the result array immediately.
13637 N.setNodeId(DAGSize++);
13638 allnodes_iterator Q(&N);
13639 if (Q != SortedPos)
13640 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13641 assert(SortedPos != AllNodes.end() && "Overran node list");
13642 ++SortedPos;
13643 } else {
13644 // Temporarily use the Node Id as scratch space for the degree count.
13645 N.setNodeId(Degree);
13646 }
13647 }
13648
13649 // Visit all the nodes. As we iterate, move nodes into sorted order,
13650 // such that by the time the end is reached all nodes will be sorted.
13651 for (SDNode &Node : allnodes()) {
13652 SDNode *N = &Node;
13653 checkForCycles(N, this);
13654 // N is in sorted position, so all its uses have one less operand
13655 // that needs to be sorted.
13656 for (SDNode *P : N->users()) {
13657 unsigned Degree = P->getNodeId();
13658 assert(Degree != 0 && "Invalid node degree");
13659 --Degree;
13660 if (Degree == 0) {
13661 // All of P's operands are sorted, so P may sorted now.
13662 P->setNodeId(DAGSize++);
13663 if (P->getIterator() != SortedPos)
13664 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13665 assert(SortedPos != AllNodes.end() && "Overran node list");
13666 ++SortedPos;
13667 } else {
13668 // Update P's outstanding operand count.
13669 P->setNodeId(Degree);
13670 }
13671 }
13672 if (Node.getIterator() == SortedPos) {
13673#ifndef NDEBUG
13675 SDNode *S = &*++I;
13676 dbgs() << "Overran sorted position:\n";
13677 S->dumprFull(this); dbgs() << "\n";
13678 dbgs() << "Checking if this is due to cycles\n";
13679 checkForCycles(this, true);
13680#endif
13681 llvm_unreachable(nullptr);
13682 }
13683 }
13684
13685 assert(SortedPos == AllNodes.end() &&
13686 "Topological sort incomplete!");
13687 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13688 "First node in topological sort is not the entry token!");
13689 assert(AllNodes.front().getNodeId() == 0 &&
13690 "First node in topological sort has non-zero id!");
13691 assert(AllNodes.front().getNumOperands() == 0 &&
13692 "First node in topological sort has operands!");
13693 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13694 "Last node in topologic sort has unexpected id!");
13695 assert(AllNodes.back().use_empty() &&
13696 "Last node in topologic sort has users!");
13697 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13698 return DAGSize;
13699}
13700
13702 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13703 SortedNodes.clear();
13704 // Node -> remaining number of outstanding operands.
13705 DenseMap<const SDNode *, unsigned> RemainingOperands;
13706
13707 // Put nodes without any operands into SortedNodes first.
13708 for (const SDNode &N : allnodes()) {
13709 checkForCycles(&N, this);
13710 unsigned NumOperands = N.getNumOperands();
13711 if (NumOperands == 0)
13712 SortedNodes.push_back(&N);
13713 else
13714 // Record their total number of outstanding operands.
13715 RemainingOperands[&N] = NumOperands;
13716 }
13717
13718 // A node is pushed into SortedNodes when all of its operands (predecessors in
13719 // the graph) are also in SortedNodes.
13720 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13721 const SDNode *N = SortedNodes[i];
13722 for (const SDNode *U : N->users()) {
13723 // HandleSDNode is never part of a DAG and therefore has no entry in
13724 // RemainingOperands.
13725 if (U->getOpcode() == ISD::HANDLENODE)
13726 continue;
13727 unsigned &NumRemOperands = RemainingOperands[U];
13728 assert(NumRemOperands && "Invalid number of remaining operands");
13729 --NumRemOperands;
13730 if (!NumRemOperands)
13731 SortedNodes.push_back(U);
13732 }
13733 }
13734
13735 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13736 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13737 "First node in topological sort is not the entry token");
13738 assert(SortedNodes.front()->getNumOperands() == 0 &&
13739 "First node in topological sort has operands");
13740}
13741
13742/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13743/// value is produced by SD.
13744void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13745 for (SDNode *SD : DB->getSDNodes()) {
13746 if (!SD)
13747 continue;
13748 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13749 SD->setHasDebugValue(true);
13750 }
13751 DbgInfo->add(DB, isParameter);
13752}
13753
13754void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13755
13757 SDValue NewMemOpChain) {
13758 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13759 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13760 // The new memory operation must have the same position as the old load in
13761 // terms of memory dependency. Create a TokenFactor for the old load and new
13762 // memory operation and update uses of the old load's output chain to use that
13763 // TokenFactor.
13764 if (OldChain == NewMemOpChain || OldChain.use_empty())
13765 return NewMemOpChain;
13766
13767 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13768 OldChain, NewMemOpChain);
13769 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13770 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13771 return TokenFactor;
13772}
13773
13775 SDValue NewMemOp) {
13776 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13777 SDValue OldChain = SDValue(OldLoad, 1);
13778 SDValue NewMemOpChain = NewMemOp.getValue(1);
13779 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13780}
13781
13783 Function **OutFunction) {
13784 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13785
13786 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13787 auto *Module = MF->getFunction().getParent();
13788 auto *Function = Module->getFunction(Symbol);
13789
13790 if (OutFunction != nullptr)
13791 *OutFunction = Function;
13792
13793 if (Function != nullptr) {
13794 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13795 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13796 }
13797
13798 std::string ErrorStr;
13799 raw_string_ostream ErrorFormatter(ErrorStr);
13800 ErrorFormatter << "Undefined external symbol ";
13801 ErrorFormatter << '"' << Symbol << '"';
13802 report_fatal_error(Twine(ErrorStr));
13803}
13804
13805//===----------------------------------------------------------------------===//
13806// SDNode Class
13807//===----------------------------------------------------------------------===//
13808
13811 return Const != nullptr && Const->isZero();
13812}
13813
13815 return V.isUndef() || isNullConstant(V);
13816}
13817
13820 return Const != nullptr && Const->isZero() && !Const->isNegative();
13821}
13822
13825 return Const != nullptr && Const->isAllOnes();
13826}
13827
13830 return Const != nullptr && Const->isOne();
13831}
13832
13835 return Const != nullptr && Const->isMinSignedValue();
13836}
13837
13839 SDValue V, unsigned OperandNo,
13840 unsigned Depth) const {
13841 APInt DemandedElts = getDemandAllEltsMask(V);
13842 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13843}
13844
13846 SDValue V, const APInt &DemandedElts,
13847 unsigned OperandNo, unsigned Depth) const {
13848 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13849 // TODO: Target-specific opcodes could be added.
13850 if (V.getValueType().isInteger()) {
13851 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13852 if (Known.isConstant()) {
13853 const APInt &Const = Known.getConstant();
13854 switch (Opcode) {
13855 case ISD::ADD:
13856 case ISD::OR:
13857 case ISD::XOR:
13858 case ISD::UMAX:
13859 return Const.isZero();
13860 case ISD::MUL:
13861 return Const.isOne();
13862 case ISD::AND:
13863 case ISD::UMIN:
13864 return Const.isAllOnes();
13865 case ISD::SMAX:
13866 return Const.isMinSignedValue();
13867 case ISD::SMIN:
13868 return Const.isMaxSignedValue();
13869 case ISD::SUB:
13870 case ISD::SHL:
13871 case ISD::SRA:
13872 case ISD::SRL:
13873 return OperandNo == 1 && Const.isZero();
13874 case ISD::UDIV:
13875 case ISD::SDIV:
13876 return OperandNo == 1 && Const.isOne();
13877 }
13878 }
13879 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13880 switch (Opcode) {
13881 case ISD::FADD:
13882 return ConstFP->isZero() &&
13883 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13884 case ISD::FSUB:
13885 return OperandNo == 1 && ConstFP->isZero() &&
13886 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13887 case ISD::FMUL:
13888 return ConstFP->isOne();
13889 case ISD::FDIV:
13890 return OperandNo == 1 && ConstFP->isOne();
13891 case ISD::FMINNUM:
13892 case ISD::FMAXNUM: {
13893 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
13894 EVT VT = V.getValueType();
13895 const fltSemantics &Semantics = VT.getFltSemantics();
13896 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13897 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13898 : APFloat::getLargest(Semantics);
13899 if (Opcode == ISD::FMAXNUM)
13900 NeutralAF.changeSign();
13901
13902 return ConstFP->isExactlyValue(NeutralAF);
13903 }
13904 case ISD::FMINIMUM:
13905 case ISD::FMAXIMUM: {
13906 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
13907 const APFloat &VAPF = ConstFP->getValueAPF();
13908 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
13909 if (Flags.hasNoInfs())
13910 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
13911 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
13912 }
13913 }
13914 }
13915 return false;
13916}
13917
13919 while (V.getOpcode() == ISD::BITCAST)
13920 V = V.getOperand(0);
13921 return V;
13922}
13923
13925 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
13926 V = V.getOperand(0);
13927 return V;
13928}
13929
13931 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13932 V = V.getOperand(0);
13933 return V;
13934}
13935
13937 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13938 SDValue InVec = V.getOperand(0);
13939 SDValue EltNo = V.getOperand(2);
13940 EVT VT = InVec.getValueType();
13941 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
13942 if (IndexC && VT.isFixedLengthVector() &&
13943 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
13944 !DemandedElts[IndexC->getZExtValue()]) {
13945 V = InVec;
13946 continue;
13947 }
13948 break;
13949 }
13950 return V;
13951}
13952
13954 while (V.getOpcode() == ISD::TRUNCATE)
13955 V = V.getOperand(0);
13956 return V;
13957}
13958
13959bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
13960 if (V.getOpcode() != ISD::XOR)
13961 return false;
13962 V = peekThroughBitcasts(V.getOperand(1));
13963 unsigned NumBits = V.getScalarValueSizeInBits();
13964 ConstantSDNode *C =
13965 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
13966 return C && (C->getAPIntValue().countr_one() >= NumBits);
13967}
13968
13970 bool AllowTruncation) {
13971 APInt DemandedElts = getDemandAllEltsMask(N);
13972 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
13973}
13974
13976 bool AllowUndefs,
13977 bool AllowTruncation) {
13979 return CN;
13980
13981 // SplatVectors can truncate their operands. Ignore that case here unless
13982 // AllowTruncation is set.
13983 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
13984 EVT VecEltVT = N->getValueType(0).getVectorElementType();
13985 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13986 EVT CVT = CN->getValueType(0);
13987 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
13988 if (AllowTruncation || CVT == VecEltVT)
13989 return CN;
13990 }
13991 }
13992
13994 BitVector UndefElements;
13995 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
13996
13997 // BuildVectors can truncate their operands. Ignore that case here unless
13998 // AllowTruncation is set.
13999 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14000 if (CN && (UndefElements.none() || AllowUndefs)) {
14001 EVT CVT = CN->getValueType(0);
14002 EVT NSVT = N.getValueType().getScalarType();
14003 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14004 if (AllowTruncation || (CVT == NSVT))
14005 return CN;
14006 }
14007 }
14008
14009 return nullptr;
14010}
14011
14013 APInt DemandedElts = getDemandAllEltsMask(N);
14014 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14015}
14016
14018 const APInt &DemandedElts,
14019 bool AllowUndefs) {
14021 return CN;
14022
14024 BitVector UndefElements;
14025 ConstantFPSDNode *CN =
14026 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14027 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14028 if (CN && (UndefElements.none() || AllowUndefs))
14029 return CN;
14030 }
14031
14032 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14033 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14034 return CN;
14035
14036 return nullptr;
14037}
14038
14039bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14040 // TODO: may want to use peekThroughBitcast() here.
14041 ConstantSDNode *C =
14042 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14043 return C && C->isZero();
14044}
14045
14046bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14047 ConstantSDNode *C =
14048 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14049 return C && C->isOne();
14050}
14051
14052bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14053 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14054 return C && C->isOne();
14055}
14056
14057bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14059 unsigned BitWidth = N.getScalarValueSizeInBits();
14060 ConstantSDNode *C =
14061 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14062 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14063}
14064
14065bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
14066 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
14067 return C && APInt::isSameValue(C->getAPIntValue(),
14068 APInt(C->getAPIntValue().getBitWidth(), 1));
14069}
14070
14071bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14073 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14074 return C && C->isZero();
14075}
14076
14077bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14078 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14079 return C && C->isZero();
14080}
14081
14085
14087 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14089 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14090 bool IsVolatile = false;
14091 bool IsNonTemporal = false;
14092 bool IsDereferenceable = true;
14093 bool IsInvariant = true;
14094 for (const MachineMemOperand *MMO : memoperands()) {
14095 IsVolatile |= MMO->isVolatile();
14096 IsNonTemporal |= MMO->isNonTemporal();
14097 IsDereferenceable &= MMO->isDereferenceable();
14098 IsInvariant &= MMO->isInvariant();
14099 }
14100 MemSDNodeBits.IsVolatile = IsVolatile;
14101 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14102 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14103 MemSDNodeBits.IsInvariant = IsInvariant;
14104
14105 // For the single-MMO case, we check here that the size of the memory operand
14106 // fits within the size of the MMO. This is because the MMO might indicate
14107 // only a possible address range instead of specifying the affected memory
14108 // addresses precisely.
14111 getMemOperand()->getSize().getValue())) &&
14112 "Size mismatch!");
14113}
14114
14115/// Profile - Gather unique data for the node.
14116///
14118 AddNodeIDNode(ID, this);
14119}
14120
14121namespace {
14122
14123 struct EVTArray {
14124 std::vector<EVT> VTs;
14125
14126 EVTArray() {
14127 VTs.reserve(MVT::VALUETYPE_SIZE);
14128 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14129 VTs.push_back(MVT((MVT::SimpleValueType)i));
14130 }
14131 };
14132
14133} // end anonymous namespace
14134
14135/// getValueTypeList - Return a pointer to the specified value type.
14136///
14137const EVT *SDNode::getValueTypeList(MVT VT) {
14138 static EVTArray SimpleVTArray;
14139
14140 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14141 return &SimpleVTArray.VTs[VT.SimpleTy];
14142}
14143
14144/// hasAnyUseOfValue - Return true if there are any use of the indicated
14145/// value. This method ignores uses of other values defined by this operation.
14146bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14147 assert(Value < getNumValues() && "Bad value!");
14148
14149 for (SDUse &U : uses())
14150 if (U.getResNo() == Value)
14151 return true;
14152
14153 return false;
14154}
14155
14156/// isOnlyUserOf - Return true if this node is the only use of N.
14157bool SDNode::isOnlyUserOf(const SDNode *N) const {
14158 bool Seen = false;
14159 for (const SDNode *User : N->users()) {
14160 if (User == this)
14161 Seen = true;
14162 else
14163 return false;
14164 }
14165
14166 return Seen;
14167}
14168
14169/// Return true if the only users of N are contained in Nodes.
14171 bool Seen = false;
14172 for (const SDNode *User : N->users()) {
14173 if (llvm::is_contained(Nodes, User))
14174 Seen = true;
14175 else
14176 return false;
14177 }
14178
14179 return Seen;
14180}
14181
14182/// Return true if the referenced return value is an operand of N.
14183bool SDValue::isOperandOf(const SDNode *N) const {
14184 return is_contained(N->op_values(), *this);
14185}
14186
14187bool SDNode::isOperandOf(const SDNode *N) const {
14188 return any_of(N->op_values(),
14189 [this](SDValue Op) { return this == Op.getNode(); });
14190}
14191
14192/// reachesChainWithoutSideEffects - Return true if this operand (which must
14193/// be a chain) reaches the specified operand without crossing any
14194/// side-effecting instructions on any chain path. In practice, this looks
14195/// through token factors and non-volatile loads. In order to remain efficient,
14196/// this only looks a couple of nodes in, it does not do an exhaustive search.
14197///
14198/// Note that we only need to examine chains when we're searching for
14199/// side-effects; SelectionDAG requires that all side-effects are represented
14200/// by chains, even if another operand would force a specific ordering. This
14201/// constraint is necessary to allow transformations like splitting loads.
14203 unsigned Depth) const {
14204 if (*this == Dest) return true;
14205
14206 // Don't search too deeply, we just want to be able to see through
14207 // TokenFactor's etc.
14208 if (Depth == 0) return false;
14209
14210 // If this is a token factor, all inputs to the TF happen in parallel.
14211 if (getOpcode() == ISD::TokenFactor) {
14212 // First, try a shallow search.
14213 if (is_contained((*this)->ops(), Dest)) {
14214 // We found the chain we want as an operand of this TokenFactor.
14215 // Essentially, we reach the chain without side-effects if we could
14216 // serialize the TokenFactor into a simple chain of operations with
14217 // Dest as the last operation. This is automatically true if the
14218 // chain has one use: there are no other ordering constraints.
14219 // If the chain has more than one use, we give up: some other
14220 // use of Dest might force a side-effect between Dest and the current
14221 // node.
14222 if (Dest.hasOneUse())
14223 return true;
14224 }
14225 // Next, try a deep search: check whether every operand of the TokenFactor
14226 // reaches Dest.
14227 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14228 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14229 });
14230 }
14231
14232 // Loads don't have side effects, look through them.
14233 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14234 if (Ld->isUnordered())
14235 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14236 }
14237 return false;
14238}
14239
14240bool SDNode::hasPredecessor(const SDNode *N) const {
14243 Worklist.push_back(this);
14244 return hasPredecessorHelper(N, Visited, Worklist);
14245}
14246
14248 this->Flags &= Flags;
14249}
14250
14251SDValue
14253 ArrayRef<ISD::NodeType> CandidateBinOps,
14254 bool AllowPartials) {
14255 // The pattern must end in an extract from index 0.
14256 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14257 !isNullConstant(Extract->getOperand(1)))
14258 return SDValue();
14259
14260 // Match against one of the candidate binary ops.
14261 SDValue Op = Extract->getOperand(0);
14262 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14263 return Op.getOpcode() == unsigned(BinOp);
14264 }))
14265 return SDValue();
14266
14267 // Floating-point reductions may require relaxed constraints on the final step
14268 // of the reduction because they may reorder intermediate operations.
14269 unsigned CandidateBinOp = Op.getOpcode();
14270 if (Op.getValueType().isFloatingPoint()) {
14271 SDNodeFlags Flags = Op->getFlags();
14272 switch (CandidateBinOp) {
14273 case ISD::FADD:
14274 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14275 return SDValue();
14276 break;
14277 default:
14278 llvm_unreachable("Unhandled FP opcode for binop reduction");
14279 }
14280 }
14281
14282 // Matching failed - attempt to see if we did enough stages that a partial
14283 // reduction from a subvector is possible.
14284 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14285 if (!AllowPartials || !Op)
14286 return SDValue();
14287 EVT OpVT = Op.getValueType();
14288 EVT OpSVT = OpVT.getScalarType();
14289 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14290 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14292 return SDValue();
14293 BinOp = (ISD::NodeType)CandidateBinOp;
14294 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14295 };
14296
14297 // At each stage, we're looking for something that looks like:
14298 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14299 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14300 // i32 undef, i32 undef, i32 undef, i32 undef>
14301 // %a = binop <8 x i32> %op, %s
14302 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14303 // we expect something like:
14304 // <4,5,6,7,u,u,u,u>
14305 // <2,3,u,u,u,u,u,u>
14306 // <1,u,u,u,u,u,u,u>
14307 // While a partial reduction match would be:
14308 // <2,3,u,u,u,u,u,u>
14309 // <1,u,u,u,u,u,u,u>
14310 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14311 SDValue PrevOp;
14312 for (unsigned i = 0; i < Stages; ++i) {
14313 unsigned MaskEnd = (1 << i);
14314
14315 if (Op.getOpcode() != CandidateBinOp)
14316 return PartialReduction(PrevOp, MaskEnd);
14317
14318 SDValue Op0 = Op.getOperand(0);
14319 SDValue Op1 = Op.getOperand(1);
14320
14322 if (Shuffle) {
14323 Op = Op1;
14324 } else {
14325 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14326 Op = Op0;
14327 }
14328
14329 // The first operand of the shuffle should be the same as the other operand
14330 // of the binop.
14331 if (!Shuffle || Shuffle->getOperand(0) != Op)
14332 return PartialReduction(PrevOp, MaskEnd);
14333
14334 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14335 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14336 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14337 return PartialReduction(PrevOp, MaskEnd);
14338
14339 PrevOp = Op;
14340 }
14341
14342 // Handle subvector reductions, which tend to appear after the shuffle
14343 // reduction stages.
14344 while (Op.getOpcode() == CandidateBinOp) {
14345 unsigned NumElts = Op.getValueType().getVectorNumElements();
14346 SDValue Op0 = Op.getOperand(0);
14347 SDValue Op1 = Op.getOperand(1);
14348 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14350 Op0.getOperand(0) != Op1.getOperand(0))
14351 break;
14352 SDValue Src = Op0.getOperand(0);
14353 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14354 if (NumSrcElts != (2 * NumElts))
14355 break;
14356 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14357 Op1.getConstantOperandAPInt(1) == NumElts) &&
14358 !(Op1.getConstantOperandAPInt(1) == 0 &&
14359 Op0.getConstantOperandAPInt(1) == NumElts))
14360 break;
14361 Op = Src;
14362 }
14363
14364 BinOp = (ISD::NodeType)CandidateBinOp;
14365 return Op;
14366}
14367
14369 EVT VT = N->getValueType(0);
14370 EVT EltVT = VT.getVectorElementType();
14371 unsigned NE = VT.getVectorNumElements();
14372
14373 SDLoc dl(N);
14374
14375 // If ResNE is 0, fully unroll the vector op.
14376 if (ResNE == 0)
14377 ResNE = NE;
14378 else if (NE > ResNE)
14379 NE = ResNE;
14380
14381 if (N->getNumValues() == 2) {
14382 SmallVector<SDValue, 8> Scalars0, Scalars1;
14383 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14384 EVT VT1 = N->getValueType(1);
14385 EVT EltVT1 = VT1.getVectorElementType();
14386
14387 unsigned i;
14388 for (i = 0; i != NE; ++i) {
14389 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14390 SDValue Operand = N->getOperand(j);
14391 EVT OperandVT = Operand.getValueType();
14392
14393 // A vector operand; extract a single element.
14394 EVT OperandEltVT = OperandVT.getVectorElementType();
14395 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14396 }
14397
14398 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14399 Scalars0.push_back(EltOp);
14400 Scalars1.push_back(EltOp.getValue(1));
14401 }
14402
14403 for (; i < ResNE; ++i) {
14404 Scalars0.push_back(getUNDEF(EltVT));
14405 Scalars1.push_back(getUNDEF(EltVT1));
14406 }
14407
14408 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14409 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResNE);
14410 SDValue Vec0 = getBuildVector(VecVT, dl, Scalars0);
14411 SDValue Vec1 = getBuildVector(VecVT1, dl, Scalars1);
14412 return getMergeValues({Vec0, Vec1}, dl);
14413 }
14414
14415 assert(N->getNumValues() == 1 &&
14416 "Can't unroll a vector with multiple results!");
14417
14419 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14420
14421 unsigned i;
14422 for (i= 0; i != NE; ++i) {
14423 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14424 SDValue Operand = N->getOperand(j);
14425 EVT OperandVT = Operand.getValueType();
14426 if (OperandVT.isVector()) {
14427 // A vector operand; extract a single element.
14428 EVT OperandEltVT = OperandVT.getVectorElementType();
14429 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14430 } else {
14431 // A scalar operand; just use it as is.
14432 Operands[j] = Operand;
14433 }
14434 }
14435
14436 switch (N->getOpcode()) {
14437 default: {
14438 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14439 N->getFlags()));
14440 break;
14441 }
14442 case ISD::VSELECT:
14443 Scalars.push_back(
14444 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14445 break;
14446 case ISD::SHL:
14447 case ISD::SRA:
14448 case ISD::SRL:
14449 case ISD::ROTL:
14450 case ISD::ROTR:
14451 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14453 Operands[1])));
14454 break;
14456 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14457 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14458 Operands[0],
14459 getValueType(ExtVT)));
14460 break;
14461 }
14462 case ISD::ADDRSPACECAST: {
14463 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14464 Scalars.push_back(getAddrSpaceCast(dl, EltVT, Operands[0],
14465 ASC->getSrcAddressSpace(),
14466 ASC->getDestAddressSpace()));
14467 break;
14468 }
14469 }
14470 }
14471
14472 for (; i < ResNE; ++i)
14473 Scalars.push_back(getUNDEF(EltVT));
14474
14475 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14476 return getBuildVector(VecVT, dl, Scalars);
14477}
14478
14479std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14480 SDNode *N, unsigned ResNE) {
14481 unsigned Opcode = N->getOpcode();
14482 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14483 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14484 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14485 "Expected an overflow opcode");
14486
14487 EVT ResVT = N->getValueType(0);
14488 EVT OvVT = N->getValueType(1);
14489 EVT ResEltVT = ResVT.getVectorElementType();
14490 EVT OvEltVT = OvVT.getVectorElementType();
14491 SDLoc dl(N);
14492
14493 // If ResNE is 0, fully unroll the vector op.
14494 unsigned NE = ResVT.getVectorNumElements();
14495 if (ResNE == 0)
14496 ResNE = NE;
14497 else if (NE > ResNE)
14498 NE = ResNE;
14499
14500 SmallVector<SDValue, 8> LHSScalars;
14501 SmallVector<SDValue, 8> RHSScalars;
14502 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14503 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14504
14505 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14506 SDVTList VTs = getVTList(ResEltVT, SVT);
14507 SmallVector<SDValue, 8> ResScalars;
14508 SmallVector<SDValue, 8> OvScalars;
14509 for (unsigned i = 0; i < NE; ++i) {
14510 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14511 SDValue Ov =
14512 getSelect(dl, OvEltVT, Res.getValue(1),
14513 getBoolConstant(true, dl, OvEltVT, ResVT),
14514 getConstant(0, dl, OvEltVT));
14515
14516 ResScalars.push_back(Res);
14517 OvScalars.push_back(Ov);
14518 }
14519
14520 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14521 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14522
14523 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14524 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14525 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14526 getBuildVector(NewOvVT, dl, OvScalars));
14527}
14528
14531 unsigned Bytes,
14532 int Dist) const {
14533 if (LD->isVolatile() || Base->isVolatile())
14534 return false;
14535 // TODO: probably too restrictive for atomics, revisit
14536 if (!LD->isSimple())
14537 return false;
14538 if (LD->isIndexed() || Base->isIndexed())
14539 return false;
14540 if (LD->getChain() != Base->getChain())
14541 return false;
14542 EVT VT = LD->getMemoryVT();
14543 if (VT.getSizeInBits() / 8 != Bytes)
14544 return false;
14545
14546 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
14547 auto LocDecomp = BaseIndexOffset::match(LD, *this);
14548
14549 int64_t Offset = 0;
14550 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
14551 return (Dist * (int64_t)Bytes == Offset);
14552 return false;
14553}
14554
14555/// InferPtrAlignment - Infer alignment of a load / store address. Return
14556/// std::nullopt if it cannot be inferred.
14558 // If this is a GlobalAddress + cst, return the alignment.
14559 const GlobalValue *GV = nullptr;
14560 int64_t GVOffset = 0;
14561 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14562 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14563 KnownBits Known(PtrWidth);
14565 unsigned AlignBits = Known.countMinTrailingZeros();
14566 if (AlignBits)
14567 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
14568 }
14569
14570 // If this is a direct reference to a stack slot, use information about the
14571 // stack slot's alignment.
14572 int FrameIdx = INT_MIN;
14573 int64_t FrameOffset = 0;
14575 FrameIdx = FI->getIndex();
14576 } else if (isBaseWithConstantOffset(Ptr) &&
14578 // Handle FI+Cst
14579 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14580 FrameOffset = Ptr.getConstantOperandVal(1);
14581 }
14582
14583 if (FrameIdx != INT_MIN) {
14585 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14586 }
14587
14588 return std::nullopt;
14589}
14590
14591/// Split the scalar node with EXTRACT_ELEMENT using the provided
14592/// VTs and return the low/high part.
14593std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14594 const SDLoc &DL,
14595 const EVT &LoVT,
14596 const EVT &HiVT) {
14597 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14598 "Split node must be a scalar type");
14599 SDValue Lo =
14601 SDValue Hi =
14603 return std::make_pair(Lo, Hi);
14604}
14605
14606/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14607/// which is split (or expanded) into two not necessarily identical pieces.
14608std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14609 // Currently all types are split in half.
14610 EVT LoVT, HiVT;
14611 if (!VT.isVector())
14612 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14613 else
14614 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14615
14616 return std::make_pair(LoVT, HiVT);
14617}
14618
14619/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14620/// type, dependent on an enveloping VT that has been split into two identical
14621/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14622std::pair<EVT, EVT>
14624 bool *HiIsEmpty) const {
14625 EVT EltTp = VT.getVectorElementType();
14626 // Examples:
14627 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14628 // custom VL=9 with enveloping VL=8/8 yields 8/1
14629 // custom VL=10 with enveloping VL=8/8 yields 8/2
14630 // etc.
14631 ElementCount VTNumElts = VT.getVectorElementCount();
14632 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14633 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14634 "Mixing fixed width and scalable vectors when enveloping a type");
14635 EVT LoVT, HiVT;
14636 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14637 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14638 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14639 *HiIsEmpty = false;
14640 } else {
14641 // Flag that hi type has zero storage size, but return split envelop type
14642 // (this would be easier if vector types with zero elements were allowed).
14643 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14644 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14645 *HiIsEmpty = true;
14646 }
14647 return std::make_pair(LoVT, HiVT);
14648}
14649
14650/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14651/// low/high part.
14652std::pair<SDValue, SDValue>
14653SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14654 const EVT &HiVT) {
14655 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14656 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14657 "Splitting vector with an invalid mixture of fixed and scalable "
14658 "vector types");
14660 N.getValueType().getVectorMinNumElements() &&
14661 "More vector elements requested than available!");
14662 SDValue Lo, Hi;
14663 Lo = getExtractSubvector(DL, LoVT, N, 0);
14664 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14665 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14666 // IDX with the runtime scaling factor of the result vector type. For
14667 // fixed-width result vectors, that runtime scaling factor is 1.
14669 return std::make_pair(Lo, Hi);
14670}
14671
14672std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14673 const SDLoc &DL) {
14674 // Split the vector length parameter.
14675 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14676 EVT VT = N.getValueType();
14678 "Expecting the mask to be an evenly-sized vector");
14679 SDValue HalfNumElts = getElementCount(
14681 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14682 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14683 return std::make_pair(Lo, Hi);
14684}
14685
14686/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14688 EVT VT = N.getValueType();
14691 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14692}
14693
14696 unsigned Start, unsigned Count,
14697 EVT EltVT) {
14698 EVT VT = Op.getValueType();
14699 if (Count == 0)
14701 if (EltVT == EVT())
14702 EltVT = VT.getVectorElementType();
14703 SDLoc SL(Op);
14704 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14705 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14706 }
14707}
14708
14709// getAddressSpace - Return the address space this GlobalAddress belongs to.
14711 return getGlobal()->getType()->getAddressSpace();
14712}
14713
14716 return Val.MachineCPVal->getType();
14717 return Val.ConstVal->getType();
14718}
14719
14720bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14721 unsigned &SplatBitSize,
14722 bool &HasAnyUndefs,
14723 unsigned MinSplatBits,
14724 bool IsBigEndian) const {
14725 EVT VT = getValueType(0);
14726 assert(VT.isVector() && "Expected a vector type");
14727 unsigned VecWidth = VT.getSizeInBits();
14728 if (MinSplatBits > VecWidth)
14729 return false;
14730
14731 // FIXME: The widths are based on this node's type, but build vectors can
14732 // truncate their operands.
14733 SplatValue = APInt(VecWidth, 0);
14734 SplatUndef = APInt(VecWidth, 0);
14735
14736 // Get the bits. Bits with undefined values (when the corresponding element
14737 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14738 // in SplatValue. If any of the values are not constant, give up and return
14739 // false.
14740 unsigned int NumOps = getNumOperands();
14741 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14742 unsigned EltWidth = VT.getScalarSizeInBits();
14743
14744 for (unsigned j = 0; j < NumOps; ++j) {
14745 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14746 SDValue OpVal = getOperand(i);
14747 unsigned BitPos = j * EltWidth;
14748
14749 if (OpVal.isUndef())
14750 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14751 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14752 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14753 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14754 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14755 else
14756 return false;
14757 }
14758
14759 // The build_vector is all constants or undefs. Find the smallest element
14760 // size that splats the vector.
14761 HasAnyUndefs = (SplatUndef != 0);
14762
14763 // FIXME: This does not work for vectors with elements less than 8 bits.
14764 while (VecWidth > 8) {
14765 // If we can't split in half, stop here.
14766 if (VecWidth & 1)
14767 break;
14768
14769 unsigned HalfSize = VecWidth / 2;
14770 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14771 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14772 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14773 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14774
14775 // If the two halves do not match (ignoring undef bits), stop here.
14776 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14777 MinSplatBits > HalfSize)
14778 break;
14779
14780 SplatValue = HighValue | LowValue;
14781 SplatUndef = HighUndef & LowUndef;
14782
14783 VecWidth = HalfSize;
14784 }
14785
14786 // FIXME: The loop above only tries to split in halves. But if the input
14787 // vector for example is <3 x i16> it wouldn't be able to detect a
14788 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14789 // optimizations. I guess that back in the days when this helper was created
14790 // vectors normally was power-of-2 sized.
14791
14792 SplatBitSize = VecWidth;
14793 return true;
14794}
14795
14797 BitVector *UndefElements) const {
14798 unsigned NumOps = getNumOperands();
14799 if (UndefElements) {
14800 UndefElements->clear();
14801 UndefElements->resize(NumOps);
14802 }
14803 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14804 if (!DemandedElts)
14805 return SDValue();
14806 SDValue Splatted;
14807 for (unsigned i = 0; i != NumOps; ++i) {
14808 if (!DemandedElts[i])
14809 continue;
14810 SDValue Op = getOperand(i);
14811 if (Op.isUndef()) {
14812 if (UndefElements)
14813 (*UndefElements)[i] = true;
14814 } else if (!Splatted) {
14815 Splatted = Op;
14816 } else if (Splatted != Op) {
14817 return SDValue();
14818 }
14819 }
14820
14821 if (!Splatted) {
14822 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14823 assert(getOperand(FirstDemandedIdx).isUndef() &&
14824 "Can only have a splat without a constant for all undefs.");
14825 return getOperand(FirstDemandedIdx);
14826 }
14827
14828 return Splatted;
14829}
14830
14832 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14833 return getSplatValue(DemandedElts, UndefElements);
14834}
14835
14837 SmallVectorImpl<SDValue> &Sequence,
14838 BitVector *UndefElements) const {
14839 unsigned NumOps = getNumOperands();
14840 Sequence.clear();
14841 if (UndefElements) {
14842 UndefElements->clear();
14843 UndefElements->resize(NumOps);
14844 }
14845 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14846 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14847 return false;
14848
14849 // Set the undefs even if we don't find a sequence (like getSplatValue).
14850 if (UndefElements)
14851 for (unsigned I = 0; I != NumOps; ++I)
14852 if (DemandedElts[I] && getOperand(I).isUndef())
14853 (*UndefElements)[I] = true;
14854
14855 // Iteratively widen the sequence length looking for repetitions.
14856 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14857 Sequence.append(SeqLen, SDValue());
14858 for (unsigned I = 0; I != NumOps; ++I) {
14859 if (!DemandedElts[I])
14860 continue;
14861 SDValue &SeqOp = Sequence[I % SeqLen];
14863 if (Op.isUndef()) {
14864 if (!SeqOp)
14865 SeqOp = Op;
14866 continue;
14867 }
14868 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14869 Sequence.clear();
14870 break;
14871 }
14872 SeqOp = Op;
14873 }
14874 if (!Sequence.empty())
14875 return true;
14876 }
14877
14878 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14879 return false;
14880}
14881
14883 BitVector *UndefElements) const {
14884 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14885 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14886}
14887
14890 BitVector *UndefElements) const {
14892 getSplatValue(DemandedElts, UndefElements));
14893}
14894
14897 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14898}
14899
14902 BitVector *UndefElements) const {
14904 getSplatValue(DemandedElts, UndefElements));
14905}
14906
14911
14912int32_t
14914 uint32_t BitWidth) const {
14915 if (ConstantFPSDNode *CN =
14917 bool IsExact;
14918 APSInt IntVal(BitWidth);
14919 const APFloat &APF = CN->getValueAPF();
14920 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14921 APFloat::opOK ||
14922 !IsExact)
14923 return -1;
14924
14925 return IntVal.exactLogBase2();
14926 }
14927 return -1;
14928}
14929
14931 bool IsLittleEndian, unsigned DstEltSizeInBits,
14932 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
14933 // Early-out if this contains anything but Undef/Constant/ConstantFP.
14934 if (!isConstant())
14935 return false;
14936
14937 unsigned NumSrcOps = getNumOperands();
14938 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
14939 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14940 "Invalid bitcast scale");
14941
14942 // Extract raw src bits.
14943 SmallVector<APInt> SrcBitElements(NumSrcOps,
14944 APInt::getZero(SrcEltSizeInBits));
14945 BitVector SrcUndeElements(NumSrcOps, false);
14946
14947 for (unsigned I = 0; I != NumSrcOps; ++I) {
14949 if (Op.isUndef()) {
14950 SrcUndeElements.set(I);
14951 continue;
14952 }
14953 auto *CInt = dyn_cast<ConstantSDNode>(Op);
14954 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
14955 assert((CInt || CFP) && "Unknown constant");
14956 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
14957 : CFP->getValueAPF().bitcastToAPInt();
14958 }
14959
14960 // Recast to dst width.
14961 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
14962 SrcBitElements, UndefElements, SrcUndeElements);
14963 return true;
14964}
14965
14966void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
14967 unsigned DstEltSizeInBits,
14968 SmallVectorImpl<APInt> &DstBitElements,
14969 ArrayRef<APInt> SrcBitElements,
14970 BitVector &DstUndefElements,
14971 const BitVector &SrcUndefElements) {
14972 unsigned NumSrcOps = SrcBitElements.size();
14973 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
14974 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14975 "Invalid bitcast scale");
14976 assert(NumSrcOps == SrcUndefElements.size() &&
14977 "Vector size mismatch");
14978
14979 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
14980 DstUndefElements.clear();
14981 DstUndefElements.resize(NumDstOps, false);
14982 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
14983
14984 // Concatenate src elements constant bits together into dst element.
14985 if (SrcEltSizeInBits <= DstEltSizeInBits) {
14986 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
14987 for (unsigned I = 0; I != NumDstOps; ++I) {
14988 DstUndefElements.set(I);
14989 APInt &DstBits = DstBitElements[I];
14990 for (unsigned J = 0; J != Scale; ++J) {
14991 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14992 if (SrcUndefElements[Idx])
14993 continue;
14994 DstUndefElements.reset(I);
14995 const APInt &SrcBits = SrcBitElements[Idx];
14996 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
14997 "Illegal constant bitwidths");
14998 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
14999 }
15000 }
15001 return;
15002 }
15003
15004 // Split src element constant bits into dst elements.
15005 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15006 for (unsigned I = 0; I != NumSrcOps; ++I) {
15007 if (SrcUndefElements[I]) {
15008 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15009 continue;
15010 }
15011 const APInt &SrcBits = SrcBitElements[I];
15012 for (unsigned J = 0; J != Scale; ++J) {
15013 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15014 APInt &DstBits = DstBitElements[Idx];
15015 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15016 }
15017 }
15018}
15019
15021 for (const SDValue &Op : op_values()) {
15022 unsigned Opc = Op.getOpcode();
15023 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15024 return false;
15025 }
15026 return true;
15027}
15028
15029std::optional<std::pair<APInt, APInt>>
15031 unsigned NumOps = getNumOperands();
15032 if (NumOps < 2)
15033 return std::nullopt;
15034
15035 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15036 APInt Start, Stride;
15037 int FirstIdx = -1, SecondIdx = -1;
15038
15039 // Find the first two non-undef constant elements to determine Start and
15040 // Stride, then verify all remaining elements match the sequence.
15041 for (unsigned I = 0; I < NumOps; ++I) {
15043 if (Op->isUndef())
15044 continue;
15045 if (!isa<ConstantSDNode>(Op))
15046 return std::nullopt;
15047
15048 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15049 if (FirstIdx < 0) {
15050 FirstIdx = I;
15051 Start = Val;
15052 } else if (SecondIdx < 0) {
15053 SecondIdx = I;
15054 // Compute stride using modular arithmetic. Simple division would handle
15055 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15056 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15057 // Note that modular arithmetic is agnostic to signed/unsigned.
15058 unsigned IdxDiff = I - FirstIdx;
15059 APInt ValDiff = Val - Start;
15060
15061 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15062 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15063 if (ValDiff.countr_zero() < CommonPow2Bits)
15064 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15065 IdxDiff >>= CommonPow2Bits;
15066 ValDiff.lshrInPlace(CommonPow2Bits);
15067
15068 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15069 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15070 // one, but we could try all candidates to handle more cases.
15071 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15072 if (Stride.isZero())
15073 return std::nullopt;
15074
15075 // Step 3: Adjust Start based on the first defined element's index.
15076 Start -= Stride * FirstIdx;
15077 } else {
15078 // Verify this element matches the sequence.
15079 if (Val != Start + Stride * I)
15080 return std::nullopt;
15081 }
15082 }
15083
15084 // Need at least two defined elements.
15085 if (SecondIdx < 0)
15086 return std::nullopt;
15087
15088 return std::make_pair(Start, Stride);
15089}
15090
15092 // Find the first non-undef value in the shuffle mask.
15093 unsigned i, e;
15094 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15095 /* search */;
15096
15097 // If all elements are undefined, this shuffle can be considered a splat
15098 // (although it should eventually get simplified away completely).
15099 if (i == e)
15100 return true;
15101
15102 // Make sure all remaining elements are either undef or the same as the first
15103 // non-undef value.
15104 for (int Idx = Mask[i]; i != e; ++i)
15105 if (Mask[i] >= 0 && Mask[i] != Idx)
15106 return false;
15107 return true;
15108}
15109
15110// Returns true if it is a constant integer BuildVector or constant integer,
15111// possibly hidden by a bitcast.
15113 SDValue N, bool AllowOpaques) const {
15115
15116 if (auto *C = dyn_cast<ConstantSDNode>(N))
15117 return AllowOpaques || !C->isOpaque();
15118
15120 return true;
15121
15122 // Treat a GlobalAddress supporting constant offset folding as a
15123 // constant integer.
15124 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15125 if (GA->getOpcode() == ISD::GlobalAddress &&
15126 TLI->isOffsetFoldingLegal(GA))
15127 return true;
15128
15129 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15130 isa<ConstantSDNode>(N.getOperand(0)))
15131 return true;
15132 return false;
15133}
15134
15135// Returns true if it is a constant float BuildVector or constant float.
15138 return true;
15139
15141 return true;
15142
15143 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15144 isa<ConstantFPSDNode>(N.getOperand(0)))
15145 return true;
15146
15147 return false;
15148}
15149
15150std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15151 ConstantSDNode *Const =
15152 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15153 if (!Const)
15154 return std::nullopt;
15155
15156 EVT VT = N->getValueType(0);
15157 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15158 switch (TLI->getBooleanContents(N.getValueType())) {
15160 if (CVal.isOne())
15161 return true;
15162 if (CVal.isZero())
15163 return false;
15164 return std::nullopt;
15166 if (CVal.isAllOnes())
15167 return true;
15168 if (CVal.isZero())
15169 return false;
15170 return std::nullopt;
15172 return CVal[0];
15173 }
15174 llvm_unreachable("Unknown BooleanContent enum");
15175}
15176
15177void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15178 assert(!Node->OperandList && "Node already has operands");
15180 "too many operands to fit into SDNode");
15181 SDUse *Ops = OperandRecycler.allocate(
15182 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15183
15184 bool IsDivergent = false;
15185 for (unsigned I = 0; I != Vals.size(); ++I) {
15186 Ops[I].setUser(Node);
15187 Ops[I].setInitial(Vals[I]);
15188 EVT VT = Ops[I].getValueType();
15189
15190 // Skip Chain. It does not carry divergence.
15191 if (VT != MVT::Other &&
15192 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15193 Ops[I].getNode()->isDivergent()) {
15194 IsDivergent = true;
15195 }
15196 }
15197 Node->NumOperands = Vals.size();
15198 Node->OperandList = Ops;
15199 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15200 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15201 Node->SDNodeBits.IsDivergent = IsDivergent;
15202 }
15203 checkForCycles(Node);
15204}
15205
15208 size_t Limit = SDNode::getMaxNumOperands();
15209 while (Vals.size() > Limit) {
15210 unsigned SliceIdx = Vals.size() - Limit;
15211 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15212 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15213 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15214 Vals.emplace_back(NewTF);
15215 }
15216 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15217}
15218
15220 EVT VT, SDNodeFlags Flags) {
15221 switch (Opcode) {
15222 default:
15223 return SDValue();
15224 case ISD::ADD:
15225 case ISD::OR:
15226 case ISD::XOR:
15227 case ISD::UMAX:
15228 case ISD::MUL:
15229 case ISD::AND:
15230 case ISD::UMIN:
15231 case ISD::SMAX:
15232 case ISD::SMIN:
15234 VT);
15235 case ISD::FADD:
15236 // If flags allow, prefer positive zero since it's generally cheaper
15237 // to materialize on most targets.
15238 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15239 case ISD::FMUL:
15240 return getConstantFP(1.0, DL, VT);
15241 case ISD::FMINNUM:
15242 case ISD::FMAXNUM: {
15243 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
15244 const fltSemantics &Semantics = VT.getFltSemantics();
15245 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15246 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15247 APFloat::getLargest(Semantics);
15248 if (Opcode == ISD::FMAXNUM)
15249 NeutralAF.changeSign();
15250
15251 return getConstantFP(NeutralAF, DL, VT);
15252 }
15253 case ISD::FMINIMUM:
15254 case ISD::FMAXIMUM: {
15255 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15256 const fltSemantics &Semantics = VT.getFltSemantics();
15257 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15258 : APFloat::getLargest(Semantics);
15259 if (Opcode == ISD::FMAXIMUM)
15260 NeutralAF.changeSign();
15261
15262 return getConstantFP(NeutralAF, DL, VT);
15263 }
15264
15265 }
15266}
15267
15269 SDValue Acc, SDValue LHS,
15270 SDValue RHS) {
15271 EVT AccVT = Acc.getValueType();
15272 if (AccVT.isFloatingPoint()) {
15273 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15274 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15275 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15276 }
15278 "Unexpected opcode");
15279 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15280 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15281 return getNegative(MLA, DL, AccVT);
15282}
15283
15284/// Helper used to make a call to a library function that has one argument of
15285/// pointer type.
15286///
15287/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15288/// used to get or set floating-point state. They have one argument of pointer
15289/// type, which points to the memory region containing bits of the
15290/// floating-point state. The value returned by such function is ignored in the
15291/// created call.
15292///
15293/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15294/// \param Ptr Pointer used to save/load state.
15295/// \param InChain Ingoing token chain.
15296/// \returns Outgoing chain token.
15298 SDValue InChain,
15299 const SDLoc &DLoc) {
15300 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15302 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15303 RTLIB::LibcallImpl LibcallImpl =
15304 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15305 if (LibcallImpl == RTLIB::Unsupported)
15306 reportFatalUsageError("emitting call to unsupported libcall");
15307
15308 SDValue Callee =
15309 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15311 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
15312 Libcalls->getLibcallImplCallingConv(LibcallImpl),
15313 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15314 return TLI->LowerCallTo(CLI).second;
15315}
15316
15318 assert(From && To && "Invalid SDNode; empty source SDValue?");
15319 auto I = SDEI.find(From);
15320 if (I == SDEI.end())
15321 return;
15322
15323 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15324 // the iterator, hence the need to make a copy to prevent a use-after-free.
15325 NodeExtraInfo NEI = I->second;
15326 if (LLVM_LIKELY(!NEI.PCSections)) {
15327 // No deep copy required for the types of extra info set.
15328 //
15329 // FIXME: Investigate if other types of extra info also need deep copy. This
15330 // depends on the types of nodes they can be attached to: if some extra info
15331 // is only ever attached to nodes where a replacement To node is always the
15332 // node where later use and propagation of the extra info has the intended
15333 // semantics, no deep copy is required.
15334 SDEI[To] = std::move(NEI);
15335 return;
15336 }
15337
15338 const SDNode *EntrySDN = getEntryNode().getNode();
15339
15340 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15341 // through the replacement of From with To. Otherwise, replacements of a node
15342 // (From) with more complex nodes (To and its operands) may result in lost
15343 // extra info where the root node (To) is insignificant in further propagating
15344 // and using extra info when further lowering to MIR.
15345 //
15346 // In the first step pre-populate the visited set with the nodes reachable
15347 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15348 // DAG that is not new and should be left untouched.
15349 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15350 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15351 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15352 if (MaxDepth == 0) {
15353 // Remember this node in case we need to increase MaxDepth and continue
15354 // populating FromReach from this node.
15355 Leafs.emplace_back(N);
15356 return;
15357 }
15358 if (!FromReach.insert(N).second)
15359 return;
15360 for (const SDValue &Op : N->op_values())
15361 Self(Self, Op.getNode(), MaxDepth - 1);
15362 };
15363
15364 // Copy extra info to To and all its transitive operands (that are new).
15366 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15367 if (FromReach.contains(N))
15368 return true;
15369 if (!Visited.insert(N).second)
15370 return true;
15371 if (EntrySDN == N)
15372 return false;
15373 for (const SDValue &Op : N->op_values()) {
15374 if (N == To && Op.getNode() == EntrySDN) {
15375 // Special case: New node's operand is the entry node; just need to
15376 // copy extra info to new node.
15377 break;
15378 }
15379 if (!Self(Self, Op.getNode()))
15380 return false;
15381 }
15382 // Copy only if entry node was not reached.
15383 SDEI[N] = std::move(NEI);
15384 return true;
15385 };
15386
15387 // We first try with a lower MaxDepth, assuming that the path to common
15388 // operands between From and To is relatively short. This significantly
15389 // improves performance in the common case. The initial MaxDepth is big
15390 // enough to avoid retry in the common case; the last MaxDepth is large
15391 // enough to avoid having to use the fallback below (and protects from
15392 // potential stack exhaustion from recursion).
15393 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15394 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15395 // StartFrom is the previous (or initial) set of leafs reachable at the
15396 // previous maximum depth.
15398 std::swap(StartFrom, Leafs);
15399 for (const SDNode *N : StartFrom)
15400 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15401 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15402 return;
15403 // This should happen very rarely (reached the entry node).
15404 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15405 assert(!Leafs.empty());
15406 }
15407
15408 // This should not happen - but if it did, that means the subgraph reachable
15409 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15410 // could not visit all reachable common operands. Consequently, we were able
15411 // to reach the entry node.
15412 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15413 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15414 // Best-effort fallback if assertions disabled.
15415 SDEI[To] = std::move(NEI);
15416}
15417
15418#ifndef NDEBUG
15419static void checkForCyclesHelper(const SDNode *N,
15422 const llvm::SelectionDAG *DAG) {
15423 // If this node has already been checked, don't check it again.
15424 if (Checked.count(N))
15425 return;
15426
15427 // If a node has already been visited on this depth-first walk, reject it as
15428 // a cycle.
15429 if (!Visited.insert(N).second) {
15430 errs() << "Detected cycle in SelectionDAG\n";
15431 dbgs() << "Offending node:\n";
15432 N->dumprFull(DAG); dbgs() << "\n";
15433 abort();
15434 }
15435
15436 for (const SDValue &Op : N->op_values())
15437 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15438
15439 Checked.insert(N);
15440 Visited.erase(N);
15441}
15442#endif
15443
15445 const llvm::SelectionDAG *DAG,
15446 bool force) {
15447#ifndef NDEBUG
15448 bool check = force;
15449#ifdef EXPENSIVE_CHECKS
15450 check = true;
15451#endif // EXPENSIVE_CHECKS
15452 if (check) {
15453 assert(N && "Checking nonexistent SDNode");
15456 checkForCyclesHelper(N, visited, checked, DAG);
15457 }
15458#endif // !NDEBUG
15459}
15460
15461void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15462 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15463}
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
static bool isConstant(const MachineInstr &MI)
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h: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:5946
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:2007
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2091
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:226
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1077
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:969
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2062
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:255
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1693
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1671
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1198
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:785
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:837
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:647
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2122
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2136
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1085
static bool isSameValue(const APInt &I1, const APInt &I2, bool SignedCompare=false)
Determine if two APInts have the same value, after zero-extending or sign-extending (if SignedCompare...
Definition APInt.h:551
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1185
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
unsigned logBase2() const
Definition APInt.h:1782
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2072
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1301
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1772
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1029
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1388
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:763
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1438
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:386
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:861
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2081
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:212
void AddInteger(signed I)
Definition FoldingSet.h:241
void AddPointer(const void *Ptr)
Add* - Add various data types to Bit data.
Definition FoldingSet.h:232
Data structure describing the variable locations in a function.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:695
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 or function.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
This SDNode is used for LIFETIME_START/LIFETIME_END values.
This class is used to represent ISD::LOAD nodes.
static LocationSize precise(uint64_t Value)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
Machine Value Type.
SimpleValueType SimpleTy
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.
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 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 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 getMaskFromElementCount(const SDLoc &DL, EVT VT, ElementCount Len)
Return a vector with the first 'Len' lanes set to true and remaining lanes set to false.
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, const MDNode *Ranges=nullptr, bool IsExpanding=false)
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDDbgValue * getConstantDbgValue(DIVariable *Var, DIExpression *Expr, const Value *C, const DebugLoc &DL, unsigned O)
Creates a constant SDDbgValue node.
LLVM_ABI SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain, int FrameIndex)
Creates a LifetimeSDNode that starts (IsStart==true) or ends (IsStart==false) the lifetime of the Fra...
ArrayRef< SDDbgValue * > GetDbgValues(const SDNode *SD) const
Get the debug values which reference the given SDNode.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the signed addition of 2 nodes can overflow.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
ilist< SDNode >::size_type allnodes_size() const
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
LLVM_ABI SDValue FoldConstantBuildVector(BuildVectorSDNode *BV, const SDLoc &DL, EVT DstEltVT)
Fold BUILD_VECTOR of constants/undefs to the destination type BUILD_VECTOR of constants/undefs elemen...
LLVM_ABI SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsCompressing=false)
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool MaskedVectorIsZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Return true if 'Op' is known to be zero in DemandedElts.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
LLVM_ABI SDDbgValue * getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr, unsigned FI, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a FrameIndex SDDbgValue node.
LLVM_ABI SDValue getExtStridedLoadVP(ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
LLVM_ABI SDValue getJumpTable(int JTI, EVT VT, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void getTopologicallyOrderedNodes(SmallVectorImpl< const SDNode * > &SortedNodes) const
Get all the nodes in their topological order without modifying any states.
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI std::pair< SDValue, SDValue > getStrstr(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strstr operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to extend the Op as a pointer value assuming it was the smaller SrcTy ...
LLVM_ABI OverflowKind computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the unsigned addition of 2 nodes can overflow.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getErrorMergeValues(ArrayRef< EVT > ResultTypes, SDValue Chain, const SDLoc &dl)
Return poison values for each of ResultTypes, substituting Chain for any result of type MVT::Other,...
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT SVT, MachineMemOperand *MMO, bool IsCompressing=false)
LLVM_ABI void canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, SDValue &N2) const
Swap N1 and N2 if Opcode is a commutative binary opcode and the canonical form expects the opposite o...
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth=0) const
Test if the given fp value is known to be an integer power-of-2, either positive or negative.
LLVM_ABI OverflowKind computeOverflowForSignedSub(SDValue N0, SDValue N1) const
Determine if the result of the signed sub of 2 nodes can overflow.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, SDNodeFlags Flags)
Try to simplify a floating-point binary operation into 1 of its operands or a constant.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
LLVM_ABI SDValue getDeactivationSymbol(const GlobalValue *GV)
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
LLVM_ABI bool isUndef(unsigned Opcode, ArrayRef< SDValue > Ops)
Return true if the result of this operation is always undefined.
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
LLVM_ABI std::pair< EVT, EVT > GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, bool *HiIsEmpty) const
Compute the VTs needed for the low/hi parts of a type, dependent on an enveloping VT that has been sp...
LLVM_ABI SDValue foldConstantFPMath(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops)
Fold floating-point operations when all operands are constants and/or undefined.
LLVM_ABI std::optional< ConstantRange > getValidShiftAmountRange(SDValue V, const APInt &DemandedElts, unsigned Depth) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue FoldSymbolOffset(unsigned Opcode, EVT VT, const GlobalAddressSDNode *GA, const SDNode *N2)
LLVM_ABI SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDDbgValue * getDbgValue(DIVariable *Var, DIExpression *Expr, SDNode *N, unsigned R, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a SDDbgValue node.
LLVM_ABI SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base, SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, ISD::LoadExtType, bool IsExpanding=false)
DenormalMode getDenormalMode(EVT VT) const
Return the current function's default denormal handling kind for the given floating point type.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, ArrayRef< ISD::NodeType > CandidateBinOps, bool AllowPartials=false)
Match a binop + shuffle pyramid that represents a horizontal reduction over the elements of a vector ...
LLVM_ABI bool isADDLike(SDValue Op, bool NoWrap=false) const
Return true if the specified operand is an ISD::OR or ISD::XOR node that can be treated as an ISD::AD...
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue simplifyShift(SDValue X, SDValue Y)
Try to simplify a shift into 1 of its operands or a constant.
LLVM_ABI 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:3233
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3163
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3150
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3140
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3243
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3214
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3155
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:3223
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3253
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2295
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3205
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:3041
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3238
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2300
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3135
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3145
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, bool isIntegerLike)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:24
LLVM_ABI CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical AND between different comparisons of identical values: ((X op1 Y) & (X...
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
bool matchUnaryPredicateImpl(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstNodeType *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant BUI...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ TargetConstantPool
Definition ISDOpcodes.h:189
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:513
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:45
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:236
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ MLOAD
Masked load and store - consecutive vector load and store operations with additional mask operand tha...
@ 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.
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, const APInt &DemandedElts, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
LLVM_ABI bool isFreezeUndef(const SDNode *N)
Return true if the specified node is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI std::optional< unsigned > getVPForBaseOpcode(unsigned Opcode)
Translate this non-VP Opcode to its corresponding VP Opcode.
MemIndexType
MemIndexType enum - This enum defines how to interpret MGATHER/SCATTER's index parameter when calcula...
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
LLVM_ABI NodeType getInverseMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns ISD::(U|S)MAX and ISD::(U|S)MIN,...
LLVM_ABI bool isVPReduction(unsigned Opcode)
Whether this is a vector-predicated reduction opcode.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
LLVM_ABI bool isBuildVectorOfConstantFPSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantFPSDNode or undef.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
bool matchUnaryPredicate(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
LLVM_ABI CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical OR between different comparisons of identical values: ((X op1 Y) | (X ...
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
LLVM_ABI Libcall getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMCPY_ELEMENT_UNORDERED_ATOMIC - Return MEMCPY_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMSET_ELEMENT_UNORDERED_ATOMIC - Return MEMSET_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMMOVE_ELEMENT_UNORDERED_ATOMIC - Return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_* value for the given e...
bool sd_match(SDNode *N, const SelectionDAG *DAG, Pattern &&P)
LLVM_ABI unsigned rot(unsigned SrcSignBits, unsigned BitWidth, std::optional< APInt > RotAmt, bool IsRotateRight)
Compute the number of sign bits after rotating a value.
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp: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:326
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.
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isNullConstantOrUndef(SDValue V)
Returns true if V is a constant integer zero or an UNDEF node.
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:539
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
constexpr unsigned BitWidth
LLVM_ABI bool funcReturnsFirstArgOfCall(const CallInst &CI)
Returns true if the parent of CI returns CI's first argument after calling CI.
Definition Analysis.cpp:719
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant (+/-)0.0 floating-point value or a splatted vector thereof (wi...
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:368
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:783
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
intptr_t getRawBits() const
Definition ValueTypes.h:543
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
KnownBits byteSwap() const
Definition KnownBits.h:559
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
void resetAll()
Resets the known state of all bits.
Definition KnownBits.h:72
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
static LLVM_ABI KnownBits abdu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for abdu(LHS, RHS).
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
static LLVM_ABI KnownBits computeForSubBorrow(const KnownBits &LHS, KnownBits RHS, const KnownBits &Borrow)
Compute known bits results from subtracting RHS from LHS with 1-bit Borrow.
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits abds(KnownBits LHS, KnownBits RHS)
Compute known bits for abds(LHS, RHS).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static LLVM_ABI KnownBits avgFloorS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorS.
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry)
Compute known bits resulting from adding LHS, RHS and a 1-bit Carry.
Definition KnownBits.cpp:54
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
static LLVM_ABI KnownBits avgCeilU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilU.
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
static LLVM_ABI KnownBits avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI bool isDereferenceable(unsigned Size, LLVMContext &C, const DataLayout &DL) const
Return true if memory region [V, V+Offset+Size) is known to be dereferenceable.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
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)