LLVM 22.0.0git
SelectionDAG.cpp
Go to the documentation of this file.
1//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the SelectionDAG class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/APSInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Twine.h"
51#include "llvm/IR/Constant.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugLoc.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/GlobalValue.h"
59#include "llvm/IR/Metadata.h"
60#include "llvm/IR/Type.h"
64#include "llvm/Support/Debug.h"
73#include <algorithm>
74#include <cassert>
75#include <cstdint>
76#include <cstdlib>
77#include <limits>
78#include <optional>
79#include <string>
80#include <utility>
81#include <vector>
82
83using namespace llvm;
84using namespace llvm::SDPatternMatch;
85
86/// makeVTList - Return an instance of the SDVTList struct initialized with the
87/// specified members.
88static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
89 SDVTList Res = {VTs, NumVTs};
90 return Res;
91}
92
93// Default null implementations of the callbacks.
97
98void SelectionDAG::DAGNodeDeletedListener::anchor() {}
99void SelectionDAG::DAGNodeInsertedListener::anchor() {}
100
101#define DEBUG_TYPE "selectiondag"
102
103static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
104 cl::Hidden, cl::init(true),
105 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
106
107static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
108 cl::desc("Number limit for gluing ld/st of memcpy."),
109 cl::Hidden, cl::init(0));
110
112 MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192),
113 cl::desc("DAG combiner limit number of steps when searching DAG "
114 "for predecessor nodes"));
115
117 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
118}
119
121
122//===----------------------------------------------------------------------===//
123// ConstantFPSDNode Class
124//===----------------------------------------------------------------------===//
125
126/// isExactlyValue - We don't rely on operator== working on double values, as
127/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
128/// As such, this method can be used to do an exact bit-for-bit comparison of
129/// two floating point values.
131 return getValueAPF().bitwiseIsEqual(V);
132}
133
135 const APFloat& Val) {
136 assert(VT.isFloatingPoint() && "Can only convert between FP types");
137
138 // convert modifies in place, so make a copy.
139 APFloat Val2 = APFloat(Val);
140 bool losesInfo;
142 &losesInfo);
143 return !losesInfo;
144}
145
146//===----------------------------------------------------------------------===//
147// ISD Namespace
148//===----------------------------------------------------------------------===//
149
150bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
151 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
152 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
153 unsigned EltSize =
154 N->getValueType(0).getVectorElementType().getSizeInBits();
155 SplatVal = OptAPInt->trunc(EltSize);
156 return true;
157 }
158 }
159
160 auto *BV = dyn_cast<BuildVectorSDNode>(N);
161 if (!BV)
162 return false;
163
164 APInt SplatUndef;
165 unsigned SplatBitSize;
166 bool HasUndefs;
167 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
168 // Endianness does not matter here. We are checking for a splat given the
169 // element size of the vector, and if we find such a splat for little endian
170 // layout, then that should be valid also for big endian (as the full vector
171 // size is known to be a multiple of the element size).
172 const bool IsBigEndian = false;
173 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
174 EltSize, IsBigEndian) &&
175 EltSize == SplatBitSize;
176}
177
178// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
179// specializations of the more general isConstantSplatVector()?
180
181bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
182 // Look through a bit convert.
183 while (N->getOpcode() == ISD::BITCAST)
184 N = N->getOperand(0).getNode();
185
186 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
187 APInt SplatVal;
188 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
189 }
190
191 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
192
193 unsigned i = 0, e = N->getNumOperands();
194
195 // Skip over all of the undef values.
196 while (i != e && N->getOperand(i).isUndef())
197 ++i;
198
199 // Do not accept an all-undef vector.
200 if (i == e) return false;
201
202 // Do not accept build_vectors that aren't all constants or which have non-~0
203 // elements. We have to be a bit careful here, as the type of the constant
204 // may not be the same as the type of the vector elements due to type
205 // legalization (the elements are promoted to a legal type for the target and
206 // a vector of a type may be legal when the base element type is not).
207 // We only want to check enough bits to cover the vector elements, because
208 // we care if the resultant vector is all ones, not whether the individual
209 // constants are.
210 SDValue NotZero = N->getOperand(i);
211 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
212 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
213 if (OptAPInt->countr_one() < EltSize)
214 return false;
215 } else
216 return false;
217
218 // Okay, we have at least one ~0 value, check to see if the rest match or are
219 // undefs. Even with the above element type twiddling, this should be OK, as
220 // the same type legalization should have applied to all the elements.
221 for (++i; i != e; ++i)
222 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
223 return false;
224 return true;
225}
226
227bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
228 // Look through a bit convert.
229 while (N->getOpcode() == ISD::BITCAST)
230 N = N->getOperand(0).getNode();
231
232 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
233 APInt SplatVal;
234 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
235 }
236
237 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
238
239 bool IsAllUndef = true;
240 for (const SDValue &Op : N->op_values()) {
241 if (Op.isUndef())
242 continue;
243 IsAllUndef = false;
244 // Do not accept build_vectors that aren't all constants or which have non-0
245 // elements. We have to be a bit careful here, as the type of the constant
246 // may not be the same as the type of the vector elements due to type
247 // legalization (the elements are promoted to a legal type for the target
248 // and a vector of a type may be legal when the base element type is not).
249 // We only want to check enough bits to cover the vector elements, because
250 // we care if the resultant vector is all zeros, not whether the individual
251 // constants are.
252 if (auto OptAPInt = Op->bitcastToAPInt()) {
253 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
254 if (OptAPInt->countr_zero() < EltSize)
255 return false;
256 } else
257 return false;
258 }
259
260 // Do not accept an all-undef vector.
261 if (IsAllUndef)
262 return false;
263 return true;
264}
265
267 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
268}
269
271 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
272}
273
275 if (N->getOpcode() != ISD::BUILD_VECTOR)
276 return false;
277
278 for (const SDValue &Op : N->op_values()) {
279 if (Op.isUndef())
280 continue;
282 return false;
283 }
284 return true;
285}
286
288 if (N->getOpcode() != ISD::BUILD_VECTOR)
289 return false;
290
291 for (const SDValue &Op : N->op_values()) {
292 if (Op.isUndef())
293 continue;
295 return false;
296 }
297 return true;
298}
299
300bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
301 bool Signed) {
302 assert(N->getValueType(0).isVector() && "Expected a vector!");
303
304 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
305 if (EltSize <= NewEltSize)
306 return false;
307
308 if (N->getOpcode() == ISD::ZERO_EXTEND) {
309 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
310 NewEltSize) &&
311 !Signed;
312 }
313 if (N->getOpcode() == ISD::SIGN_EXTEND) {
314 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
315 NewEltSize) &&
316 Signed;
317 }
318 if (N->getOpcode() != ISD::BUILD_VECTOR)
319 return false;
320
321 for (const SDValue &Op : N->op_values()) {
322 if (Op.isUndef())
323 continue;
325 return false;
326
327 APInt C = Op->getAsAPIntVal().trunc(EltSize);
328 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
329 return false;
330 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
331 return false;
332 }
333
334 return true;
335}
336
338 // Return false if the node has no operands.
339 // This is "logically inconsistent" with the definition of "all" but
340 // is probably the desired behavior.
341 if (N->getNumOperands() == 0)
342 return false;
343 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
344}
345
347 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
348}
349
350template <typename ConstNodeType>
352 std::function<bool(ConstNodeType *)> Match,
353 bool AllowUndefs, bool AllowTruncation) {
354 // FIXME: Add support for scalar UNDEF cases?
355 if (auto *C = dyn_cast<ConstNodeType>(Op))
356 return Match(C);
357
358 // FIXME: Add support for vector UNDEF cases?
359 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
360 ISD::SPLAT_VECTOR != Op.getOpcode())
361 return false;
362
363 EVT SVT = Op.getValueType().getScalarType();
364 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
365 if (AllowUndefs && Op.getOperand(i).isUndef()) {
366 if (!Match(nullptr))
367 return false;
368 continue;
369 }
370
371 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
372 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
373 !Match(Cst))
374 return false;
375 }
376 return true;
377}
378// Build used template types.
380 SDValue, std::function<bool(ConstantSDNode *)>, bool, bool);
382 SDValue, std::function<bool(ConstantFPSDNode *)>, bool, bool);
383
385 SDValue LHS, SDValue RHS,
386 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
387 bool AllowUndefs, bool AllowTypeMismatch) {
388 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
389 return false;
390
391 // TODO: Add support for scalar UNDEF cases?
392 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
393 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
394 return Match(LHSCst, RHSCst);
395
396 // TODO: Add support for vector UNDEF cases?
397 if (LHS.getOpcode() != RHS.getOpcode() ||
398 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
399 LHS.getOpcode() != ISD::SPLAT_VECTOR))
400 return false;
401
402 EVT SVT = LHS.getValueType().getScalarType();
403 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
404 SDValue LHSOp = LHS.getOperand(i);
405 SDValue RHSOp = RHS.getOperand(i);
406 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
407 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
408 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
409 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
410 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
411 return false;
412 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
413 LHSOp.getValueType() != RHSOp.getValueType()))
414 return false;
415 if (!Match(LHSCst, RHSCst))
416 return false;
417 }
418 return true;
419}
420
422 switch (MinMaxOpc) {
423 default:
424 llvm_unreachable("unrecognized opcode");
425 case ISD::UMIN:
426 return ISD::UMAX;
427 case ISD::UMAX:
428 return ISD::UMIN;
429 case ISD::SMIN:
430 return ISD::SMAX;
431 case ISD::SMAX:
432 return ISD::SMIN;
433 }
434}
435
437 switch (VecReduceOpcode) {
438 default:
439 llvm_unreachable("Expected VECREDUCE opcode");
442 case ISD::VP_REDUCE_FADD:
443 case ISD::VP_REDUCE_SEQ_FADD:
444 return ISD::FADD;
447 case ISD::VP_REDUCE_FMUL:
448 case ISD::VP_REDUCE_SEQ_FMUL:
449 return ISD::FMUL;
451 case ISD::VP_REDUCE_ADD:
452 return ISD::ADD;
454 case ISD::VP_REDUCE_MUL:
455 return ISD::MUL;
457 case ISD::VP_REDUCE_AND:
458 return ISD::AND;
460 case ISD::VP_REDUCE_OR:
461 return ISD::OR;
463 case ISD::VP_REDUCE_XOR:
464 return ISD::XOR;
466 case ISD::VP_REDUCE_SMAX:
467 return ISD::SMAX;
469 case ISD::VP_REDUCE_SMIN:
470 return ISD::SMIN;
472 case ISD::VP_REDUCE_UMAX:
473 return ISD::UMAX;
475 case ISD::VP_REDUCE_UMIN:
476 return ISD::UMIN;
478 case ISD::VP_REDUCE_FMAX:
479 return ISD::FMAXNUM;
481 case ISD::VP_REDUCE_FMIN:
482 return ISD::FMINNUM;
484 case ISD::VP_REDUCE_FMAXIMUM:
485 return ISD::FMAXIMUM;
487 case ISD::VP_REDUCE_FMINIMUM:
488 return ISD::FMINIMUM;
489 }
490}
491
492bool ISD::isVPOpcode(unsigned Opcode) {
493 switch (Opcode) {
494 default:
495 return false;
496#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
497 case ISD::VPSD: \
498 return true;
499#include "llvm/IR/VPIntrinsics.def"
500 }
501}
502
503bool ISD::isVPBinaryOp(unsigned Opcode) {
504 switch (Opcode) {
505 default:
506 break;
507#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
508#define VP_PROPERTY_BINARYOP return true;
509#define END_REGISTER_VP_SDNODE(VPSD) break;
510#include "llvm/IR/VPIntrinsics.def"
511 }
512 return false;
513}
514
515bool ISD::isVPReduction(unsigned Opcode) {
516 switch (Opcode) {
517 default:
518 return false;
519 case ISD::VP_REDUCE_ADD:
520 case ISD::VP_REDUCE_MUL:
521 case ISD::VP_REDUCE_AND:
522 case ISD::VP_REDUCE_OR:
523 case ISD::VP_REDUCE_XOR:
524 case ISD::VP_REDUCE_SMAX:
525 case ISD::VP_REDUCE_SMIN:
526 case ISD::VP_REDUCE_UMAX:
527 case ISD::VP_REDUCE_UMIN:
528 case ISD::VP_REDUCE_FMAX:
529 case ISD::VP_REDUCE_FMIN:
530 case ISD::VP_REDUCE_FMAXIMUM:
531 case ISD::VP_REDUCE_FMINIMUM:
532 case ISD::VP_REDUCE_FADD:
533 case ISD::VP_REDUCE_FMUL:
534 case ISD::VP_REDUCE_SEQ_FADD:
535 case ISD::VP_REDUCE_SEQ_FMUL:
536 return true;
537 }
538}
539
540/// The operand position of the vector mask.
541std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
542 switch (Opcode) {
543 default:
544 return std::nullopt;
545#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
546 case ISD::VPSD: \
547 return MASKPOS;
548#include "llvm/IR/VPIntrinsics.def"
549 }
550}
551
552/// The operand position of the explicit vector length parameter.
553std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
554 switch (Opcode) {
555 default:
556 return std::nullopt;
557#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
558 case ISD::VPSD: \
559 return EVLPOS;
560#include "llvm/IR/VPIntrinsics.def"
561 }
562}
563
564std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
565 bool hasFPExcept) {
566 // FIXME: Return strict opcodes in case of fp exceptions.
567 switch (VPOpcode) {
568 default:
569 return std::nullopt;
570#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
571#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
572#define END_REGISTER_VP_SDNODE(VPOPC) break;
573#include "llvm/IR/VPIntrinsics.def"
574 }
575 return std::nullopt;
576}
577
578std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
579 switch (Opcode) {
580 default:
581 return std::nullopt;
582#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
583#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
584#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
585#include "llvm/IR/VPIntrinsics.def"
586 }
587}
588
590 switch (ExtType) {
591 case ISD::EXTLOAD:
592 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
593 case ISD::SEXTLOAD:
594 return ISD::SIGN_EXTEND;
595 case ISD::ZEXTLOAD:
596 return ISD::ZERO_EXTEND;
597 default:
598 break;
599 }
600
601 llvm_unreachable("Invalid LoadExtType");
602}
603
605 // To perform this operation, we just need to swap the L and G bits of the
606 // operation.
607 unsigned OldL = (Operation >> 2) & 1;
608 unsigned OldG = (Operation >> 1) & 1;
609 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
610 (OldL << 1) | // New G bit
611 (OldG << 2)); // New L bit.
612}
613
615 unsigned Operation = Op;
616 if (isIntegerLike)
617 Operation ^= 7; // Flip L, G, E bits, but not U.
618 else
619 Operation ^= 15; // Flip all of the condition bits.
620
622 Operation &= ~8; // Don't let N and U bits get set.
623
624 return ISD::CondCode(Operation);
625}
626
630
632 bool isIntegerLike) {
633 return getSetCCInverseImpl(Op, isIntegerLike);
634}
635
636/// For an integer comparison, return 1 if the comparison is a signed operation
637/// and 2 if the result is an unsigned comparison. Return zero if the operation
638/// does not depend on the sign of the input (setne and seteq).
639static int isSignedOp(ISD::CondCode Opcode) {
640 switch (Opcode) {
641 default: llvm_unreachable("Illegal integer setcc operation!");
642 case ISD::SETEQ:
643 case ISD::SETNE: return 0;
644 case ISD::SETLT:
645 case ISD::SETLE:
646 case ISD::SETGT:
647 case ISD::SETGE: return 1;
648 case ISD::SETULT:
649 case ISD::SETULE:
650 case ISD::SETUGT:
651 case ISD::SETUGE: return 2;
652 }
653}
654
656 EVT Type) {
657 bool IsInteger = Type.isInteger();
658 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
659 // Cannot fold a signed integer setcc with an unsigned integer setcc.
660 return ISD::SETCC_INVALID;
661
662 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
663
664 // If the N and U bits get set, then the resultant comparison DOES suddenly
665 // care about orderedness, and it is true when ordered.
666 if (Op > ISD::SETTRUE2)
667 Op &= ~16; // Clear the U bit if the N bit is set.
668
669 // Canonicalize illegal integer setcc's.
670 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
671 Op = ISD::SETNE;
672
673 return ISD::CondCode(Op);
674}
675
677 EVT Type) {
678 bool IsInteger = Type.isInteger();
679 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
680 // Cannot fold a signed setcc with an unsigned setcc.
681 return ISD::SETCC_INVALID;
682
683 // Combine all of the condition bits.
684 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
685
686 // Canonicalize illegal integer setcc's.
687 if (IsInteger) {
688 switch (Result) {
689 default: break;
690 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
691 case ISD::SETOEQ: // SETEQ & SETU[LG]E
692 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
693 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
694 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
695 }
696 }
697
698 return Result;
699}
700
701//===----------------------------------------------------------------------===//
702// SDNode Profile Support
703//===----------------------------------------------------------------------===//
704
705/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
706static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
707 ID.AddInteger(OpC);
708}
709
710/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
711/// solely with their pointer.
713 ID.AddPointer(VTList.VTs);
714}
715
716/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
719 for (const auto &Op : Ops) {
720 ID.AddPointer(Op.getNode());
721 ID.AddInteger(Op.getResNo());
722 }
723}
724
725/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
728 for (const auto &Op : Ops) {
729 ID.AddPointer(Op.getNode());
730 ID.AddInteger(Op.getResNo());
731 }
732}
733
734static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
735 SDVTList VTList, ArrayRef<SDValue> OpList) {
736 AddNodeIDOpcode(ID, OpC);
737 AddNodeIDValueTypes(ID, VTList);
738 AddNodeIDOperands(ID, OpList);
739}
740
741/// If this is an SDNode with special info, add this info to the NodeID data.
743 switch (N->getOpcode()) {
746 case ISD::MCSymbol:
747 llvm_unreachable("Should only be used on nodes with operands");
748 default: break; // Normal nodes don't need extra info.
750 case ISD::Constant: {
752 ID.AddPointer(C->getConstantIntValue());
753 ID.AddBoolean(C->isOpaque());
754 break;
755 }
757 case ISD::ConstantFP:
758 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
759 break;
765 ID.AddPointer(GA->getGlobal());
766 ID.AddInteger(GA->getOffset());
767 ID.AddInteger(GA->getTargetFlags());
768 break;
769 }
770 case ISD::BasicBlock:
772 break;
773 case ISD::Register:
774 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
775 break;
777 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
778 break;
779 case ISD::SRCVALUE:
780 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
781 break;
782 case ISD::FrameIndex:
784 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
785 break;
787 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
788 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
789 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
790 break;
791 case ISD::JumpTable:
793 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
794 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
795 break;
799 ID.AddInteger(CP->getAlign().value());
800 ID.AddInteger(CP->getOffset());
801 if (CP->isMachineConstantPoolEntry())
802 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
803 else
804 ID.AddPointer(CP->getConstVal());
805 ID.AddInteger(CP->getTargetFlags());
806 break;
807 }
808 case ISD::TargetIndex: {
810 ID.AddInteger(TI->getIndex());
811 ID.AddInteger(TI->getOffset());
812 ID.AddInteger(TI->getTargetFlags());
813 break;
814 }
815 case ISD::LOAD: {
816 const LoadSDNode *LD = cast<LoadSDNode>(N);
817 ID.AddInteger(LD->getMemoryVT().getRawBits());
818 ID.AddInteger(LD->getRawSubclassData());
819 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
820 ID.AddInteger(LD->getMemOperand()->getFlags());
821 break;
822 }
823 case ISD::STORE: {
824 const StoreSDNode *ST = cast<StoreSDNode>(N);
825 ID.AddInteger(ST->getMemoryVT().getRawBits());
826 ID.AddInteger(ST->getRawSubclassData());
827 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
828 ID.AddInteger(ST->getMemOperand()->getFlags());
829 break;
830 }
831 case ISD::VP_LOAD: {
832 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
833 ID.AddInteger(ELD->getMemoryVT().getRawBits());
834 ID.AddInteger(ELD->getRawSubclassData());
835 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
836 ID.AddInteger(ELD->getMemOperand()->getFlags());
837 break;
838 }
839 case ISD::VP_LOAD_FF: {
840 const auto *LD = cast<VPLoadFFSDNode>(N);
841 ID.AddInteger(LD->getMemoryVT().getRawBits());
842 ID.AddInteger(LD->getRawSubclassData());
843 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
844 ID.AddInteger(LD->getMemOperand()->getFlags());
845 break;
846 }
847 case ISD::VP_STORE: {
848 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
849 ID.AddInteger(EST->getMemoryVT().getRawBits());
850 ID.AddInteger(EST->getRawSubclassData());
851 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
852 ID.AddInteger(EST->getMemOperand()->getFlags());
853 break;
854 }
855 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
857 ID.AddInteger(SLD->getMemoryVT().getRawBits());
858 ID.AddInteger(SLD->getRawSubclassData());
859 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
860 break;
861 }
862 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
864 ID.AddInteger(SST->getMemoryVT().getRawBits());
865 ID.AddInteger(SST->getRawSubclassData());
866 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
867 break;
868 }
869 case ISD::VP_GATHER: {
871 ID.AddInteger(EG->getMemoryVT().getRawBits());
872 ID.AddInteger(EG->getRawSubclassData());
873 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
874 ID.AddInteger(EG->getMemOperand()->getFlags());
875 break;
876 }
877 case ISD::VP_SCATTER: {
879 ID.AddInteger(ES->getMemoryVT().getRawBits());
880 ID.AddInteger(ES->getRawSubclassData());
881 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
882 ID.AddInteger(ES->getMemOperand()->getFlags());
883 break;
884 }
885 case ISD::MLOAD: {
887 ID.AddInteger(MLD->getMemoryVT().getRawBits());
888 ID.AddInteger(MLD->getRawSubclassData());
889 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
890 ID.AddInteger(MLD->getMemOperand()->getFlags());
891 break;
892 }
893 case ISD::MSTORE: {
895 ID.AddInteger(MST->getMemoryVT().getRawBits());
896 ID.AddInteger(MST->getRawSubclassData());
897 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
898 ID.AddInteger(MST->getMemOperand()->getFlags());
899 break;
900 }
901 case ISD::MGATHER: {
903 ID.AddInteger(MG->getMemoryVT().getRawBits());
904 ID.AddInteger(MG->getRawSubclassData());
905 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
906 ID.AddInteger(MG->getMemOperand()->getFlags());
907 break;
908 }
909 case ISD::MSCATTER: {
911 ID.AddInteger(MS->getMemoryVT().getRawBits());
912 ID.AddInteger(MS->getRawSubclassData());
913 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
914 ID.AddInteger(MS->getMemOperand()->getFlags());
915 break;
916 }
919 case ISD::ATOMIC_SWAP:
931 case ISD::ATOMIC_LOAD:
932 case ISD::ATOMIC_STORE: {
933 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
934 ID.AddInteger(AT->getMemoryVT().getRawBits());
935 ID.AddInteger(AT->getRawSubclassData());
936 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
937 ID.AddInteger(AT->getMemOperand()->getFlags());
938 break;
939 }
940 case ISD::VECTOR_SHUFFLE: {
941 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
942 for (int M : Mask)
943 ID.AddInteger(M);
944 break;
945 }
946 case ISD::ADDRSPACECAST: {
948 ID.AddInteger(ASC->getSrcAddressSpace());
949 ID.AddInteger(ASC->getDestAddressSpace());
950 break;
951 }
953 case ISD::BlockAddress: {
955 ID.AddPointer(BA->getBlockAddress());
956 ID.AddInteger(BA->getOffset());
957 ID.AddInteger(BA->getTargetFlags());
958 break;
959 }
960 case ISD::AssertAlign:
961 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
962 break;
963 case ISD::PREFETCH:
966 // Handled by MemIntrinsicSDNode check after the switch.
967 break;
969 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
970 break;
971 } // end switch (N->getOpcode())
972
973 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
974 // to check.
975 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
976 ID.AddInteger(MN->getRawSubclassData());
977 ID.AddInteger(MN->getPointerInfo().getAddrSpace());
978 ID.AddInteger(MN->getMemOperand()->getFlags());
979 ID.AddInteger(MN->getMemoryVT().getRawBits());
980 }
981}
982
983/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
984/// data.
985static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
986 AddNodeIDOpcode(ID, N->getOpcode());
987 // Add the return value info.
988 AddNodeIDValueTypes(ID, N->getVTList());
989 // Add the operand info.
990 AddNodeIDOperands(ID, N->ops());
991
992 // Handle SDNode leafs with special info.
994}
995
996//===----------------------------------------------------------------------===//
997// SelectionDAG Class
998//===----------------------------------------------------------------------===//
999
1000/// doNotCSE - Return true if CSE should not be performed for this node.
1001static bool doNotCSE(SDNode *N) {
1002 if (N->getValueType(0) == MVT::Glue)
1003 return true; // Never CSE anything that produces a glue result.
1004
1005 switch (N->getOpcode()) {
1006 default: break;
1007 case ISD::HANDLENODE:
1008 case ISD::EH_LABEL:
1009 return true; // Never CSE these nodes.
1010 }
1011
1012 // Check that remaining values produced are not flags.
1013 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1014 if (N->getValueType(i) == MVT::Glue)
1015 return true; // Never CSE anything that produces a glue result.
1016
1017 return false;
1018}
1019
1020/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1021/// SelectionDAG.
1023 // Create a dummy node (which is not added to allnodes), that adds a reference
1024 // to the root node, preventing it from being deleted.
1025 HandleSDNode Dummy(getRoot());
1026
1027 SmallVector<SDNode*, 128> DeadNodes;
1028
1029 // Add all obviously-dead nodes to the DeadNodes worklist.
1030 for (SDNode &Node : allnodes())
1031 if (Node.use_empty())
1032 DeadNodes.push_back(&Node);
1033
1034 RemoveDeadNodes(DeadNodes);
1035
1036 // If the root changed (e.g. it was a dead load, update the root).
1037 setRoot(Dummy.getValue());
1038}
1039
1040/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1041/// given list, and any nodes that become unreachable as a result.
1043
1044 // Process the worklist, deleting the nodes and adding their uses to the
1045 // worklist.
1046 while (!DeadNodes.empty()) {
1047 SDNode *N = DeadNodes.pop_back_val();
1048 // Skip to next node if we've already managed to delete the node. This could
1049 // happen if replacing a node causes a node previously added to the node to
1050 // be deleted.
1051 if (N->getOpcode() == ISD::DELETED_NODE)
1052 continue;
1053
1054 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1055 DUL->NodeDeleted(N, nullptr);
1056
1057 // Take the node out of the appropriate CSE map.
1058 RemoveNodeFromCSEMaps(N);
1059
1060 // Next, brutally remove the operand list. This is safe to do, as there are
1061 // no cycles in the graph.
1062 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1063 SDUse &Use = *I++;
1064 SDNode *Operand = Use.getNode();
1065 Use.set(SDValue());
1066
1067 // Now that we removed this operand, see if there are no uses of it left.
1068 if (Operand->use_empty())
1069 DeadNodes.push_back(Operand);
1070 }
1071
1072 DeallocateNode(N);
1073 }
1074}
1075
1077 SmallVector<SDNode*, 16> DeadNodes(1, N);
1078
1079 // Create a dummy node that adds a reference to the root node, preventing
1080 // it from being deleted. (This matters if the root is an operand of the
1081 // dead node.)
1082 HandleSDNode Dummy(getRoot());
1083
1084 RemoveDeadNodes(DeadNodes);
1085}
1086
1088 // First take this out of the appropriate CSE map.
1089 RemoveNodeFromCSEMaps(N);
1090
1091 // Finally, remove uses due to operands of this node, remove from the
1092 // AllNodes list, and delete the node.
1093 DeleteNodeNotInCSEMaps(N);
1094}
1095
1096void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1097 assert(N->getIterator() != AllNodes.begin() &&
1098 "Cannot delete the entry node!");
1099 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1100
1101 // Drop all of the operands and decrement used node's use counts.
1102 N->DropOperands();
1103
1104 DeallocateNode(N);
1105}
1106
1107void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1108 assert(!(V->isVariadic() && isParameter));
1109 if (isParameter)
1110 ByvalParmDbgValues.push_back(V);
1111 else
1112 DbgValues.push_back(V);
1113 for (const SDNode *Node : V->getSDNodes())
1114 if (Node)
1115 DbgValMap[Node].push_back(V);
1116}
1117
1119 DbgValMapType::iterator I = DbgValMap.find(Node);
1120 if (I == DbgValMap.end())
1121 return;
1122 for (auto &Val: I->second)
1123 Val->setIsInvalidated();
1124 DbgValMap.erase(I);
1125}
1126
1127void SelectionDAG::DeallocateNode(SDNode *N) {
1128 // If we have operands, deallocate them.
1130
1131 NodeAllocator.Deallocate(AllNodes.remove(N));
1132
1133 // Set the opcode to DELETED_NODE to help catch bugs when node
1134 // memory is reallocated.
1135 // FIXME: There are places in SDag that have grown a dependency on the opcode
1136 // value in the released node.
1137 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1138 N->NodeType = ISD::DELETED_NODE;
1139
1140 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1141 // them and forget about that node.
1142 DbgInfo->erase(N);
1143
1144 // Invalidate extra info.
1145 SDEI.erase(N);
1146}
1147
1148#ifndef NDEBUG
1149/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1150void SelectionDAG::verifyNode(SDNode *N) const {
1151 switch (N->getOpcode()) {
1152 default:
1153 if (N->isTargetOpcode())
1155 break;
1156 case ISD::BUILD_PAIR: {
1157 EVT VT = N->getValueType(0);
1158 assert(N->getNumValues() == 1 && "Too many results!");
1159 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1160 "Wrong return type!");
1161 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1162 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1163 "Mismatched operand types!");
1164 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1165 "Wrong operand type!");
1166 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1167 "Wrong return type size");
1168 break;
1169 }
1170 case ISD::BUILD_VECTOR: {
1171 assert(N->getNumValues() == 1 && "Too many results!");
1172 assert(N->getValueType(0).isVector() && "Wrong return type!");
1173 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1174 "Wrong number of operands!");
1175 EVT EltVT = N->getValueType(0).getVectorElementType();
1176 for (const SDUse &Op : N->ops()) {
1177 assert((Op.getValueType() == EltVT ||
1178 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1179 EltVT.bitsLE(Op.getValueType()))) &&
1180 "Wrong operand type!");
1181 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1182 "Operands must all have the same type");
1183 }
1184 break;
1185 }
1186 }
1187}
1188#endif // NDEBUG
1189
1190/// Insert a newly allocated node into the DAG.
1191///
1192/// Handles insertion into the all nodes list and CSE map, as well as
1193/// verification and other common operations when a new node is allocated.
1194void SelectionDAG::InsertNode(SDNode *N) {
1195 AllNodes.push_back(N);
1196#ifndef NDEBUG
1197 N->PersistentId = NextPersistentId++;
1198 verifyNode(N);
1199#endif
1200 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1201 DUL->NodeInserted(N);
1202}
1203
1204/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1205/// correspond to it. This is useful when we're about to delete or repurpose
1206/// the node. We don't want future request for structurally identical nodes
1207/// to return N anymore.
1208bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1209 bool Erased = false;
1210 switch (N->getOpcode()) {
1211 case ISD::HANDLENODE: return false; // noop.
1212 case ISD::CONDCODE:
1213 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1214 "Cond code doesn't exist!");
1215 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1216 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1217 break;
1219 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1220 break;
1222 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1223 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1224 ESN->getSymbol(), ESN->getTargetFlags()));
1225 break;
1226 }
1227 case ISD::MCSymbol: {
1228 auto *MCSN = cast<MCSymbolSDNode>(N);
1229 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1230 break;
1231 }
1232 case ISD::VALUETYPE: {
1233 EVT VT = cast<VTSDNode>(N)->getVT();
1234 if (VT.isExtended()) {
1235 Erased = ExtendedValueTypeNodes.erase(VT);
1236 } else {
1237 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1238 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1239 }
1240 break;
1241 }
1242 default:
1243 // Remove it from the CSE Map.
1244 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1245 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1246 Erased = CSEMap.RemoveNode(N);
1247 break;
1248 }
1249#ifndef NDEBUG
1250 // Verify that the node was actually in one of the CSE maps, unless it has a
1251 // glue result (which cannot be CSE'd) or is one of the special cases that are
1252 // not subject to CSE.
1253 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1254 !N->isMachineOpcode() && !doNotCSE(N)) {
1255 N->dump(this);
1256 dbgs() << "\n";
1257 llvm_unreachable("Node is not in map!");
1258 }
1259#endif
1260 return Erased;
1261}
1262
1263/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1264/// maps and modified in place. Add it back to the CSE maps, unless an identical
1265/// node already exists, in which case transfer all its users to the existing
1266/// node. This transfer can potentially trigger recursive merging.
1267void
1268SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1269 // For node types that aren't CSE'd, just act as if no identical node
1270 // already exists.
1271 if (!doNotCSE(N)) {
1272 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1273 if (Existing != N) {
1274 // If there was already an existing matching node, use ReplaceAllUsesWith
1275 // to replace the dead one with the existing one. This can cause
1276 // recursive merging of other unrelated nodes down the line.
1277 Existing->intersectFlagsWith(N->getFlags());
1278 if (auto *MemNode = dyn_cast<MemSDNode>(Existing))
1279 MemNode->refineRanges(cast<MemSDNode>(N)->getMemOperand());
1280 ReplaceAllUsesWith(N, Existing);
1281
1282 // N is now dead. Inform the listeners and delete it.
1283 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1284 DUL->NodeDeleted(N, Existing);
1285 DeleteNodeNotInCSEMaps(N);
1286 return;
1287 }
1288 }
1289
1290 // If the node doesn't already exist, we updated it. Inform listeners.
1291 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1292 DUL->NodeUpdated(N);
1293}
1294
1295/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1296/// were replaced with those specified. If this node is never memoized,
1297/// return null, otherwise return a pointer to the slot it would take. If a
1298/// node already exists with these operands, the slot will be non-null.
1299SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1300 void *&InsertPos) {
1301 if (doNotCSE(N))
1302 return nullptr;
1303
1304 SDValue Ops[] = { Op };
1305 FoldingSetNodeID ID;
1306 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1308 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1309 if (Node)
1310 Node->intersectFlagsWith(N->getFlags());
1311 return Node;
1312}
1313
1314/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1315/// were replaced with those specified. If this node is never memoized,
1316/// return null, otherwise return a pointer to the slot it would take. If a
1317/// node already exists with these operands, the slot will be non-null.
1318SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1319 SDValue Op1, SDValue Op2,
1320 void *&InsertPos) {
1321 if (doNotCSE(N))
1322 return nullptr;
1323
1324 SDValue Ops[] = { Op1, Op2 };
1325 FoldingSetNodeID ID;
1326 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1328 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1329 if (Node)
1330 Node->intersectFlagsWith(N->getFlags());
1331 return Node;
1332}
1333
1334/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1335/// were replaced with those specified. If this node is never memoized,
1336/// return null, otherwise return a pointer to the slot it would take. If a
1337/// node already exists with these operands, the slot will be non-null.
1338SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1339 void *&InsertPos) {
1340 if (doNotCSE(N))
1341 return nullptr;
1342
1343 FoldingSetNodeID ID;
1344 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1346 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1347 if (Node)
1348 Node->intersectFlagsWith(N->getFlags());
1349 return Node;
1350}
1351
1353 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1354 : VT.getTypeForEVT(*getContext());
1355
1356 return getDataLayout().getABITypeAlign(Ty);
1357}
1358
1359// EntryNode could meaningfully have debug info if we can find it...
1361 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1362 getVTList(MVT::Other, MVT::Glue)),
1363 Root(getEntryNode()) {
1364 InsertNode(&EntryNode);
1365 DbgInfo = new SDDbgInfo();
1366}
1367
1369 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1370 const TargetLibraryInfo *LibraryInfo,
1371 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1373 FunctionVarLocs const *VarLocs) {
1374 MF = &NewMF;
1375 SDAGISelPass = PassPtr;
1376 ORE = &NewORE;
1379 LibInfo = LibraryInfo;
1380 Context = &MF->getFunction().getContext();
1381 UA = NewUA;
1382 PSI = PSIin;
1383 BFI = BFIin;
1384 MMI = &MMIin;
1385 FnVarLocs = VarLocs;
1386}
1387
1389 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1390 allnodes_clear();
1391 OperandRecycler.clear(OperandAllocator);
1392 delete DbgInfo;
1393}
1394
1396 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1397}
1398
1399void SelectionDAG::allnodes_clear() {
1400 assert(&*AllNodes.begin() == &EntryNode);
1401 AllNodes.remove(AllNodes.begin());
1402 while (!AllNodes.empty())
1403 DeallocateNode(&AllNodes.front());
1404#ifndef NDEBUG
1405 NextPersistentId = 0;
1406#endif
1407}
1408
1409SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1410 void *&InsertPos) {
1411 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1412 if (N) {
1413 switch (N->getOpcode()) {
1414 default: break;
1415 case ISD::Constant:
1416 case ISD::ConstantFP:
1417 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1418 "debug location. Use another overload.");
1419 }
1420 }
1421 return N;
1422}
1423
1424SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1425 const SDLoc &DL, void *&InsertPos) {
1426 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1427 if (N) {
1428 switch (N->getOpcode()) {
1429 case ISD::Constant:
1430 case ISD::ConstantFP:
1431 // Erase debug location from the node if the node is used at several
1432 // different places. Do not propagate one location to all uses as it
1433 // will cause a worse single stepping debugging experience.
1434 if (N->getDebugLoc() != DL.getDebugLoc())
1435 N->setDebugLoc(DebugLoc());
1436 break;
1437 default:
1438 // When the node's point of use is located earlier in the instruction
1439 // sequence than its prior point of use, update its debug info to the
1440 // earlier location.
1441 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1442 N->setDebugLoc(DL.getDebugLoc());
1443 break;
1444 }
1445 }
1446 return N;
1447}
1448
1450 allnodes_clear();
1451 OperandRecycler.clear(OperandAllocator);
1452 OperandAllocator.Reset();
1453 CSEMap.clear();
1454
1455 ExtendedValueTypeNodes.clear();
1456 ExternalSymbols.clear();
1457 TargetExternalSymbols.clear();
1458 MCSymbols.clear();
1459 SDEI.clear();
1460 llvm::fill(CondCodeNodes, nullptr);
1461 llvm::fill(ValueTypeNodes, nullptr);
1462
1463 EntryNode.UseList = nullptr;
1464 InsertNode(&EntryNode);
1465 Root = getEntryNode();
1466 DbgInfo->clear();
1467}
1468
1470 return VT.bitsGT(Op.getValueType())
1471 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1472 : getNode(ISD::FP_ROUND, DL, VT, Op,
1473 getIntPtrConstant(0, DL, /*isTarget=*/true));
1474}
1475
1476std::pair<SDValue, SDValue>
1478 const SDLoc &DL, EVT VT) {
1479 assert(!VT.bitsEq(Op.getValueType()) &&
1480 "Strict no-op FP extend/round not allowed.");
1481 SDValue Res =
1482 VT.bitsGT(Op.getValueType())
1483 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1484 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1485 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1486
1487 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1488}
1489
1491 return VT.bitsGT(Op.getValueType()) ?
1492 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1493 getNode(ISD::TRUNCATE, DL, VT, Op);
1494}
1495
1497 return VT.bitsGT(Op.getValueType()) ?
1498 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1499 getNode(ISD::TRUNCATE, DL, VT, Op);
1500}
1501
1503 return VT.bitsGT(Op.getValueType()) ?
1504 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1505 getNode(ISD::TRUNCATE, DL, VT, Op);
1506}
1507
1509 EVT VT) {
1510 assert(!VT.isVector());
1511 auto Type = Op.getValueType();
1512 SDValue DestOp;
1513 if (Type == VT)
1514 return Op;
1515 auto Size = Op.getValueSizeInBits();
1516 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1517 if (DestOp.getValueType() == VT)
1518 return DestOp;
1519
1520 return getAnyExtOrTrunc(DestOp, DL, VT);
1521}
1522
1524 EVT VT) {
1525 assert(!VT.isVector());
1526 auto Type = Op.getValueType();
1527 SDValue DestOp;
1528 if (Type == VT)
1529 return Op;
1530 auto Size = Op.getValueSizeInBits();
1531 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1532 if (DestOp.getValueType() == VT)
1533 return DestOp;
1534
1535 return getSExtOrTrunc(DestOp, DL, VT);
1536}
1537
1539 EVT VT) {
1540 assert(!VT.isVector());
1541 auto Type = Op.getValueType();
1542 SDValue DestOp;
1543 if (Type == VT)
1544 return Op;
1545 auto Size = Op.getValueSizeInBits();
1546 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1547 if (DestOp.getValueType() == VT)
1548 return DestOp;
1549
1550 return getZExtOrTrunc(DestOp, DL, VT);
1551}
1552
1554 EVT OpVT) {
1555 if (VT.bitsLE(Op.getValueType()))
1556 return getNode(ISD::TRUNCATE, SL, VT, Op);
1557
1558 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1559 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1560}
1561
1563 EVT OpVT = Op.getValueType();
1564 assert(VT.isInteger() && OpVT.isInteger() &&
1565 "Cannot getZeroExtendInReg FP types");
1566 assert(VT.isVector() == OpVT.isVector() &&
1567 "getZeroExtendInReg type should be vector iff the operand "
1568 "type is vector!");
1569 assert((!VT.isVector() ||
1571 "Vector element counts must match in getZeroExtendInReg");
1572 assert(VT.bitsLE(OpVT) && "Not extending!");
1573 if (OpVT == VT)
1574 return Op;
1576 VT.getScalarSizeInBits());
1577 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1578}
1579
1581 SDValue EVL, const SDLoc &DL,
1582 EVT VT) {
1583 EVT OpVT = Op.getValueType();
1584 assert(VT.isInteger() && OpVT.isInteger() &&
1585 "Cannot getVPZeroExtendInReg FP types");
1586 assert(VT.isVector() && OpVT.isVector() &&
1587 "getVPZeroExtendInReg type and operand type should be vector!");
1589 "Vector element counts must match in getZeroExtendInReg");
1590 assert(VT.bitsLE(OpVT) && "Not extending!");
1591 if (OpVT == VT)
1592 return Op;
1594 VT.getScalarSizeInBits());
1595 return getNode(ISD::VP_AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT), Mask,
1596 EVL);
1597}
1598
1600 // Only unsigned pointer semantics are supported right now. In the future this
1601 // might delegate to TLI to check pointer signedness.
1602 return getZExtOrTrunc(Op, DL, VT);
1603}
1604
1606 // Only unsigned pointer semantics are supported right now. In the future this
1607 // might delegate to TLI to check pointer signedness.
1608 return getZeroExtendInReg(Op, DL, VT);
1609}
1610
1612 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1613}
1614
1615/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1617 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1618}
1619
1621 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1622 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1623}
1624
1626 SDValue Mask, SDValue EVL, EVT VT) {
1627 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1628 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1629}
1630
1632 SDValue Mask, SDValue EVL) {
1633 return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL);
1634}
1635
1637 SDValue Mask, SDValue EVL) {
1638 if (VT.bitsGT(Op.getValueType()))
1639 return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL);
1640 if (VT.bitsLT(Op.getValueType()))
1641 return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL);
1642 return Op;
1643}
1644
1646 EVT OpVT) {
1647 if (!V)
1648 return getConstant(0, DL, VT);
1649
1650 switch (TLI->getBooleanContents(OpVT)) {
1653 return getConstant(1, DL, VT);
1655 return getAllOnesConstant(DL, VT);
1656 }
1657 llvm_unreachable("Unexpected boolean content enum!");
1658}
1659
1661 bool isT, bool isO) {
1662 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1663 DL, VT, isT, isO);
1664}
1665
1667 bool isT, bool isO) {
1668 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1669}
1670
1672 EVT VT, bool isT, bool isO) {
1673 assert(VT.isInteger() && "Cannot create FP integer constant!");
1674
1675 EVT EltVT = VT.getScalarType();
1676 const ConstantInt *Elt = &Val;
1677
1678 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1679 // to-be-splatted scalar ConstantInt.
1680 if (isa<VectorType>(Elt->getType()))
1681 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1682
1683 // In some cases the vector type is legal but the element type is illegal and
1684 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1685 // inserted value (the type does not need to match the vector element type).
1686 // Any extra bits introduced will be truncated away.
1687 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1689 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1690 APInt NewVal;
1691 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1692 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1693 else
1694 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1695 Elt = ConstantInt::get(*getContext(), NewVal);
1696 }
1697 // In other cases the element type is illegal and needs to be expanded, for
1698 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1699 // the value into n parts and use a vector type with n-times the elements.
1700 // Then bitcast to the type requested.
1701 // Legalizing constants too early makes the DAGCombiner's job harder so we
1702 // only legalize if the DAG tells us we must produce legal types.
1703 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1704 TLI->getTypeAction(*getContext(), EltVT) ==
1706 const APInt &NewVal = Elt->getValue();
1707 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1708 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1709
1710 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1711 if (VT.isScalableVector() ||
1712 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1713 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1714 "Can only handle an even split!");
1715 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1716
1717 SmallVector<SDValue, 2> ScalarParts;
1718 for (unsigned i = 0; i != Parts; ++i)
1719 ScalarParts.push_back(getConstant(
1720 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1721 ViaEltVT, isT, isO));
1722
1723 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1724 }
1725
1726 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1727 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1728
1729 // Check the temporary vector is the correct size. If this fails then
1730 // getTypeToTransformTo() probably returned a type whose size (in bits)
1731 // isn't a power-of-2 factor of the requested type size.
1732 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1733
1734 SmallVector<SDValue, 2> EltParts;
1735 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1736 EltParts.push_back(getConstant(
1737 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1738 ViaEltVT, isT, isO));
1739
1740 // EltParts is currently in little endian order. If we actually want
1741 // big-endian order then reverse it now.
1742 if (getDataLayout().isBigEndian())
1743 std::reverse(EltParts.begin(), EltParts.end());
1744
1745 // The elements must be reversed when the element order is different
1746 // to the endianness of the elements (because the BITCAST is itself a
1747 // vector shuffle in this situation). However, we do not need any code to
1748 // perform this reversal because getConstant() is producing a vector
1749 // splat.
1750 // This situation occurs in MIPS MSA.
1751
1753 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1754 llvm::append_range(Ops, EltParts);
1755
1756 SDValue V =
1757 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1758 return V;
1759 }
1760
1761 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1762 "APInt size does not match type size!");
1763 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1764 SDVTList VTs = getVTList(EltVT);
1766 AddNodeIDNode(ID, Opc, VTs, {});
1767 ID.AddPointer(Elt);
1768 ID.AddBoolean(isO);
1769 void *IP = nullptr;
1770 SDNode *N = nullptr;
1771 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1772 if (!VT.isVector())
1773 return SDValue(N, 0);
1774
1775 if (!N) {
1776 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1777 CSEMap.InsertNode(N, IP);
1778 InsertNode(N);
1779 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1780 }
1781
1782 SDValue Result(N, 0);
1783 if (VT.isVector())
1784 Result = getSplat(VT, DL, Result);
1785 return Result;
1786}
1787
1789 bool isT, bool isO) {
1790 unsigned Size = VT.getScalarSizeInBits();
1791 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1792}
1793
1795 bool IsOpaque) {
1797 IsTarget, IsOpaque);
1798}
1799
1801 bool isTarget) {
1802 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1803}
1804
1806 const SDLoc &DL) {
1807 assert(VT.isInteger() && "Shift amount is not an integer type!");
1808 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1809 return getConstant(Val, DL, ShiftVT);
1810}
1811
1813 const SDLoc &DL) {
1814 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1815 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1816}
1817
1819 bool isTarget) {
1820 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1821}
1822
1824 bool isTarget) {
1825 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1826}
1827
1829 EVT VT, bool isTarget) {
1830 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1831
1832 EVT EltVT = VT.getScalarType();
1833 const ConstantFP *Elt = &V;
1834
1835 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1836 // the to-be-splatted scalar ConstantFP.
1837 if (isa<VectorType>(Elt->getType()))
1838 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1839
1840 // Do the map lookup using the actual bit pattern for the floating point
1841 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1842 // we don't have issues with SNANs.
1843 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1844 SDVTList VTs = getVTList(EltVT);
1846 AddNodeIDNode(ID, Opc, VTs, {});
1847 ID.AddPointer(Elt);
1848 void *IP = nullptr;
1849 SDNode *N = nullptr;
1850 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1851 if (!VT.isVector())
1852 return SDValue(N, 0);
1853
1854 if (!N) {
1855 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1856 CSEMap.InsertNode(N, IP);
1857 InsertNode(N);
1858 }
1859
1860 SDValue Result(N, 0);
1861 if (VT.isVector())
1862 Result = getSplat(VT, DL, Result);
1863 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1864 return Result;
1865}
1866
1868 bool isTarget) {
1869 EVT EltVT = VT.getScalarType();
1870 if (EltVT == MVT::f32)
1871 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1872 if (EltVT == MVT::f64)
1873 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1874 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1875 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1876 bool Ignored;
1877 APFloat APF = APFloat(Val);
1879 &Ignored);
1880 return getConstantFP(APF, DL, VT, isTarget);
1881 }
1882 llvm_unreachable("Unsupported type in getConstantFP");
1883}
1884
1886 EVT VT, int64_t Offset, bool isTargetGA,
1887 unsigned TargetFlags) {
1888 assert((TargetFlags == 0 || isTargetGA) &&
1889 "Cannot set target flags on target-independent globals");
1890
1891 // Truncate (with sign-extension) the offset value to the pointer size.
1893 if (BitWidth < 64)
1895
1896 unsigned Opc;
1897 if (GV->isThreadLocal())
1899 else
1901
1902 SDVTList VTs = getVTList(VT);
1904 AddNodeIDNode(ID, Opc, VTs, {});
1905 ID.AddPointer(GV);
1906 ID.AddInteger(Offset);
1907 ID.AddInteger(TargetFlags);
1908 void *IP = nullptr;
1909 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1910 return SDValue(E, 0);
1911
1912 auto *N = newSDNode<GlobalAddressSDNode>(
1913 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1914 CSEMap.InsertNode(N, IP);
1915 InsertNode(N);
1916 return SDValue(N, 0);
1917}
1918
1920 SDVTList VTs = getVTList(MVT::Untyped);
1923 ID.AddPointer(GV);
1924 void *IP = nullptr;
1925 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP))
1926 return SDValue(E, 0);
1927
1928 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1929 CSEMap.InsertNode(N, IP);
1930 InsertNode(N);
1931 return SDValue(N, 0);
1932}
1933
1934SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1935 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1936 SDVTList VTs = getVTList(VT);
1938 AddNodeIDNode(ID, Opc, VTs, {});
1939 ID.AddInteger(FI);
1940 void *IP = nullptr;
1941 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1942 return SDValue(E, 0);
1943
1944 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1945 CSEMap.InsertNode(N, IP);
1946 InsertNode(N);
1947 return SDValue(N, 0);
1948}
1949
1950SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1951 unsigned TargetFlags) {
1952 assert((TargetFlags == 0 || isTarget) &&
1953 "Cannot set target flags on target-independent jump tables");
1954 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1955 SDVTList VTs = getVTList(VT);
1957 AddNodeIDNode(ID, Opc, VTs, {});
1958 ID.AddInteger(JTI);
1959 ID.AddInteger(TargetFlags);
1960 void *IP = nullptr;
1961 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1962 return SDValue(E, 0);
1963
1964 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
1965 CSEMap.InsertNode(N, IP);
1966 InsertNode(N);
1967 return SDValue(N, 0);
1968}
1969
1971 const SDLoc &DL) {
1973 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Glue, Chain,
1974 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
1975}
1976
1978 MaybeAlign Alignment, int Offset,
1979 bool isTarget, unsigned TargetFlags) {
1980 assert((TargetFlags == 0 || isTarget) &&
1981 "Cannot set target flags on target-independent globals");
1982 if (!Alignment)
1983 Alignment = shouldOptForSize()
1984 ? getDataLayout().getABITypeAlign(C->getType())
1985 : getDataLayout().getPrefTypeAlign(C->getType());
1986 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1987 SDVTList VTs = getVTList(VT);
1989 AddNodeIDNode(ID, Opc, VTs, {});
1990 ID.AddInteger(Alignment->value());
1991 ID.AddInteger(Offset);
1992 ID.AddPointer(C);
1993 ID.AddInteger(TargetFlags);
1994 void *IP = nullptr;
1995 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1996 return SDValue(E, 0);
1997
1998 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
1999 TargetFlags);
2000 CSEMap.InsertNode(N, IP);
2001 InsertNode(N);
2002 SDValue V = SDValue(N, 0);
2003 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2004 return V;
2005}
2006
2008 MaybeAlign Alignment, int Offset,
2009 bool isTarget, unsigned TargetFlags) {
2010 assert((TargetFlags == 0 || isTarget) &&
2011 "Cannot set target flags on target-independent globals");
2012 if (!Alignment)
2013 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2014 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2015 SDVTList VTs = getVTList(VT);
2017 AddNodeIDNode(ID, Opc, VTs, {});
2018 ID.AddInteger(Alignment->value());
2019 ID.AddInteger(Offset);
2020 C->addSelectionDAGCSEId(ID);
2021 ID.AddInteger(TargetFlags);
2022 void *IP = nullptr;
2023 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2024 return SDValue(E, 0);
2025
2026 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2027 TargetFlags);
2028 CSEMap.InsertNode(N, IP);
2029 InsertNode(N);
2030 return SDValue(N, 0);
2031}
2032
2035 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), {});
2036 ID.AddPointer(MBB);
2037 void *IP = nullptr;
2038 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2039 return SDValue(E, 0);
2040
2041 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2042 CSEMap.InsertNode(N, IP);
2043 InsertNode(N);
2044 return SDValue(N, 0);
2045}
2046
2048 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2049 ValueTypeNodes.size())
2050 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2051
2052 SDNode *&N = VT.isExtended() ?
2053 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2054
2055 if (N) return SDValue(N, 0);
2056 N = newSDNode<VTSDNode>(VT);
2057 InsertNode(N);
2058 return SDValue(N, 0);
2059}
2060
2062 SDNode *&N = ExternalSymbols[Sym];
2063 if (N) return SDValue(N, 0);
2064 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2065 InsertNode(N);
2066 return SDValue(N, 0);
2067}
2068
2069SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2070 StringRef SymName = TLI->getLibcallImplName(Libcall);
2071 return getExternalSymbol(SymName.data(), VT);
2072}
2073
2075 SDNode *&N = MCSymbols[Sym];
2076 if (N)
2077 return SDValue(N, 0);
2078 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2079 InsertNode(N);
2080 return SDValue(N, 0);
2081}
2082
2084 unsigned TargetFlags) {
2085 SDNode *&N =
2086 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2087 if (N) return SDValue(N, 0);
2088 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2089 InsertNode(N);
2090 return SDValue(N, 0);
2091}
2092
2094 EVT VT, unsigned TargetFlags) {
2095 StringRef SymName = TLI->getLibcallImplName(Libcall);
2096 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2097}
2098
2100 if ((unsigned)Cond >= CondCodeNodes.size())
2101 CondCodeNodes.resize(Cond+1);
2102
2103 if (!CondCodeNodes[Cond]) {
2104 auto *N = newSDNode<CondCodeSDNode>(Cond);
2105 CondCodeNodes[Cond] = N;
2106 InsertNode(N);
2107 }
2108
2109 return SDValue(CondCodeNodes[Cond], 0);
2110}
2111
2113 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2114 "APInt size does not match type size!");
2115
2116 if (MulImm == 0)
2117 return getConstant(0, DL, VT);
2118
2119 const MachineFunction &MF = getMachineFunction();
2120 const Function &F = MF.getFunction();
2121 ConstantRange CR = getVScaleRange(&F, 64);
2122 if (const APInt *C = CR.getSingleElement())
2123 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2124
2125 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2126}
2127
2128/// \returns a value of type \p VT that represents the runtime value of \p
2129/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2130/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2131/// or TypeSize.
2132template <typename Ty>
2134 EVT VT, Ty Quantity) {
2135 if (Quantity.isScalable())
2136 return DAG.getVScale(
2137 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2138
2139 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2140}
2141
2143 ElementCount EC) {
2144 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2145}
2146
2148 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2149}
2150
2152 ElementCount EC) {
2153 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2154 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2155 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2156 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2157}
2158
2160 APInt One(ResVT.getScalarSizeInBits(), 1);
2161 return getStepVector(DL, ResVT, One);
2162}
2163
2165 const APInt &StepVal) {
2166 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2167 if (ResVT.isScalableVector())
2168 return getNode(
2169 ISD::STEP_VECTOR, DL, ResVT,
2170 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2171
2172 SmallVector<SDValue, 16> OpsStepConstants;
2173 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2174 OpsStepConstants.push_back(
2175 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2176 return getBuildVector(ResVT, DL, OpsStepConstants);
2177}
2178
2179/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2180/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2185
2187 SDValue N2, ArrayRef<int> Mask) {
2188 assert(VT.getVectorNumElements() == Mask.size() &&
2189 "Must have the same number of vector elements as mask elements!");
2190 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2191 "Invalid VECTOR_SHUFFLE");
2192
2193 // Canonicalize shuffle undef, undef -> undef
2194 if (N1.isUndef() && N2.isUndef())
2195 return getUNDEF(VT);
2196
2197 // Validate that all indices in Mask are within the range of the elements
2198 // input to the shuffle.
2199 int NElts = Mask.size();
2200 assert(llvm::all_of(Mask,
2201 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2202 "Index out of range");
2203
2204 // Copy the mask so we can do any needed cleanup.
2205 SmallVector<int, 8> MaskVec(Mask);
2206
2207 // Canonicalize shuffle v, v -> v, undef
2208 if (N1 == N2) {
2209 N2 = getUNDEF(VT);
2210 for (int i = 0; i != NElts; ++i)
2211 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2212 }
2213
2214 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2215 if (N1.isUndef())
2216 commuteShuffle(N1, N2, MaskVec);
2217
2218 if (TLI->hasVectorBlend()) {
2219 // If shuffling a splat, try to blend the splat instead. We do this here so
2220 // that even when this arises during lowering we don't have to re-handle it.
2221 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2222 BitVector UndefElements;
2223 SDValue Splat = BV->getSplatValue(&UndefElements);
2224 if (!Splat)
2225 return;
2226
2227 for (int i = 0; i < NElts; ++i) {
2228 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2229 continue;
2230
2231 // If this input comes from undef, mark it as such.
2232 if (UndefElements[MaskVec[i] - Offset]) {
2233 MaskVec[i] = -1;
2234 continue;
2235 }
2236
2237 // If we can blend a non-undef lane, use that instead.
2238 if (!UndefElements[i])
2239 MaskVec[i] = i + Offset;
2240 }
2241 };
2242 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2243 BlendSplat(N1BV, 0);
2244 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2245 BlendSplat(N2BV, NElts);
2246 }
2247
2248 // Canonicalize all index into lhs, -> shuffle lhs, undef
2249 // Canonicalize all index into rhs, -> shuffle rhs, undef
2250 bool AllLHS = true, AllRHS = true;
2251 bool N2Undef = N2.isUndef();
2252 for (int i = 0; i != NElts; ++i) {
2253 if (MaskVec[i] >= NElts) {
2254 if (N2Undef)
2255 MaskVec[i] = -1;
2256 else
2257 AllLHS = false;
2258 } else if (MaskVec[i] >= 0) {
2259 AllRHS = false;
2260 }
2261 }
2262 if (AllLHS && AllRHS)
2263 return getUNDEF(VT);
2264 if (AllLHS && !N2Undef)
2265 N2 = getUNDEF(VT);
2266 if (AllRHS) {
2267 N1 = getUNDEF(VT);
2268 commuteShuffle(N1, N2, MaskVec);
2269 }
2270 // Reset our undef status after accounting for the mask.
2271 N2Undef = N2.isUndef();
2272 // Re-check whether both sides ended up undef.
2273 if (N1.isUndef() && N2Undef)
2274 return getUNDEF(VT);
2275
2276 // If Identity shuffle return that node.
2277 bool Identity = true, AllSame = true;
2278 for (int i = 0; i != NElts; ++i) {
2279 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2280 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2281 }
2282 if (Identity && NElts)
2283 return N1;
2284
2285 // Shuffling a constant splat doesn't change the result.
2286 if (N2Undef) {
2287 SDValue V = N1;
2288
2289 // Look through any bitcasts. We check that these don't change the number
2290 // (and size) of elements and just changes their types.
2291 while (V.getOpcode() == ISD::BITCAST)
2292 V = V->getOperand(0);
2293
2294 // A splat should always show up as a build vector node.
2295 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2296 BitVector UndefElements;
2297 SDValue Splat = BV->getSplatValue(&UndefElements);
2298 // If this is a splat of an undef, shuffling it is also undef.
2299 if (Splat && Splat.isUndef())
2300 return getUNDEF(VT);
2301
2302 bool SameNumElts =
2303 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2304
2305 // We only have a splat which can skip shuffles if there is a splatted
2306 // value and no undef lanes rearranged by the shuffle.
2307 if (Splat && UndefElements.none()) {
2308 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2309 // number of elements match or the value splatted is a zero constant.
2310 if (SameNumElts || isNullConstant(Splat))
2311 return N1;
2312 }
2313
2314 // If the shuffle itself creates a splat, build the vector directly.
2315 if (AllSame && SameNumElts) {
2316 EVT BuildVT = BV->getValueType(0);
2317 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2318 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2319
2320 // We may have jumped through bitcasts, so the type of the
2321 // BUILD_VECTOR may not match the type of the shuffle.
2322 if (BuildVT != VT)
2323 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2324 return NewBV;
2325 }
2326 }
2327 }
2328
2329 SDVTList VTs = getVTList(VT);
2331 SDValue Ops[2] = { N1, N2 };
2333 for (int i = 0; i != NElts; ++i)
2334 ID.AddInteger(MaskVec[i]);
2335
2336 void* IP = nullptr;
2337 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2338 return SDValue(E, 0);
2339
2340 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2341 // SDNode doesn't have access to it. This memory will be "leaked" when
2342 // the node is deallocated, but recovered when the NodeAllocator is released.
2343 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2344 llvm::copy(MaskVec, MaskAlloc);
2345
2346 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2347 dl.getDebugLoc(), MaskAlloc);
2348 createOperands(N, Ops);
2349
2350 CSEMap.InsertNode(N, IP);
2351 InsertNode(N);
2352 SDValue V = SDValue(N, 0);
2353 NewSDValueDbgMsg(V, "Creating new node: ", this);
2354 return V;
2355}
2356
2358 EVT VT = SV.getValueType(0);
2359 SmallVector<int, 8> MaskVec(SV.getMask());
2361
2362 SDValue Op0 = SV.getOperand(0);
2363 SDValue Op1 = SV.getOperand(1);
2364 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2365}
2366
2368 SDVTList VTs = getVTList(VT);
2370 AddNodeIDNode(ID, ISD::Register, VTs, {});
2371 ID.AddInteger(Reg.id());
2372 void *IP = nullptr;
2373 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2374 return SDValue(E, 0);
2375
2376 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2377 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2378 CSEMap.InsertNode(N, IP);
2379 InsertNode(N);
2380 return SDValue(N, 0);
2381}
2382
2385 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), {});
2386 ID.AddPointer(RegMask);
2387 void *IP = nullptr;
2388 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2389 return SDValue(E, 0);
2390
2391 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2392 CSEMap.InsertNode(N, IP);
2393 InsertNode(N);
2394 return SDValue(N, 0);
2395}
2396
2398 MCSymbol *Label) {
2399 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2400}
2401
2402SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2403 SDValue Root, MCSymbol *Label) {
2405 SDValue Ops[] = { Root };
2406 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2407 ID.AddPointer(Label);
2408 void *IP = nullptr;
2409 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2410 return SDValue(E, 0);
2411
2412 auto *N =
2413 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2414 createOperands(N, Ops);
2415
2416 CSEMap.InsertNode(N, IP);
2417 InsertNode(N);
2418 return SDValue(N, 0);
2419}
2420
2422 int64_t Offset, bool isTarget,
2423 unsigned TargetFlags) {
2424 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2425 SDVTList VTs = getVTList(VT);
2426
2428 AddNodeIDNode(ID, Opc, VTs, {});
2429 ID.AddPointer(BA);
2430 ID.AddInteger(Offset);
2431 ID.AddInteger(TargetFlags);
2432 void *IP = nullptr;
2433 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2434 return SDValue(E, 0);
2435
2436 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2437 CSEMap.InsertNode(N, IP);
2438 InsertNode(N);
2439 return SDValue(N, 0);
2440}
2441
2444 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), {});
2445 ID.AddPointer(V);
2446
2447 void *IP = nullptr;
2448 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2449 return SDValue(E, 0);
2450
2451 auto *N = newSDNode<SrcValueSDNode>(V);
2452 CSEMap.InsertNode(N, IP);
2453 InsertNode(N);
2454 return SDValue(N, 0);
2455}
2456
2459 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2460 ID.AddPointer(MD);
2461
2462 void *IP = nullptr;
2463 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2464 return SDValue(E, 0);
2465
2466 auto *N = newSDNode<MDNodeSDNode>(MD);
2467 CSEMap.InsertNode(N, IP);
2468 InsertNode(N);
2469 return SDValue(N, 0);
2470}
2471
2473 if (VT == V.getValueType())
2474 return V;
2475
2476 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2477}
2478
2480 unsigned SrcAS, unsigned DestAS) {
2481 SDVTList VTs = getVTList(VT);
2482 SDValue Ops[] = {Ptr};
2485 ID.AddInteger(SrcAS);
2486 ID.AddInteger(DestAS);
2487
2488 void *IP = nullptr;
2489 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2490 return SDValue(E, 0);
2491
2492 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2493 VTs, SrcAS, DestAS);
2494 createOperands(N, Ops);
2495
2496 CSEMap.InsertNode(N, IP);
2497 InsertNode(N);
2498 return SDValue(N, 0);
2499}
2500
2502 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2503}
2504
2505/// getShiftAmountOperand - Return the specified value casted to
2506/// the target's desired shift amount type.
2508 EVT OpTy = Op.getValueType();
2509 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2510 if (OpTy == ShTy || OpTy.isVector()) return Op;
2511
2512 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2513}
2514
2516 SDLoc dl(Node);
2518 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2519 EVT VT = Node->getValueType(0);
2520 SDValue Tmp1 = Node->getOperand(0);
2521 SDValue Tmp2 = Node->getOperand(1);
2522 const MaybeAlign MA(Node->getConstantOperandVal(3));
2523
2524 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2525 Tmp2, MachinePointerInfo(V));
2526 SDValue VAList = VAListLoad;
2527
2528 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2529 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2530 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2531
2532 VAList = getNode(
2533 ISD::AND, dl, VAList.getValueType(), VAList,
2534 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2535 }
2536
2537 // Increment the pointer, VAList, to the next vaarg
2538 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2539 getConstant(getDataLayout().getTypeAllocSize(
2540 VT.getTypeForEVT(*getContext())),
2541 dl, VAList.getValueType()));
2542 // Store the incremented VAList to the legalized pointer
2543 Tmp1 =
2544 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2545 // Load the actual argument out of the pointer VAList
2546 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2547}
2548
2550 SDLoc dl(Node);
2552 // This defaults to loading a pointer from the input and storing it to the
2553 // output, returning the chain.
2554 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2555 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2556 SDValue Tmp1 =
2557 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2558 Node->getOperand(2), MachinePointerInfo(VS));
2559 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2560 MachinePointerInfo(VD));
2561}
2562
2564 const DataLayout &DL = getDataLayout();
2565 Type *Ty = VT.getTypeForEVT(*getContext());
2566 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2567
2568 if (TLI->isTypeLegal(VT) || !VT.isVector())
2569 return RedAlign;
2570
2571 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2572 const Align StackAlign = TFI->getStackAlign();
2573
2574 // See if we can choose a smaller ABI alignment in cases where it's an
2575 // illegal vector type that will get broken down.
2576 if (RedAlign > StackAlign) {
2577 EVT IntermediateVT;
2578 MVT RegisterVT;
2579 unsigned NumIntermediates;
2580 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2581 NumIntermediates, RegisterVT);
2582 Ty = IntermediateVT.getTypeForEVT(*getContext());
2583 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2584 if (RedAlign2 < RedAlign)
2585 RedAlign = RedAlign2;
2586
2587 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2588 // If the stack is not realignable, the alignment should be limited to the
2589 // StackAlignment
2590 RedAlign = std::min(RedAlign, StackAlign);
2591 }
2592
2593 return RedAlign;
2594}
2595
2597 MachineFrameInfo &MFI = MF->getFrameInfo();
2598 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2599 int StackID = 0;
2600 if (Bytes.isScalable())
2601 StackID = TFI->getStackIDForScalableVectors();
2602 // The stack id gives an indication of whether the object is scalable or
2603 // not, so it's safe to pass in the minimum size here.
2604 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2605 false, nullptr, StackID);
2606 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2607}
2608
2610 Type *Ty = VT.getTypeForEVT(*getContext());
2611 Align StackAlign =
2612 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2613 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2614}
2615
2617 TypeSize VT1Size = VT1.getStoreSize();
2618 TypeSize VT2Size = VT2.getStoreSize();
2619 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2620 "Don't know how to choose the maximum size when creating a stack "
2621 "temporary");
2622 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2623 ? VT1Size
2624 : VT2Size;
2625
2626 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2627 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2628 const DataLayout &DL = getDataLayout();
2629 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2630 return CreateStackTemporary(Bytes, Align);
2631}
2632
2634 ISD::CondCode Cond, const SDLoc &dl) {
2635 EVT OpVT = N1.getValueType();
2636
2637 auto GetUndefBooleanConstant = [&]() {
2638 if (VT.getScalarType() == MVT::i1 ||
2639 TLI->getBooleanContents(OpVT) ==
2641 return getUNDEF(VT);
2642 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2643 // so we cannot use getUNDEF(). Return zero instead.
2644 return getConstant(0, dl, VT);
2645 };
2646
2647 // These setcc operations always fold.
2648 switch (Cond) {
2649 default: break;
2650 case ISD::SETFALSE:
2651 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2652 case ISD::SETTRUE:
2653 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2654
2655 case ISD::SETOEQ:
2656 case ISD::SETOGT:
2657 case ISD::SETOGE:
2658 case ISD::SETOLT:
2659 case ISD::SETOLE:
2660 case ISD::SETONE:
2661 case ISD::SETO:
2662 case ISD::SETUO:
2663 case ISD::SETUEQ:
2664 case ISD::SETUNE:
2665 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2666 break;
2667 }
2668
2669 if (OpVT.isInteger()) {
2670 // For EQ and NE, we can always pick a value for the undef to make the
2671 // predicate pass or fail, so we can return undef.
2672 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2673 // icmp eq/ne X, undef -> undef.
2674 if ((N1.isUndef() || N2.isUndef()) &&
2675 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2676 return GetUndefBooleanConstant();
2677
2678 // If both operands are undef, we can return undef for int comparison.
2679 // icmp undef, undef -> undef.
2680 if (N1.isUndef() && N2.isUndef())
2681 return GetUndefBooleanConstant();
2682
2683 // icmp X, X -> true/false
2684 // icmp X, undef -> true/false because undef could be X.
2685 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2686 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2687 }
2688
2690 const APInt &C2 = N2C->getAPIntValue();
2692 const APInt &C1 = N1C->getAPIntValue();
2693
2695 dl, VT, OpVT);
2696 }
2697 }
2698
2699 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2700 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2701
2702 if (N1CFP && N2CFP) {
2703 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2704 switch (Cond) {
2705 default: break;
2706 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2707 return GetUndefBooleanConstant();
2708 [[fallthrough]];
2709 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2710 OpVT);
2711 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2712 return GetUndefBooleanConstant();
2713 [[fallthrough]];
2715 R==APFloat::cmpLessThan, dl, VT,
2716 OpVT);
2717 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2718 return GetUndefBooleanConstant();
2719 [[fallthrough]];
2720 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2721 OpVT);
2722 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2723 return GetUndefBooleanConstant();
2724 [[fallthrough]];
2726 VT, OpVT);
2727 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2728 return GetUndefBooleanConstant();
2729 [[fallthrough]];
2731 R==APFloat::cmpEqual, dl, VT,
2732 OpVT);
2733 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2734 return GetUndefBooleanConstant();
2735 [[fallthrough]];
2737 R==APFloat::cmpEqual, dl, VT, OpVT);
2738 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2739 OpVT);
2740 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2741 OpVT);
2743 R==APFloat::cmpEqual, dl, VT,
2744 OpVT);
2745 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2746 OpVT);
2748 R==APFloat::cmpLessThan, dl, VT,
2749 OpVT);
2751 R==APFloat::cmpUnordered, dl, VT,
2752 OpVT);
2754 VT, OpVT);
2755 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2756 OpVT);
2757 }
2758 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2759 // Ensure that the constant occurs on the RHS.
2761 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2762 return SDValue();
2763 return getSetCC(dl, VT, N2, N1, SwappedCond);
2764 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2765 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2766 // If an operand is known to be a nan (or undef that could be a nan), we can
2767 // fold it.
2768 // Choosing NaN for the undef will always make unordered comparison succeed
2769 // and ordered comparison fails.
2770 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2771 switch (ISD::getUnorderedFlavor(Cond)) {
2772 default:
2773 llvm_unreachable("Unknown flavor!");
2774 case 0: // Known false.
2775 return getBoolConstant(false, dl, VT, OpVT);
2776 case 1: // Known true.
2777 return getBoolConstant(true, dl, VT, OpVT);
2778 case 2: // Undefined.
2779 return GetUndefBooleanConstant();
2780 }
2781 }
2782
2783 // Could not fold it.
2784 return SDValue();
2785}
2786
2787/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2788/// use this predicate to simplify operations downstream.
2790 unsigned BitWidth = Op.getScalarValueSizeInBits();
2792}
2793
2794// TODO: Should have argument to specify if sign bit of nan is ignorable.
2796 if (Depth >= MaxRecursionDepth)
2797 return false; // Limit search depth.
2798
2799 unsigned Opc = Op.getOpcode();
2800 switch (Opc) {
2801 case ISD::FABS:
2802 return true;
2803 case ISD::AssertNoFPClass: {
2804 FPClassTest NoFPClass =
2805 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2806
2807 const FPClassTest TestMask = fcNan | fcNegative;
2808 return (NoFPClass & TestMask) == TestMask;
2809 }
2810 case ISD::ARITH_FENCE:
2811 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2812 case ISD::FEXP:
2813 case ISD::FEXP2:
2814 case ISD::FEXP10:
2815 return Op->getFlags().hasNoNaNs();
2816 case ISD::FMINNUM:
2817 case ISD::FMINNUM_IEEE:
2818 case ISD::FMINIMUM:
2819 case ISD::FMINIMUMNUM:
2820 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2821 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2822 case ISD::FMAXNUM:
2823 case ISD::FMAXNUM_IEEE:
2824 case ISD::FMAXIMUM:
2825 case ISD::FMAXIMUMNUM:
2826 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2827 // is sufficient.
2828 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2829 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2830 default:
2831 return false;
2832 }
2833
2834 llvm_unreachable("covered opcode switch");
2835}
2836
2837/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2838/// this predicate to simplify operations downstream. Mask is known to be zero
2839/// for bits that V cannot have.
2841 unsigned Depth) const {
2842 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2843}
2844
2845/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2846/// DemandedElts. We use this predicate to simplify operations downstream.
2847/// Mask is known to be zero for bits that V cannot have.
2849 const APInt &DemandedElts,
2850 unsigned Depth) const {
2851 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2852}
2853
2854/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2855/// DemandedElts. We use this predicate to simplify operations downstream.
2857 unsigned Depth /* = 0 */) const {
2858 return computeKnownBits(V, DemandedElts, Depth).isZero();
2859}
2860
2861/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2863 unsigned Depth) const {
2864 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2865}
2866
2868 const APInt &DemandedElts,
2869 unsigned Depth) const {
2870 EVT VT = Op.getValueType();
2871 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2872
2873 unsigned NumElts = VT.getVectorNumElements();
2874 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2875
2876 APInt KnownZeroElements = APInt::getZero(NumElts);
2877 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2878 if (!DemandedElts[EltIdx])
2879 continue; // Don't query elements that are not demanded.
2880 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2881 if (MaskedVectorIsZero(Op, Mask, Depth))
2882 KnownZeroElements.setBit(EltIdx);
2883 }
2884 return KnownZeroElements;
2885}
2886
2887/// isSplatValue - Return true if the vector V has the same value
2888/// across all DemandedElts. For scalable vectors, we don't know the
2889/// number of lanes at compile time. Instead, we use a 1 bit APInt
2890/// to represent a conservative value for all lanes; that is, that
2891/// one bit value is implicitly splatted across all lanes.
2892bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2893 APInt &UndefElts, unsigned Depth) const {
2894 unsigned Opcode = V.getOpcode();
2895 EVT VT = V.getValueType();
2896 assert(VT.isVector() && "Vector type expected");
2897 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2898 "scalable demanded bits are ignored");
2899
2900 if (!DemandedElts)
2901 return false; // No demanded elts, better to assume we don't know anything.
2902
2903 if (Depth >= MaxRecursionDepth)
2904 return false; // Limit search depth.
2905
2906 // Deal with some common cases here that work for both fixed and scalable
2907 // vector types.
2908 switch (Opcode) {
2909 case ISD::SPLAT_VECTOR:
2910 UndefElts = V.getOperand(0).isUndef()
2911 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2912 : APInt(DemandedElts.getBitWidth(), 0);
2913 return true;
2914 case ISD::ADD:
2915 case ISD::SUB:
2916 case ISD::AND:
2917 case ISD::XOR:
2918 case ISD::OR: {
2919 APInt UndefLHS, UndefRHS;
2920 SDValue LHS = V.getOperand(0);
2921 SDValue RHS = V.getOperand(1);
2922 // Only recognize splats with the same demanded undef elements for both
2923 // operands, otherwise we might fail to handle binop-specific undef
2924 // handling.
2925 // e.g. (and undef, 0) -> 0 etc.
2926 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2927 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2928 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2929 UndefElts = UndefLHS | UndefRHS;
2930 return true;
2931 }
2932 return false;
2933 }
2934 case ISD::ABS:
2935 case ISD::TRUNCATE:
2936 case ISD::SIGN_EXTEND:
2937 case ISD::ZERO_EXTEND:
2938 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2939 default:
2940 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2941 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2942 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
2943 Depth);
2944 break;
2945 }
2946
2947 // We don't support other cases than those above for scalable vectors at
2948 // the moment.
2949 if (VT.isScalableVector())
2950 return false;
2951
2952 unsigned NumElts = VT.getVectorNumElements();
2953 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2954 UndefElts = APInt::getZero(NumElts);
2955
2956 switch (Opcode) {
2957 case ISD::BUILD_VECTOR: {
2958 SDValue Scl;
2959 for (unsigned i = 0; i != NumElts; ++i) {
2960 SDValue Op = V.getOperand(i);
2961 if (Op.isUndef()) {
2962 UndefElts.setBit(i);
2963 continue;
2964 }
2965 if (!DemandedElts[i])
2966 continue;
2967 if (Scl && Scl != Op)
2968 return false;
2969 Scl = Op;
2970 }
2971 return true;
2972 }
2973 case ISD::VECTOR_SHUFFLE: {
2974 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2975 APInt DemandedLHS = APInt::getZero(NumElts);
2976 APInt DemandedRHS = APInt::getZero(NumElts);
2977 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2978 for (int i = 0; i != (int)NumElts; ++i) {
2979 int M = Mask[i];
2980 if (M < 0) {
2981 UndefElts.setBit(i);
2982 continue;
2983 }
2984 if (!DemandedElts[i])
2985 continue;
2986 if (M < (int)NumElts)
2987 DemandedLHS.setBit(M);
2988 else
2989 DemandedRHS.setBit(M - NumElts);
2990 }
2991
2992 // If we aren't demanding either op, assume there's no splat.
2993 // If we are demanding both ops, assume there's no splat.
2994 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2995 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2996 return false;
2997
2998 // See if the demanded elts of the source op is a splat or we only demand
2999 // one element, which should always be a splat.
3000 // TODO: Handle source ops splats with undefs.
3001 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3002 APInt SrcUndefs;
3003 return (SrcElts.popcount() == 1) ||
3004 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3005 (SrcElts & SrcUndefs).isZero());
3006 };
3007 if (!DemandedLHS.isZero())
3008 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3009 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3010 }
3012 // Offset the demanded elts by the subvector index.
3013 SDValue Src = V.getOperand(0);
3014 // We don't support scalable vectors at the moment.
3015 if (Src.getValueType().isScalableVector())
3016 return false;
3017 uint64_t Idx = V.getConstantOperandVal(1);
3018 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3019 APInt UndefSrcElts;
3020 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3021 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3022 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3023 return true;
3024 }
3025 break;
3026 }
3030 // Widen the demanded elts by the src element count.
3031 SDValue Src = V.getOperand(0);
3032 // We don't support scalable vectors at the moment.
3033 if (Src.getValueType().isScalableVector())
3034 return false;
3035 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3036 APInt UndefSrcElts;
3037 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3038 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3039 UndefElts = UndefSrcElts.trunc(NumElts);
3040 return true;
3041 }
3042 break;
3043 }
3044 case ISD::BITCAST: {
3045 SDValue Src = V.getOperand(0);
3046 EVT SrcVT = Src.getValueType();
3047 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3048 unsigned BitWidth = VT.getScalarSizeInBits();
3049
3050 // Ignore bitcasts from unsupported types.
3051 // TODO: Add fp support?
3052 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3053 break;
3054
3055 // Bitcast 'small element' vector to 'large element' vector.
3056 if ((BitWidth % SrcBitWidth) == 0) {
3057 // See if each sub element is a splat.
3058 unsigned Scale = BitWidth / SrcBitWidth;
3059 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3060 APInt ScaledDemandedElts =
3061 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3062 for (unsigned I = 0; I != Scale; ++I) {
3063 APInt SubUndefElts;
3064 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3065 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3066 SubDemandedElts &= ScaledDemandedElts;
3067 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3068 return false;
3069 // TODO: Add support for merging sub undef elements.
3070 if (!SubUndefElts.isZero())
3071 return false;
3072 }
3073 return true;
3074 }
3075 break;
3076 }
3077 }
3078
3079 return false;
3080}
3081
3082/// Helper wrapper to main isSplatValue function.
3083bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3084 EVT VT = V.getValueType();
3085 assert(VT.isVector() && "Vector type expected");
3086
3087 APInt UndefElts;
3088 // Since the number of lanes in a scalable vector is unknown at compile time,
3089 // we track one bit which is implicitly broadcast to all lanes. This means
3090 // that all lanes in a scalable vector are considered demanded.
3091 APInt DemandedElts
3093 return isSplatValue(V, DemandedElts, UndefElts) &&
3094 (AllowUndefs || !UndefElts);
3095}
3096
3099
3100 EVT VT = V.getValueType();
3101 unsigned Opcode = V.getOpcode();
3102 switch (Opcode) {
3103 default: {
3104 APInt UndefElts;
3105 // Since the number of lanes in a scalable vector is unknown at compile time,
3106 // we track one bit which is implicitly broadcast to all lanes. This means
3107 // that all lanes in a scalable vector are considered demanded.
3108 APInt DemandedElts
3110
3111 if (isSplatValue(V, DemandedElts, UndefElts)) {
3112 if (VT.isScalableVector()) {
3113 // DemandedElts and UndefElts are ignored for scalable vectors, since
3114 // the only supported cases are SPLAT_VECTOR nodes.
3115 SplatIdx = 0;
3116 } else {
3117 // Handle case where all demanded elements are UNDEF.
3118 if (DemandedElts.isSubsetOf(UndefElts)) {
3119 SplatIdx = 0;
3120 return getUNDEF(VT);
3121 }
3122 SplatIdx = (UndefElts & DemandedElts).countr_one();
3123 }
3124 return V;
3125 }
3126 break;
3127 }
3128 case ISD::SPLAT_VECTOR:
3129 SplatIdx = 0;
3130 return V;
3131 case ISD::VECTOR_SHUFFLE: {
3132 assert(!VT.isScalableVector());
3133 // Check if this is a shuffle node doing a splat.
3134 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3135 // getTargetVShiftNode currently struggles without the splat source.
3136 auto *SVN = cast<ShuffleVectorSDNode>(V);
3137 if (!SVN->isSplat())
3138 break;
3139 int Idx = SVN->getSplatIndex();
3140 int NumElts = V.getValueType().getVectorNumElements();
3141 SplatIdx = Idx % NumElts;
3142 return V.getOperand(Idx / NumElts);
3143 }
3144 }
3145
3146 return SDValue();
3147}
3148
3150 int SplatIdx;
3151 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3152 EVT SVT = SrcVector.getValueType().getScalarType();
3153 EVT LegalSVT = SVT;
3154 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3155 if (!SVT.isInteger())
3156 return SDValue();
3157 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3158 if (LegalSVT.bitsLT(SVT))
3159 return SDValue();
3160 }
3161 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3162 }
3163 return SDValue();
3164}
3165
3166std::optional<ConstantRange>
3168 unsigned Depth) const {
3169 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3170 V.getOpcode() == ISD::SRA) &&
3171 "Unknown shift node");
3172 // Shifting more than the bitwidth is not valid.
3173 unsigned BitWidth = V.getScalarValueSizeInBits();
3174
3175 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3176 const APInt &ShAmt = Cst->getAPIntValue();
3177 if (ShAmt.uge(BitWidth))
3178 return std::nullopt;
3179 return ConstantRange(ShAmt);
3180 }
3181
3182 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3183 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3184 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3185 if (!DemandedElts[i])
3186 continue;
3187 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3188 if (!SA) {
3189 MinAmt = MaxAmt = nullptr;
3190 break;
3191 }
3192 const APInt &ShAmt = SA->getAPIntValue();
3193 if (ShAmt.uge(BitWidth))
3194 return std::nullopt;
3195 if (!MinAmt || MinAmt->ugt(ShAmt))
3196 MinAmt = &ShAmt;
3197 if (!MaxAmt || MaxAmt->ult(ShAmt))
3198 MaxAmt = &ShAmt;
3199 }
3200 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3201 "Failed to find matching min/max shift amounts");
3202 if (MinAmt && MaxAmt)
3203 return ConstantRange(*MinAmt, *MaxAmt + 1);
3204 }
3205
3206 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3207 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3208 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3209 if (KnownAmt.getMaxValue().ult(BitWidth))
3210 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3211
3212 return std::nullopt;
3213}
3214
3215std::optional<unsigned>
3217 unsigned Depth) const {
3218 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3219 V.getOpcode() == ISD::SRA) &&
3220 "Unknown shift node");
3221 if (std::optional<ConstantRange> AmtRange =
3222 getValidShiftAmountRange(V, DemandedElts, Depth))
3223 if (const APInt *ShAmt = AmtRange->getSingleElement())
3224 return ShAmt->getZExtValue();
3225 return std::nullopt;
3226}
3227
3228std::optional<unsigned>
3230 EVT VT = V.getValueType();
3231 APInt DemandedElts = VT.isFixedLengthVector()
3233 : APInt(1, 1);
3234 return getValidShiftAmount(V, DemandedElts, Depth);
3235}
3236
3237std::optional<unsigned>
3239 unsigned Depth) const {
3240 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3241 V.getOpcode() == ISD::SRA) &&
3242 "Unknown shift node");
3243 if (std::optional<ConstantRange> AmtRange =
3244 getValidShiftAmountRange(V, DemandedElts, Depth))
3245 return AmtRange->getUnsignedMin().getZExtValue();
3246 return std::nullopt;
3247}
3248
3249std::optional<unsigned>
3251 EVT VT = V.getValueType();
3252 APInt DemandedElts = VT.isFixedLengthVector()
3254 : APInt(1, 1);
3255 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3256}
3257
3258std::optional<unsigned>
3260 unsigned Depth) const {
3261 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3262 V.getOpcode() == ISD::SRA) &&
3263 "Unknown shift node");
3264 if (std::optional<ConstantRange> AmtRange =
3265 getValidShiftAmountRange(V, DemandedElts, Depth))
3266 return AmtRange->getUnsignedMax().getZExtValue();
3267 return std::nullopt;
3268}
3269
3270std::optional<unsigned>
3272 EVT VT = V.getValueType();
3273 APInt DemandedElts = VT.isFixedLengthVector()
3275 : APInt(1, 1);
3276 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3277}
3278
3279/// Determine which bits of Op are known to be either zero or one and return
3280/// them in Known. For vectors, the known bits are those that are shared by
3281/// every vector element.
3283 EVT VT = Op.getValueType();
3284
3285 // Since the number of lanes in a scalable vector is unknown at compile time,
3286 // we track one bit which is implicitly broadcast to all lanes. This means
3287 // that all lanes in a scalable vector are considered demanded.
3288 APInt DemandedElts = VT.isFixedLengthVector()
3290 : APInt(1, 1);
3291 return computeKnownBits(Op, DemandedElts, Depth);
3292}
3293
3294/// Determine which bits of Op are known to be either zero or one and return
3295/// them in Known. The DemandedElts argument allows us to only collect the known
3296/// bits that are shared by the requested vector elements.
3298 unsigned Depth) const {
3299 unsigned BitWidth = Op.getScalarValueSizeInBits();
3300
3301 KnownBits Known(BitWidth); // Don't know anything.
3302
3303 if (auto OptAPInt = Op->bitcastToAPInt()) {
3304 // We know all of the bits for a constant!
3305 return KnownBits::makeConstant(*std::move(OptAPInt));
3306 }
3307
3308 if (Depth >= MaxRecursionDepth)
3309 return Known; // Limit search depth.
3310
3311 KnownBits Known2;
3312 unsigned NumElts = DemandedElts.getBitWidth();
3313 assert((!Op.getValueType().isFixedLengthVector() ||
3314 NumElts == Op.getValueType().getVectorNumElements()) &&
3315 "Unexpected vector size");
3316
3317 if (!DemandedElts)
3318 return Known; // No demanded elts, better to assume we don't know anything.
3319
3320 unsigned Opcode = Op.getOpcode();
3321 switch (Opcode) {
3322 case ISD::MERGE_VALUES:
3323 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3324 Depth + 1);
3325 case ISD::SPLAT_VECTOR: {
3326 SDValue SrcOp = Op.getOperand(0);
3327 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3328 "Expected SPLAT_VECTOR implicit truncation");
3329 // Implicitly truncate the bits to match the official semantics of
3330 // SPLAT_VECTOR.
3331 Known = computeKnownBits(SrcOp, Depth + 1).trunc(BitWidth);
3332 break;
3333 }
3335 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3336 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3337 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3338 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3339 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3340 }
3341 break;
3342 }
3343 case ISD::STEP_VECTOR: {
3344 const APInt &Step = Op.getConstantOperandAPInt(0);
3345
3346 if (Step.isPowerOf2())
3347 Known.Zero.setLowBits(Step.logBase2());
3348
3350
3351 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3352 break;
3353 const APInt MinNumElts =
3354 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3355
3356 bool Overflow;
3357 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3359 .umul_ov(MinNumElts, Overflow);
3360 if (Overflow)
3361 break;
3362
3363 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3364 if (Overflow)
3365 break;
3366
3367 Known.Zero.setHighBits(MaxValue.countl_zero());
3368 break;
3369 }
3370 case ISD::BUILD_VECTOR:
3371 assert(!Op.getValueType().isScalableVector());
3372 // Collect the known bits that are shared by every demanded vector element.
3373 Known.setAllConflict();
3374 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3375 if (!DemandedElts[i])
3376 continue;
3377
3378 SDValue SrcOp = Op.getOperand(i);
3379 Known2 = computeKnownBits(SrcOp, Depth + 1);
3380
3381 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3382 if (SrcOp.getValueSizeInBits() != BitWidth) {
3383 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3384 "Expected BUILD_VECTOR implicit truncation");
3385 Known2 = Known2.trunc(BitWidth);
3386 }
3387
3388 // Known bits are the values that are shared by every demanded element.
3389 Known = Known.intersectWith(Known2);
3390
3391 // If we don't know any bits, early out.
3392 if (Known.isUnknown())
3393 break;
3394 }
3395 break;
3396 case ISD::VECTOR_COMPRESS: {
3397 SDValue Vec = Op.getOperand(0);
3398 SDValue PassThru = Op.getOperand(2);
3399 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3400 // If we don't know any bits, early out.
3401 if (Known.isUnknown())
3402 break;
3403 Known2 = computeKnownBits(Vec, Depth + 1);
3404 Known = Known.intersectWith(Known2);
3405 break;
3406 }
3407 case ISD::VECTOR_SHUFFLE: {
3408 assert(!Op.getValueType().isScalableVector());
3409 // Collect the known bits that are shared by every vector element referenced
3410 // by the shuffle.
3411 APInt DemandedLHS, DemandedRHS;
3413 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3414 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3415 DemandedLHS, DemandedRHS))
3416 break;
3417
3418 // Known bits are the values that are shared by every demanded element.
3419 Known.setAllConflict();
3420 if (!!DemandedLHS) {
3421 SDValue LHS = Op.getOperand(0);
3422 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3423 Known = Known.intersectWith(Known2);
3424 }
3425 // If we don't know any bits, early out.
3426 if (Known.isUnknown())
3427 break;
3428 if (!!DemandedRHS) {
3429 SDValue RHS = Op.getOperand(1);
3430 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3431 Known = Known.intersectWith(Known2);
3432 }
3433 break;
3434 }
3435 case ISD::VSCALE: {
3437 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3438 Known = getVScaleRange(&F, BitWidth).multiply(Multiplier).toKnownBits();
3439 break;
3440 }
3441 case ISD::CONCAT_VECTORS: {
3442 if (Op.getValueType().isScalableVector())
3443 break;
3444 // Split DemandedElts and test each of the demanded subvectors.
3445 Known.setAllConflict();
3446 EVT SubVectorVT = Op.getOperand(0).getValueType();
3447 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3448 unsigned NumSubVectors = Op.getNumOperands();
3449 for (unsigned i = 0; i != NumSubVectors; ++i) {
3450 APInt DemandedSub =
3451 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3452 if (!!DemandedSub) {
3453 SDValue Sub = Op.getOperand(i);
3454 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3455 Known = Known.intersectWith(Known2);
3456 }
3457 // If we don't know any bits, early out.
3458 if (Known.isUnknown())
3459 break;
3460 }
3461 break;
3462 }
3463 case ISD::INSERT_SUBVECTOR: {
3464 if (Op.getValueType().isScalableVector())
3465 break;
3466 // Demand any elements from the subvector and the remainder from the src its
3467 // inserted into.
3468 SDValue Src = Op.getOperand(0);
3469 SDValue Sub = Op.getOperand(1);
3470 uint64_t Idx = Op.getConstantOperandVal(2);
3471 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3472 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3473 APInt DemandedSrcElts = DemandedElts;
3474 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3475
3476 Known.setAllConflict();
3477 if (!!DemandedSubElts) {
3478 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3479 if (Known.isUnknown())
3480 break; // early-out.
3481 }
3482 if (!!DemandedSrcElts) {
3483 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3484 Known = Known.intersectWith(Known2);
3485 }
3486 break;
3487 }
3489 // Offset the demanded elts by the subvector index.
3490 SDValue Src = Op.getOperand(0);
3491 // Bail until we can represent demanded elements for scalable vectors.
3492 if (Op.getValueType().isScalableVector() || Src.getValueType().isScalableVector())
3493 break;
3494 uint64_t Idx = Op.getConstantOperandVal(1);
3495 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3496 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3497 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3498 break;
3499 }
3500 case ISD::SCALAR_TO_VECTOR: {
3501 if (Op.getValueType().isScalableVector())
3502 break;
3503 // We know about scalar_to_vector as much as we know about it source,
3504 // which becomes the first element of otherwise unknown vector.
3505 if (DemandedElts != 1)
3506 break;
3507
3508 SDValue N0 = Op.getOperand(0);
3509 Known = computeKnownBits(N0, Depth + 1);
3510 if (N0.getValueSizeInBits() != BitWidth)
3511 Known = Known.trunc(BitWidth);
3512
3513 break;
3514 }
3515 case ISD::BITCAST: {
3516 if (Op.getValueType().isScalableVector())
3517 break;
3518
3519 SDValue N0 = Op.getOperand(0);
3520 EVT SubVT = N0.getValueType();
3521 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3522
3523 // Ignore bitcasts from unsupported types.
3524 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3525 break;
3526
3527 // Fast handling of 'identity' bitcasts.
3528 if (BitWidth == SubBitWidth) {
3529 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3530 break;
3531 }
3532
3533 bool IsLE = getDataLayout().isLittleEndian();
3534
3535 // Bitcast 'small element' vector to 'large element' scalar/vector.
3536 if ((BitWidth % SubBitWidth) == 0) {
3537 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3538
3539 // Collect known bits for the (larger) output by collecting the known
3540 // bits from each set of sub elements and shift these into place.
3541 // We need to separately call computeKnownBits for each set of
3542 // sub elements as the knownbits for each is likely to be different.
3543 unsigned SubScale = BitWidth / SubBitWidth;
3544 APInt SubDemandedElts(NumElts * SubScale, 0);
3545 for (unsigned i = 0; i != NumElts; ++i)
3546 if (DemandedElts[i])
3547 SubDemandedElts.setBit(i * SubScale);
3548
3549 for (unsigned i = 0; i != SubScale; ++i) {
3550 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3551 Depth + 1);
3552 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3553 Known.insertBits(Known2, SubBitWidth * Shifts);
3554 }
3555 }
3556
3557 // Bitcast 'large element' scalar/vector to 'small element' vector.
3558 if ((SubBitWidth % BitWidth) == 0) {
3559 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3560
3561 // Collect known bits for the (smaller) output by collecting the known
3562 // bits from the overlapping larger input elements and extracting the
3563 // sub sections we actually care about.
3564 unsigned SubScale = SubBitWidth / BitWidth;
3565 APInt SubDemandedElts =
3566 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3567 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3568
3569 Known.setAllConflict();
3570 for (unsigned i = 0; i != NumElts; ++i)
3571 if (DemandedElts[i]) {
3572 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3573 unsigned Offset = (Shifts % SubScale) * BitWidth;
3574 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3575 // If we don't know any bits, early out.
3576 if (Known.isUnknown())
3577 break;
3578 }
3579 }
3580 break;
3581 }
3582 case ISD::AND:
3583 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3584 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3585
3586 Known &= Known2;
3587 break;
3588 case ISD::OR:
3589 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3590 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3591
3592 Known |= Known2;
3593 break;
3594 case ISD::XOR:
3595 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3596 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3597
3598 Known ^= Known2;
3599 break;
3600 case ISD::MUL: {
3601 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3602 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3603 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3604 // TODO: SelfMultiply can be poison, but not undef.
3605 if (SelfMultiply)
3606 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3607 Op.getOperand(0), DemandedElts, false, Depth + 1);
3608 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3609
3610 // If the multiplication is known not to overflow, the product of a number
3611 // with itself is non-negative. Only do this if we didn't already computed
3612 // the opposite value for the sign bit.
3613 if (Op->getFlags().hasNoSignedWrap() &&
3614 Op.getOperand(0) == Op.getOperand(1) &&
3615 !Known.isNegative())
3616 Known.makeNonNegative();
3617 break;
3618 }
3619 case ISD::MULHU: {
3620 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3621 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3622 Known = KnownBits::mulhu(Known, Known2);
3623 break;
3624 }
3625 case ISD::MULHS: {
3626 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3627 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3628 Known = KnownBits::mulhs(Known, Known2);
3629 break;
3630 }
3631 case ISD::ABDU: {
3632 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3633 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3634 Known = KnownBits::abdu(Known, Known2);
3635 break;
3636 }
3637 case ISD::ABDS: {
3638 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3639 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3640 Known = KnownBits::abds(Known, Known2);
3641 unsigned SignBits1 =
3642 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3643 if (SignBits1 == 1)
3644 break;
3645 unsigned SignBits0 =
3646 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3647 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3648 break;
3649 }
3650 case ISD::UMUL_LOHI: {
3651 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3652 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3653 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3654 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3655 if (Op.getResNo() == 0)
3656 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3657 else
3658 Known = KnownBits::mulhu(Known, Known2);
3659 break;
3660 }
3661 case ISD::SMUL_LOHI: {
3662 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3663 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3664 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3665 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3666 if (Op.getResNo() == 0)
3667 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3668 else
3669 Known = KnownBits::mulhs(Known, Known2);
3670 break;
3671 }
3672 case ISD::AVGFLOORU: {
3673 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3674 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3675 Known = KnownBits::avgFloorU(Known, Known2);
3676 break;
3677 }
3678 case ISD::AVGCEILU: {
3679 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3680 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3681 Known = KnownBits::avgCeilU(Known, Known2);
3682 break;
3683 }
3684 case ISD::AVGFLOORS: {
3685 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3686 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3687 Known = KnownBits::avgFloorS(Known, Known2);
3688 break;
3689 }
3690 case ISD::AVGCEILS: {
3691 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3692 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3693 Known = KnownBits::avgCeilS(Known, Known2);
3694 break;
3695 }
3696 case ISD::SELECT:
3697 case ISD::VSELECT:
3698 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3699 // If we don't know any bits, early out.
3700 if (Known.isUnknown())
3701 break;
3702 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3703
3704 // Only known if known in both the LHS and RHS.
3705 Known = Known.intersectWith(Known2);
3706 break;
3707 case ISD::SELECT_CC:
3708 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3709 // If we don't know any bits, early out.
3710 if (Known.isUnknown())
3711 break;
3712 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3713
3714 // Only known if known in both the LHS and RHS.
3715 Known = Known.intersectWith(Known2);
3716 break;
3717 case ISD::SMULO:
3718 case ISD::UMULO:
3719 if (Op.getResNo() != 1)
3720 break;
3721 // The boolean result conforms to getBooleanContents.
3722 // If we know the result of a setcc has the top bits zero, use this info.
3723 // We know that we have an integer-based boolean since these operations
3724 // are only available for integer.
3725 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3727 BitWidth > 1)
3728 Known.Zero.setBitsFrom(1);
3729 break;
3730 case ISD::SETCC:
3731 case ISD::SETCCCARRY:
3732 case ISD::STRICT_FSETCC:
3733 case ISD::STRICT_FSETCCS: {
3734 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3735 // If we know the result of a setcc has the top bits zero, use this info.
3736 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3738 BitWidth > 1)
3739 Known.Zero.setBitsFrom(1);
3740 break;
3741 }
3742 case ISD::SHL: {
3743 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3744 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3745
3746 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3747 bool NSW = Op->getFlags().hasNoSignedWrap();
3748
3749 bool ShAmtNonZero = Known2.isNonZero();
3750
3751 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3752
3753 // Minimum shift low bits are known zero.
3754 if (std::optional<unsigned> ShMinAmt =
3755 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3756 Known.Zero.setLowBits(*ShMinAmt);
3757 break;
3758 }
3759 case ISD::SRL:
3760 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3761 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3762 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3763 Op->getFlags().hasExact());
3764
3765 // Minimum shift high bits are known zero.
3766 if (std::optional<unsigned> ShMinAmt =
3767 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3768 Known.Zero.setHighBits(*ShMinAmt);
3769 break;
3770 case ISD::SRA:
3771 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3772 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3773 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3774 Op->getFlags().hasExact());
3775 break;
3776 case ISD::ROTL:
3777 case ISD::ROTR:
3778 if (ConstantSDNode *C =
3779 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3780 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3781
3782 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3783
3784 // Canonicalize to ROTR.
3785 if (Opcode == ISD::ROTL && Amt != 0)
3786 Amt = BitWidth - Amt;
3787
3788 Known.Zero = Known.Zero.rotr(Amt);
3789 Known.One = Known.One.rotr(Amt);
3790 }
3791 break;
3792 case ISD::FSHL:
3793 case ISD::FSHR:
3794 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3795 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3796
3797 // For fshl, 0-shift returns the 1st arg.
3798 // For fshr, 0-shift returns the 2nd arg.
3799 if (Amt == 0) {
3800 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3801 DemandedElts, Depth + 1);
3802 break;
3803 }
3804
3805 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3806 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3807 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3808 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3809 if (Opcode == ISD::FSHL) {
3810 Known <<= Amt;
3811 Known2 >>= BitWidth - Amt;
3812 } else {
3813 Known <<= BitWidth - Amt;
3814 Known2 >>= Amt;
3815 }
3816 Known = Known.unionWith(Known2);
3817 }
3818 break;
3819 case ISD::SHL_PARTS:
3820 case ISD::SRA_PARTS:
3821 case ISD::SRL_PARTS: {
3822 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3823
3824 // Collect lo/hi source values and concatenate.
3825 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3826 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3827 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3828 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3829 Known = Known2.concat(Known);
3830
3831 // Collect shift amount.
3832 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3833
3834 if (Opcode == ISD::SHL_PARTS)
3835 Known = KnownBits::shl(Known, Known2);
3836 else if (Opcode == ISD::SRA_PARTS)
3837 Known = KnownBits::ashr(Known, Known2);
3838 else // if (Opcode == ISD::SRL_PARTS)
3839 Known = KnownBits::lshr(Known, Known2);
3840
3841 // TODO: Minimum shift low/high bits are known zero.
3842
3843 if (Op.getResNo() == 0)
3844 Known = Known.extractBits(LoBits, 0);
3845 else
3846 Known = Known.extractBits(HiBits, LoBits);
3847 break;
3848 }
3850 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3851 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3852 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3853 break;
3854 }
3855 case ISD::CTTZ:
3856 case ISD::CTTZ_ZERO_UNDEF: {
3857 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3858 // If we have a known 1, its position is our upper bound.
3859 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3860 unsigned LowBits = llvm::bit_width(PossibleTZ);
3861 Known.Zero.setBitsFrom(LowBits);
3862 break;
3863 }
3864 case ISD::CTLZ:
3865 case ISD::CTLZ_ZERO_UNDEF: {
3866 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3867 // If we have a known 1, its position is our upper bound.
3868 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3869 unsigned LowBits = llvm::bit_width(PossibleLZ);
3870 Known.Zero.setBitsFrom(LowBits);
3871 break;
3872 }
3873 case ISD::CTPOP: {
3874 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3875 // If we know some of the bits are zero, they can't be one.
3876 unsigned PossibleOnes = Known2.countMaxPopulation();
3877 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3878 break;
3879 }
3880 case ISD::PARITY: {
3881 // Parity returns 0 everywhere but the LSB.
3882 Known.Zero.setBitsFrom(1);
3883 break;
3884 }
3885 case ISD::MGATHER:
3886 case ISD::MLOAD: {
3887 ISD::LoadExtType ETy =
3888 (Opcode == ISD::MGATHER)
3889 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3890 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3891 if (ETy == ISD::ZEXTLOAD) {
3892 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3893 KnownBits Known0(MemVT.getScalarSizeInBits());
3894 return Known0.zext(BitWidth);
3895 }
3896 break;
3897 }
3898 case ISD::LOAD: {
3900 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3901 if (ISD::isNON_EXTLoad(LD) && Cst) {
3902 // Determine any common known bits from the loaded constant pool value.
3903 Type *CstTy = Cst->getType();
3904 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3905 !Op.getValueType().isScalableVector()) {
3906 // If its a vector splat, then we can (quickly) reuse the scalar path.
3907 // NOTE: We assume all elements match and none are UNDEF.
3908 if (CstTy->isVectorTy()) {
3909 if (const Constant *Splat = Cst->getSplatValue()) {
3910 Cst = Splat;
3911 CstTy = Cst->getType();
3912 }
3913 }
3914 // TODO - do we need to handle different bitwidths?
3915 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3916 // Iterate across all vector elements finding common known bits.
3917 Known.setAllConflict();
3918 for (unsigned i = 0; i != NumElts; ++i) {
3919 if (!DemandedElts[i])
3920 continue;
3921 if (Constant *Elt = Cst->getAggregateElement(i)) {
3922 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3923 const APInt &Value = CInt->getValue();
3924 Known.One &= Value;
3925 Known.Zero &= ~Value;
3926 continue;
3927 }
3928 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3929 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3930 Known.One &= Value;
3931 Known.Zero &= ~Value;
3932 continue;
3933 }
3934 }
3935 Known.One.clearAllBits();
3936 Known.Zero.clearAllBits();
3937 break;
3938 }
3939 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3940 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3941 Known = KnownBits::makeConstant(CInt->getValue());
3942 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3943 Known =
3944 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3945 }
3946 }
3947 }
3948 } else if (Op.getResNo() == 0) {
3949 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
3950 KnownBits KnownScalarMemory(ScalarMemorySize);
3951 if (const MDNode *MD = LD->getRanges())
3952 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
3953
3954 // Extend the Known bits from memory to the size of the scalar result.
3955 if (ISD::isZEXTLoad(Op.getNode()))
3956 Known = KnownScalarMemory.zext(BitWidth);
3957 else if (ISD::isSEXTLoad(Op.getNode()))
3958 Known = KnownScalarMemory.sext(BitWidth);
3959 else if (ISD::isEXTLoad(Op.getNode()))
3960 Known = KnownScalarMemory.anyext(BitWidth);
3961 else
3962 Known = KnownScalarMemory;
3963 assert(Known.getBitWidth() == BitWidth);
3964 return Known;
3965 }
3966 break;
3967 }
3969 if (Op.getValueType().isScalableVector())
3970 break;
3971 EVT InVT = Op.getOperand(0).getValueType();
3972 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3973 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3974 Known = Known.zext(BitWidth);
3975 break;
3976 }
3977 case ISD::ZERO_EXTEND: {
3978 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3979 Known = Known.zext(BitWidth);
3980 break;
3981 }
3983 if (Op.getValueType().isScalableVector())
3984 break;
3985 EVT InVT = Op.getOperand(0).getValueType();
3986 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3987 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3988 // If the sign bit is known to be zero or one, then sext will extend
3989 // it to the top bits, else it will just zext.
3990 Known = Known.sext(BitWidth);
3991 break;
3992 }
3993 case ISD::SIGN_EXTEND: {
3994 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3995 // If the sign bit is known to be zero or one, then sext will extend
3996 // it to the top bits, else it will just zext.
3997 Known = Known.sext(BitWidth);
3998 break;
3999 }
4001 if (Op.getValueType().isScalableVector())
4002 break;
4003 EVT InVT = Op.getOperand(0).getValueType();
4004 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4005 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4006 Known = Known.anyext(BitWidth);
4007 break;
4008 }
4009 case ISD::ANY_EXTEND: {
4010 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4011 Known = Known.anyext(BitWidth);
4012 break;
4013 }
4014 case ISD::TRUNCATE: {
4015 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4016 Known = Known.trunc(BitWidth);
4017 break;
4018 }
4019 case ISD::AssertZext: {
4020 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4022 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4023 Known.Zero |= (~InMask);
4024 Known.One &= (~Known.Zero);
4025 break;
4026 }
4027 case ISD::AssertAlign: {
4028 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4029 assert(LogOfAlign != 0);
4030
4031 // TODO: Should use maximum with source
4032 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4033 // well as clearing one bits.
4034 Known.Zero.setLowBits(LogOfAlign);
4035 Known.One.clearLowBits(LogOfAlign);
4036 break;
4037 }
4038 case ISD::AssertNoFPClass: {
4039 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4040
4041 FPClassTest NoFPClass =
4042 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4043 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4044 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4045 // Cannot be negative.
4046 Known.makeNonNegative();
4047 }
4048
4049 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4050 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4051 // Cannot be positive.
4052 Known.makeNegative();
4053 }
4054
4055 break;
4056 }
4057 case ISD::FGETSIGN:
4058 // All bits are zero except the low bit.
4059 Known.Zero.setBitsFrom(1);
4060 break;
4061 case ISD::ADD:
4062 case ISD::SUB: {
4063 SDNodeFlags Flags = Op.getNode()->getFlags();
4064 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4065 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4067 Op.getOpcode() == ISD::ADD, Flags.hasNoSignedWrap(),
4068 Flags.hasNoUnsignedWrap(), Known, Known2);
4069 break;
4070 }
4071 case ISD::USUBO:
4072 case ISD::SSUBO:
4073 case ISD::USUBO_CARRY:
4074 case ISD::SSUBO_CARRY:
4075 if (Op.getResNo() == 1) {
4076 // If we know the result of a setcc has the top bits zero, use this info.
4077 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4079 BitWidth > 1)
4080 Known.Zero.setBitsFrom(1);
4081 break;
4082 }
4083 [[fallthrough]];
4084 case ISD::SUBC: {
4085 assert(Op.getResNo() == 0 &&
4086 "We only compute knownbits for the difference here.");
4087
4088 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4089 KnownBits Borrow(1);
4090 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4091 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4092 // Borrow has bit width 1
4093 Borrow = Borrow.trunc(1);
4094 } else {
4095 Borrow.setAllZero();
4096 }
4097
4098 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4099 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4100 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4101 break;
4102 }
4103 case ISD::UADDO:
4104 case ISD::SADDO:
4105 case ISD::UADDO_CARRY:
4106 case ISD::SADDO_CARRY:
4107 if (Op.getResNo() == 1) {
4108 // If we know the result of a setcc has the top bits zero, use this info.
4109 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4111 BitWidth > 1)
4112 Known.Zero.setBitsFrom(1);
4113 break;
4114 }
4115 [[fallthrough]];
4116 case ISD::ADDC:
4117 case ISD::ADDE: {
4118 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4119
4120 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4121 KnownBits Carry(1);
4122 if (Opcode == ISD::ADDE)
4123 // Can't track carry from glue, set carry to unknown.
4124 Carry.resetAll();
4125 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4126 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4127 // Carry has bit width 1
4128 Carry = Carry.trunc(1);
4129 } else {
4130 Carry.setAllZero();
4131 }
4132
4133 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4134 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4135 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4136 break;
4137 }
4138 case ISD::UDIV: {
4139 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4140 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4141 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4142 break;
4143 }
4144 case ISD::SDIV: {
4145 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4146 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4147 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4148 break;
4149 }
4150 case ISD::SREM: {
4151 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4152 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4153 Known = KnownBits::srem(Known, Known2);
4154 break;
4155 }
4156 case ISD::UREM: {
4157 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4158 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4159 Known = KnownBits::urem(Known, Known2);
4160 break;
4161 }
4162 case ISD::EXTRACT_ELEMENT: {
4163 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4164 const unsigned Index = Op.getConstantOperandVal(1);
4165 const unsigned EltBitWidth = Op.getValueSizeInBits();
4166
4167 // Remove low part of known bits mask
4168 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4169 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4170
4171 // Remove high part of known bit mask
4172 Known = Known.trunc(EltBitWidth);
4173 break;
4174 }
4176 SDValue InVec = Op.getOperand(0);
4177 SDValue EltNo = Op.getOperand(1);
4178 EVT VecVT = InVec.getValueType();
4179 // computeKnownBits not yet implemented for scalable vectors.
4180 if (VecVT.isScalableVector())
4181 break;
4182 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4183 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4184
4185 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4186 // anything about the extended bits.
4187 if (BitWidth > EltBitWidth)
4188 Known = Known.trunc(EltBitWidth);
4189
4190 // If we know the element index, just demand that vector element, else for
4191 // an unknown element index, ignore DemandedElts and demand them all.
4192 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4193 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4194 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4195 DemandedSrcElts =
4196 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4197
4198 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4199 if (BitWidth > EltBitWidth)
4200 Known = Known.anyext(BitWidth);
4201 break;
4202 }
4204 if (Op.getValueType().isScalableVector())
4205 break;
4206
4207 // If we know the element index, split the demand between the
4208 // source vector and the inserted element, otherwise assume we need
4209 // the original demanded vector elements and the value.
4210 SDValue InVec = Op.getOperand(0);
4211 SDValue InVal = Op.getOperand(1);
4212 SDValue EltNo = Op.getOperand(2);
4213 bool DemandedVal = true;
4214 APInt DemandedVecElts = DemandedElts;
4215 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4216 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4217 unsigned EltIdx = CEltNo->getZExtValue();
4218 DemandedVal = !!DemandedElts[EltIdx];
4219 DemandedVecElts.clearBit(EltIdx);
4220 }
4221 Known.setAllConflict();
4222 if (DemandedVal) {
4223 Known2 = computeKnownBits(InVal, Depth + 1);
4224 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4225 }
4226 if (!!DemandedVecElts) {
4227 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4228 Known = Known.intersectWith(Known2);
4229 }
4230 break;
4231 }
4232 case ISD::BITREVERSE: {
4233 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4234 Known = Known2.reverseBits();
4235 break;
4236 }
4237 case ISD::BSWAP: {
4238 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4239 Known = Known2.byteSwap();
4240 break;
4241 }
4242 case ISD::ABS: {
4243 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4244 Known = Known2.abs();
4245 Known.Zero.setHighBits(
4246 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4247 break;
4248 }
4249 case ISD::USUBSAT: {
4250 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4251 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4252 Known = KnownBits::usub_sat(Known, Known2);
4253 break;
4254 }
4255 case ISD::UMIN: {
4256 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4257 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4258 Known = KnownBits::umin(Known, Known2);
4259 break;
4260 }
4261 case ISD::UMAX: {
4262 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4263 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4264 Known = KnownBits::umax(Known, Known2);
4265 break;
4266 }
4267 case ISD::SMIN:
4268 case ISD::SMAX: {
4269 // If we have a clamp pattern, we know that the number of sign bits will be
4270 // the minimum of the clamp min/max range.
4271 bool IsMax = (Opcode == ISD::SMAX);
4272 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4273 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4274 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4275 CstHigh =
4276 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4277 if (CstLow && CstHigh) {
4278 if (!IsMax)
4279 std::swap(CstLow, CstHigh);
4280
4281 const APInt &ValueLow = CstLow->getAPIntValue();
4282 const APInt &ValueHigh = CstHigh->getAPIntValue();
4283 if (ValueLow.sle(ValueHigh)) {
4284 unsigned LowSignBits = ValueLow.getNumSignBits();
4285 unsigned HighSignBits = ValueHigh.getNumSignBits();
4286 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4287 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4288 Known.One.setHighBits(MinSignBits);
4289 break;
4290 }
4291 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4292 Known.Zero.setHighBits(MinSignBits);
4293 break;
4294 }
4295 }
4296 }
4297
4298 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4299 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4300 if (IsMax)
4301 Known = KnownBits::smax(Known, Known2);
4302 else
4303 Known = KnownBits::smin(Known, Known2);
4304
4305 // For SMAX, if CstLow is non-negative we know the result will be
4306 // non-negative and thus all sign bits are 0.
4307 // TODO: There's an equivalent of this for smin with negative constant for
4308 // known ones.
4309 if (IsMax && CstLow) {
4310 const APInt &ValueLow = CstLow->getAPIntValue();
4311 if (ValueLow.isNonNegative()) {
4312 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4313 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4314 }
4315 }
4316
4317 break;
4318 }
4319 case ISD::UINT_TO_FP: {
4320 Known.makeNonNegative();
4321 break;
4322 }
4323 case ISD::SINT_TO_FP: {
4324 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4325 if (Known2.isNonNegative())
4326 Known.makeNonNegative();
4327 else if (Known2.isNegative())
4328 Known.makeNegative();
4329 break;
4330 }
4331 case ISD::FP_TO_UINT_SAT: {
4332 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4333 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4335 break;
4336 }
4337 case ISD::ATOMIC_LOAD: {
4338 // If we are looking at the loaded value.
4339 if (Op.getResNo() == 0) {
4340 auto *AT = cast<AtomicSDNode>(Op);
4341 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4342 KnownBits KnownScalarMemory(ScalarMemorySize);
4343 if (const MDNode *MD = AT->getRanges())
4344 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4345
4346 switch (AT->getExtensionType()) {
4347 case ISD::ZEXTLOAD:
4348 Known = KnownScalarMemory.zext(BitWidth);
4349 break;
4350 case ISD::SEXTLOAD:
4351 Known = KnownScalarMemory.sext(BitWidth);
4352 break;
4353 case ISD::EXTLOAD:
4354 switch (TLI->getExtendForAtomicOps()) {
4355 case ISD::ZERO_EXTEND:
4356 Known = KnownScalarMemory.zext(BitWidth);
4357 break;
4358 case ISD::SIGN_EXTEND:
4359 Known = KnownScalarMemory.sext(BitWidth);
4360 break;
4361 default:
4362 Known = KnownScalarMemory.anyext(BitWidth);
4363 break;
4364 }
4365 break;
4366 case ISD::NON_EXTLOAD:
4367 Known = KnownScalarMemory;
4368 break;
4369 }
4370 assert(Known.getBitWidth() == BitWidth);
4371 }
4372 break;
4373 }
4375 if (Op.getResNo() == 1) {
4376 // The boolean result conforms to getBooleanContents.
4377 // If we know the result of a setcc has the top bits zero, use this info.
4378 // We know that we have an integer-based boolean since these operations
4379 // are only available for integer.
4380 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4382 BitWidth > 1)
4383 Known.Zero.setBitsFrom(1);
4384 break;
4385 }
4386 [[fallthrough]];
4388 case ISD::ATOMIC_SWAP:
4399 case ISD::ATOMIC_LOAD_UMAX: {
4400 // If we are looking at the loaded value.
4401 if (Op.getResNo() == 0) {
4402 auto *AT = cast<AtomicSDNode>(Op);
4403 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4404
4405 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4406 Known.Zero.setBitsFrom(MemBits);
4407 }
4408 break;
4409 }
4410 case ISD::FrameIndex:
4412 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
4413 Known, getMachineFunction());
4414 break;
4415
4416 default:
4417 if (Opcode < ISD::BUILTIN_OP_END)
4418 break;
4419 [[fallthrough]];
4423 // TODO: Probably okay to remove after audit; here to reduce change size
4424 // in initial enablement patch for scalable vectors
4425 if (Op.getValueType().isScalableVector())
4426 break;
4427
4428 // Allow the target to implement this method for its nodes.
4429 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4430 break;
4431 }
4432
4433 return Known;
4434}
4435
4436/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4449
4452 // X + 0 never overflow
4453 if (isNullConstant(N1))
4454 return OFK_Never;
4455
4456 // If both operands each have at least two sign bits, the addition
4457 // cannot overflow.
4458 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4459 return OFK_Never;
4460
4461 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4462 return OFK_Sometime;
4463}
4464
4467 // X + 0 never overflow
4468 if (isNullConstant(N1))
4469 return OFK_Never;
4470
4471 // mulhi + 1 never overflow
4472 KnownBits N1Known = computeKnownBits(N1);
4473 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4474 N1Known.getMaxValue().ult(2))
4475 return OFK_Never;
4476
4477 KnownBits N0Known = computeKnownBits(N0);
4478 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4479 N0Known.getMaxValue().ult(2))
4480 return OFK_Never;
4481
4482 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4483 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4484 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4485 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4486}
4487
4490 // X - 0 never overflow
4491 if (isNullConstant(N1))
4492 return OFK_Never;
4493
4494 // If both operands each have at least two sign bits, the subtraction
4495 // cannot overflow.
4496 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4497 return OFK_Never;
4498
4499 KnownBits N0Known = computeKnownBits(N0);
4500 KnownBits N1Known = computeKnownBits(N1);
4501 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4502 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4503 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4504}
4505
4508 // X - 0 never overflow
4509 if (isNullConstant(N1))
4510 return OFK_Never;
4511
4512 KnownBits N0Known = computeKnownBits(N0);
4513 KnownBits N1Known = computeKnownBits(N1);
4514 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4515 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4516 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4517}
4518
4521 // X * 0 and X * 1 never overflow.
4522 if (isNullConstant(N1) || isOneConstant(N1))
4523 return OFK_Never;
4524
4525 KnownBits N0Known = computeKnownBits(N0);
4526 KnownBits N1Known = computeKnownBits(N1);
4527 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4528 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4529 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4530}
4531
4534 // X * 0 and X * 1 never overflow.
4535 if (isNullConstant(N1) || isOneConstant(N1))
4536 return OFK_Never;
4537
4538 // Get the size of the result.
4539 unsigned BitWidth = N0.getScalarValueSizeInBits();
4540
4541 // Sum of the sign bits.
4542 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4543
4544 // If we have enough sign bits, then there's no overflow.
4545 if (SignBits > BitWidth + 1)
4546 return OFK_Never;
4547
4548 if (SignBits == BitWidth + 1) {
4549 // The overflow occurs when the true multiplication of the
4550 // the operands is the minimum negative number.
4551 KnownBits N0Known = computeKnownBits(N0);
4552 KnownBits N1Known = computeKnownBits(N1);
4553 // If one of the operands is non-negative, then there's no
4554 // overflow.
4555 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4556 return OFK_Never;
4557 }
4558
4559 return OFK_Sometime;
4560}
4561
4563 if (Depth >= MaxRecursionDepth)
4564 return false; // Limit search depth.
4565
4566 EVT OpVT = Val.getValueType();
4567 unsigned BitWidth = OpVT.getScalarSizeInBits();
4568
4569 // Is the constant a known power of 2?
4571 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
4572 }))
4573 return true;
4574
4575 // A left-shift of a constant one will have exactly one bit set because
4576 // shifting the bit off the end is undefined.
4577 if (Val.getOpcode() == ISD::SHL) {
4578 auto *C = isConstOrConstSplat(Val.getOperand(0));
4579 if (C && C->getAPIntValue() == 1)
4580 return true;
4581 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1) &&
4582 isKnownNeverZero(Val, Depth);
4583 }
4584
4585 // Similarly, a logical right-shift of a constant sign-bit will have exactly
4586 // one bit set.
4587 if (Val.getOpcode() == ISD::SRL) {
4588 auto *C = isConstOrConstSplat(Val.getOperand(0));
4589 if (C && C->getAPIntValue().isSignMask())
4590 return true;
4591 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1) &&
4592 isKnownNeverZero(Val, Depth);
4593 }
4594
4595 if (Val.getOpcode() == ISD::ROTL || Val.getOpcode() == ISD::ROTR)
4596 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4597
4598 // Are all operands of a build vector constant powers of two?
4599 if (Val.getOpcode() == ISD::BUILD_VECTOR)
4600 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
4601 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
4602 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
4603 return false;
4604 }))
4605 return true;
4606
4607 // Is the operand of a splat vector a constant power of two?
4608 if (Val.getOpcode() == ISD::SPLAT_VECTOR)
4610 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
4611 return true;
4612
4613 // vscale(power-of-two) is a power-of-two for some targets
4614 if (Val.getOpcode() == ISD::VSCALE &&
4615 getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
4617 return true;
4618
4619 if (Val.getOpcode() == ISD::SMIN || Val.getOpcode() == ISD::SMAX ||
4620 Val.getOpcode() == ISD::UMIN || Val.getOpcode() == ISD::UMAX)
4621 return isKnownToBeAPowerOfTwo(Val.getOperand(1), Depth + 1) &&
4623
4624 if (Val.getOpcode() == ISD::SELECT || Val.getOpcode() == ISD::VSELECT)
4625 return isKnownToBeAPowerOfTwo(Val.getOperand(2), Depth + 1) &&
4627
4628 // Looking for `x & -x` pattern:
4629 // If x == 0:
4630 // x & -x -> 0
4631 // If x != 0:
4632 // x & -x -> non-zero pow2
4633 // so if we find the pattern return whether we know `x` is non-zero.
4634 SDValue X;
4635 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))))
4636 return isKnownNeverZero(X, Depth);
4637
4638 if (Val.getOpcode() == ISD::ZERO_EXTEND)
4639 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4640
4641 // More could be done here, though the above checks are enough
4642 // to handle some common cases.
4643 return false;
4644}
4645
4647 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4648 return C1->getValueAPF().getExactLog2Abs() >= 0;
4649
4650 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4651 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4652
4653 return false;
4654}
4655
4657 EVT VT = Op.getValueType();
4658
4659 // Since the number of lanes in a scalable vector is unknown at compile time,
4660 // we track one bit which is implicitly broadcast to all lanes. This means
4661 // that all lanes in a scalable vector are considered demanded.
4662 APInt DemandedElts = VT.isFixedLengthVector()
4664 : APInt(1, 1);
4665 return ComputeNumSignBits(Op, DemandedElts, Depth);
4666}
4667
4668unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4669 unsigned Depth) const {
4670 EVT VT = Op.getValueType();
4671 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4672 unsigned VTBits = VT.getScalarSizeInBits();
4673 unsigned NumElts = DemandedElts.getBitWidth();
4674 unsigned Tmp, Tmp2;
4675 unsigned FirstAnswer = 1;
4676
4677 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4678 const APInt &Val = C->getAPIntValue();
4679 return Val.getNumSignBits();
4680 }
4681
4682 if (Depth >= MaxRecursionDepth)
4683 return 1; // Limit search depth.
4684
4685 if (!DemandedElts)
4686 return 1; // No demanded elts, better to assume we don't know anything.
4687
4688 unsigned Opcode = Op.getOpcode();
4689 switch (Opcode) {
4690 default: break;
4691 case ISD::AssertSext:
4692 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4693 return VTBits-Tmp+1;
4694 case ISD::AssertZext:
4695 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4696 return VTBits-Tmp;
4697 case ISD::FREEZE:
4698 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4699 /*PoisonOnly=*/false))
4700 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4701 break;
4702 case ISD::MERGE_VALUES:
4703 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4704 Depth + 1);
4705 case ISD::SPLAT_VECTOR: {
4706 // Check if the sign bits of source go down as far as the truncated value.
4707 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4708 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4709 if (NumSrcSignBits > (NumSrcBits - VTBits))
4710 return NumSrcSignBits - (NumSrcBits - VTBits);
4711 break;
4712 }
4713 case ISD::BUILD_VECTOR:
4714 assert(!VT.isScalableVector());
4715 Tmp = VTBits;
4716 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4717 if (!DemandedElts[i])
4718 continue;
4719
4720 SDValue SrcOp = Op.getOperand(i);
4721 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4722 // for constant nodes to ensure we only look at the sign bits.
4724 APInt T = C->getAPIntValue().trunc(VTBits);
4725 Tmp2 = T.getNumSignBits();
4726 } else {
4727 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4728
4729 if (SrcOp.getValueSizeInBits() != VTBits) {
4730 assert(SrcOp.getValueSizeInBits() > VTBits &&
4731 "Expected BUILD_VECTOR implicit truncation");
4732 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4733 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4734 }
4735 }
4736 Tmp = std::min(Tmp, Tmp2);
4737 }
4738 return Tmp;
4739
4740 case ISD::VECTOR_COMPRESS: {
4741 SDValue Vec = Op.getOperand(0);
4742 SDValue PassThru = Op.getOperand(2);
4743 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
4744 if (Tmp == 1)
4745 return 1;
4746 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
4747 Tmp = std::min(Tmp, Tmp2);
4748 return Tmp;
4749 }
4750
4751 case ISD::VECTOR_SHUFFLE: {
4752 // Collect the minimum number of sign bits that are shared by every vector
4753 // element referenced by the shuffle.
4754 APInt DemandedLHS, DemandedRHS;
4756 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4757 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4758 DemandedLHS, DemandedRHS))
4759 return 1;
4760
4761 Tmp = std::numeric_limits<unsigned>::max();
4762 if (!!DemandedLHS)
4763 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
4764 if (!!DemandedRHS) {
4765 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
4766 Tmp = std::min(Tmp, Tmp2);
4767 }
4768 // If we don't know anything, early out and try computeKnownBits fall-back.
4769 if (Tmp == 1)
4770 break;
4771 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4772 return Tmp;
4773 }
4774
4775 case ISD::BITCAST: {
4776 if (VT.isScalableVector())
4777 break;
4778 SDValue N0 = Op.getOperand(0);
4779 EVT SrcVT = N0.getValueType();
4780 unsigned SrcBits = SrcVT.getScalarSizeInBits();
4781
4782 // Ignore bitcasts from unsupported types..
4783 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
4784 break;
4785
4786 // Fast handling of 'identity' bitcasts.
4787 if (VTBits == SrcBits)
4788 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
4789
4790 bool IsLE = getDataLayout().isLittleEndian();
4791
4792 // Bitcast 'large element' scalar/vector to 'small element' vector.
4793 if ((SrcBits % VTBits) == 0) {
4794 assert(VT.isVector() && "Expected bitcast to vector");
4795
4796 unsigned Scale = SrcBits / VTBits;
4797 APInt SrcDemandedElts =
4798 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
4799
4800 // Fast case - sign splat can be simply split across the small elements.
4801 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
4802 if (Tmp == SrcBits)
4803 return VTBits;
4804
4805 // Slow case - determine how far the sign extends into each sub-element.
4806 Tmp2 = VTBits;
4807 for (unsigned i = 0; i != NumElts; ++i)
4808 if (DemandedElts[i]) {
4809 unsigned SubOffset = i % Scale;
4810 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4811 SubOffset = SubOffset * VTBits;
4812 if (Tmp <= SubOffset)
4813 return 1;
4814 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4815 }
4816 return Tmp2;
4817 }
4818 break;
4819 }
4820
4822 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4823 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4824 return VTBits - Tmp + 1;
4825 case ISD::SIGN_EXTEND:
4826 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4827 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4829 // Max of the input and what this extends.
4830 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4831 Tmp = VTBits-Tmp+1;
4832 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4833 return std::max(Tmp, Tmp2);
4835 if (VT.isScalableVector())
4836 break;
4837 SDValue Src = Op.getOperand(0);
4838 EVT SrcVT = Src.getValueType();
4839 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4840 Tmp = VTBits - SrcVT.getScalarSizeInBits();
4841 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4842 }
4843 case ISD::SRA:
4844 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4845 // SRA X, C -> adds C sign bits.
4846 if (std::optional<unsigned> ShAmt =
4847 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
4848 Tmp = std::min(Tmp + *ShAmt, VTBits);
4849 return Tmp;
4850 case ISD::SHL:
4851 if (std::optional<ConstantRange> ShAmtRange =
4852 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
4853 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
4854 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
4855 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
4856 // shifted out, then we can compute the number of sign bits for the
4857 // operand being extended. A future improvement could be to pass along the
4858 // "shifted left by" information in the recursive calls to
4859 // ComputeKnownSignBits. Allowing us to handle this more generically.
4860 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
4861 SDValue Ext = Op.getOperand(0);
4862 EVT ExtVT = Ext.getValueType();
4863 SDValue Extendee = Ext.getOperand(0);
4864 EVT ExtendeeVT = Extendee.getValueType();
4865 unsigned SizeDifference =
4866 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
4867 if (SizeDifference <= MinShAmt) {
4868 Tmp = SizeDifference +
4869 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
4870 if (MaxShAmt < Tmp)
4871 return Tmp - MaxShAmt;
4872 }
4873 }
4874 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4875 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4876 if (MaxShAmt < Tmp)
4877 return Tmp - MaxShAmt;
4878 }
4879 break;
4880 case ISD::AND:
4881 case ISD::OR:
4882 case ISD::XOR: // NOT is handled here.
4883 // Logical binary ops preserve the number of sign bits at the worst.
4884 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4885 if (Tmp != 1) {
4886 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4887 FirstAnswer = std::min(Tmp, Tmp2);
4888 // We computed what we know about the sign bits as our first
4889 // answer. Now proceed to the generic code that uses
4890 // computeKnownBits, and pick whichever answer is better.
4891 }
4892 break;
4893
4894 case ISD::SELECT:
4895 case ISD::VSELECT:
4896 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4897 if (Tmp == 1) return 1; // Early out.
4898 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4899 return std::min(Tmp, Tmp2);
4900 case ISD::SELECT_CC:
4901 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4902 if (Tmp == 1) return 1; // Early out.
4903 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4904 return std::min(Tmp, Tmp2);
4905
4906 case ISD::SMIN:
4907 case ISD::SMAX: {
4908 // If we have a clamp pattern, we know that the number of sign bits will be
4909 // the minimum of the clamp min/max range.
4910 bool IsMax = (Opcode == ISD::SMAX);
4911 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4912 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4913 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4914 CstHigh =
4915 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4916 if (CstLow && CstHigh) {
4917 if (!IsMax)
4918 std::swap(CstLow, CstHigh);
4919 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4920 Tmp = CstLow->getAPIntValue().getNumSignBits();
4921 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4922 return std::min(Tmp, Tmp2);
4923 }
4924 }
4925
4926 // Fallback - just get the minimum number of sign bits of the operands.
4927 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4928 if (Tmp == 1)
4929 return 1; // Early out.
4930 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4931 return std::min(Tmp, Tmp2);
4932 }
4933 case ISD::UMIN:
4934 case ISD::UMAX:
4935 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4936 if (Tmp == 1)
4937 return 1; // Early out.
4938 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4939 return std::min(Tmp, Tmp2);
4940 case ISD::SSUBO_CARRY:
4941 case ISD::USUBO_CARRY:
4942 // sub_carry(x,x,c) -> 0/-1 (sext carry)
4943 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
4944 return VTBits;
4945 [[fallthrough]];
4946 case ISD::SADDO:
4947 case ISD::UADDO:
4948 case ISD::SADDO_CARRY:
4949 case ISD::UADDO_CARRY:
4950 case ISD::SSUBO:
4951 case ISD::USUBO:
4952 case ISD::SMULO:
4953 case ISD::UMULO:
4954 if (Op.getResNo() != 1)
4955 break;
4956 // The boolean result conforms to getBooleanContents. Fall through.
4957 // If setcc returns 0/-1, all bits are sign bits.
4958 // We know that we have an integer-based boolean since these operations
4959 // are only available for integer.
4960 if (TLI->getBooleanContents(VT.isVector(), false) ==
4962 return VTBits;
4963 break;
4964 case ISD::SETCC:
4965 case ISD::SETCCCARRY:
4966 case ISD::STRICT_FSETCC:
4967 case ISD::STRICT_FSETCCS: {
4968 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4969 // If setcc returns 0/-1, all bits are sign bits.
4970 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4972 return VTBits;
4973 break;
4974 }
4975 case ISD::ROTL:
4976 case ISD::ROTR:
4977 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4978
4979 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4980 if (Tmp == VTBits)
4981 return VTBits;
4982
4983 if (ConstantSDNode *C =
4984 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4985 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4986
4987 // Handle rotate right by N like a rotate left by 32-N.
4988 if (Opcode == ISD::ROTR)
4989 RotAmt = (VTBits - RotAmt) % VTBits;
4990
4991 // If we aren't rotating out all of the known-in sign bits, return the
4992 // number that are left. This handles rotl(sext(x), 1) for example.
4993 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4994 }
4995 break;
4996 case ISD::ADD:
4997 case ISD::ADDC:
4998 // TODO: Move Operand 1 check before Operand 0 check
4999 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5000 if (Tmp == 1) return 1; // Early out.
5001
5002 // Special case decrementing a value (ADD X, -1):
5003 if (ConstantSDNode *CRHS =
5004 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5005 if (CRHS->isAllOnes()) {
5006 KnownBits Known =
5007 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5008
5009 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5010 // sign bits set.
5011 if ((Known.Zero | 1).isAllOnes())
5012 return VTBits;
5013
5014 // If we are subtracting one from a positive number, there is no carry
5015 // out of the result.
5016 if (Known.isNonNegative())
5017 return Tmp;
5018 }
5019
5020 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5021 if (Tmp2 == 1) return 1; // Early out.
5022
5023 // Add can have at most one carry bit. Thus we know that the output
5024 // is, at worst, one more bit than the inputs.
5025 return std::min(Tmp, Tmp2) - 1;
5026 case ISD::SUB:
5027 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5028 if (Tmp2 == 1) return 1; // Early out.
5029
5030 // Handle NEG.
5031 if (ConstantSDNode *CLHS =
5032 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5033 if (CLHS->isZero()) {
5034 KnownBits Known =
5035 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5036 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5037 // sign bits set.
5038 if ((Known.Zero | 1).isAllOnes())
5039 return VTBits;
5040
5041 // If the input is known to be positive (the sign bit is known clear),
5042 // the output of the NEG has the same number of sign bits as the input.
5043 if (Known.isNonNegative())
5044 return Tmp2;
5045
5046 // Otherwise, we treat this like a SUB.
5047 }
5048
5049 // Sub can have at most one carry bit. Thus we know that the output
5050 // is, at worst, one more bit than the inputs.
5051 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5052 if (Tmp == 1) return 1; // Early out.
5053 return std::min(Tmp, Tmp2) - 1;
5054 case ISD::MUL: {
5055 // The output of the Mul can be at most twice the valid bits in the inputs.
5056 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5057 if (SignBitsOp0 == 1)
5058 break;
5059 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5060 if (SignBitsOp1 == 1)
5061 break;
5062 unsigned OutValidBits =
5063 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5064 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5065 }
5066 case ISD::AVGCEILS:
5067 case ISD::AVGFLOORS:
5068 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5069 if (Tmp == 1)
5070 return 1; // Early out.
5071 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5072 return std::min(Tmp, Tmp2);
5073 case ISD::SREM:
5074 // The sign bit is the LHS's sign bit, except when the result of the
5075 // remainder is zero. The magnitude of the result should be less than or
5076 // equal to the magnitude of the LHS. Therefore, the result should have
5077 // at least as many sign bits as the left hand side.
5078 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5079 case ISD::TRUNCATE: {
5080 // Check if the sign bits of source go down as far as the truncated value.
5081 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5082 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5083 if (NumSrcSignBits > (NumSrcBits - VTBits))
5084 return NumSrcSignBits - (NumSrcBits - VTBits);
5085 break;
5086 }
5087 case ISD::EXTRACT_ELEMENT: {
5088 if (VT.isScalableVector())
5089 break;
5090 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5091 const int BitWidth = Op.getValueSizeInBits();
5092 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5093
5094 // Get reverse index (starting from 1), Op1 value indexes elements from
5095 // little end. Sign starts at big end.
5096 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5097
5098 // If the sign portion ends in our element the subtraction gives correct
5099 // result. Otherwise it gives either negative or > bitwidth result
5100 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5101 }
5103 if (VT.isScalableVector())
5104 break;
5105 // If we know the element index, split the demand between the
5106 // source vector and the inserted element, otherwise assume we need
5107 // the original demanded vector elements and the value.
5108 SDValue InVec = Op.getOperand(0);
5109 SDValue InVal = Op.getOperand(1);
5110 SDValue EltNo = Op.getOperand(2);
5111 bool DemandedVal = true;
5112 APInt DemandedVecElts = DemandedElts;
5113 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5114 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5115 unsigned EltIdx = CEltNo->getZExtValue();
5116 DemandedVal = !!DemandedElts[EltIdx];
5117 DemandedVecElts.clearBit(EltIdx);
5118 }
5119 Tmp = std::numeric_limits<unsigned>::max();
5120 if (DemandedVal) {
5121 // TODO - handle implicit truncation of inserted elements.
5122 if (InVal.getScalarValueSizeInBits() != VTBits)
5123 break;
5124 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5125 Tmp = std::min(Tmp, Tmp2);
5126 }
5127 if (!!DemandedVecElts) {
5128 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5129 Tmp = std::min(Tmp, Tmp2);
5130 }
5131 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5132 return Tmp;
5133 }
5135 assert(!VT.isScalableVector());
5136 SDValue InVec = Op.getOperand(0);
5137 SDValue EltNo = Op.getOperand(1);
5138 EVT VecVT = InVec.getValueType();
5139 // ComputeNumSignBits not yet implemented for scalable vectors.
5140 if (VecVT.isScalableVector())
5141 break;
5142 const unsigned BitWidth = Op.getValueSizeInBits();
5143 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5144 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5145
5146 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5147 // anything about sign bits. But if the sizes match we can derive knowledge
5148 // about sign bits from the vector operand.
5149 if (BitWidth != EltBitWidth)
5150 break;
5151
5152 // If we know the element index, just demand that vector element, else for
5153 // an unknown element index, ignore DemandedElts and demand them all.
5154 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5155 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5156 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5157 DemandedSrcElts =
5158 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5159
5160 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5161 }
5163 // Offset the demanded elts by the subvector index.
5164 SDValue Src = Op.getOperand(0);
5165 // Bail until we can represent demanded elements for scalable vectors.
5166 if (Src.getValueType().isScalableVector())
5167 break;
5168 uint64_t Idx = Op.getConstantOperandVal(1);
5169 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5170 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5171 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5172 }
5173 case ISD::CONCAT_VECTORS: {
5174 if (VT.isScalableVector())
5175 break;
5176 // Determine the minimum number of sign bits across all demanded
5177 // elts of the input vectors. Early out if the result is already 1.
5178 Tmp = std::numeric_limits<unsigned>::max();
5179 EVT SubVectorVT = Op.getOperand(0).getValueType();
5180 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5181 unsigned NumSubVectors = Op.getNumOperands();
5182 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5183 APInt DemandedSub =
5184 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5185 if (!DemandedSub)
5186 continue;
5187 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5188 Tmp = std::min(Tmp, Tmp2);
5189 }
5190 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5191 return Tmp;
5192 }
5193 case ISD::INSERT_SUBVECTOR: {
5194 if (VT.isScalableVector())
5195 break;
5196 // Demand any elements from the subvector and the remainder from the src its
5197 // inserted into.
5198 SDValue Src = Op.getOperand(0);
5199 SDValue Sub = Op.getOperand(1);
5200 uint64_t Idx = Op.getConstantOperandVal(2);
5201 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5202 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5203 APInt DemandedSrcElts = DemandedElts;
5204 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5205
5206 Tmp = std::numeric_limits<unsigned>::max();
5207 if (!!DemandedSubElts) {
5208 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5209 if (Tmp == 1)
5210 return 1; // early-out
5211 }
5212 if (!!DemandedSrcElts) {
5213 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5214 Tmp = std::min(Tmp, Tmp2);
5215 }
5216 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5217 return Tmp;
5218 }
5219 case ISD::LOAD: {
5221 if (const MDNode *Ranges = LD->getRanges()) {
5222 if (DemandedElts != 1)
5223 break;
5224
5226 if (VTBits > CR.getBitWidth()) {
5227 switch (LD->getExtensionType()) {
5228 case ISD::SEXTLOAD:
5229 CR = CR.signExtend(VTBits);
5230 break;
5231 case ISD::ZEXTLOAD:
5232 CR = CR.zeroExtend(VTBits);
5233 break;
5234 default:
5235 break;
5236 }
5237 }
5238
5239 if (VTBits != CR.getBitWidth())
5240 break;
5241 return std::min(CR.getSignedMin().getNumSignBits(),
5243 }
5244
5245 break;
5246 }
5249 case ISD::ATOMIC_SWAP:
5261 case ISD::ATOMIC_LOAD: {
5262 auto *AT = cast<AtomicSDNode>(Op);
5263 // If we are looking at the loaded value.
5264 if (Op.getResNo() == 0) {
5265 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5266 if (Tmp == VTBits)
5267 return 1; // early-out
5268
5269 // For atomic_load, prefer to use the extension type.
5270 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5271 switch (AT->getExtensionType()) {
5272 default:
5273 break;
5274 case ISD::SEXTLOAD:
5275 return VTBits - Tmp + 1;
5276 case ISD::ZEXTLOAD:
5277 return VTBits - Tmp;
5278 }
5279 }
5280
5281 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5282 return VTBits - Tmp + 1;
5283 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5284 return VTBits - Tmp;
5285 }
5286 break;
5287 }
5288 }
5289
5290 // If we are looking at the loaded value of the SDNode.
5291 if (Op.getResNo() == 0) {
5292 // Handle LOADX separately here. EXTLOAD case will fallthrough.
5293 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
5294 unsigned ExtType = LD->getExtensionType();
5295 switch (ExtType) {
5296 default: break;
5297 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5298 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5299 return VTBits - Tmp + 1;
5300 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5301 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5302 return VTBits - Tmp;
5303 case ISD::NON_EXTLOAD:
5304 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5305 // We only need to handle vectors - computeKnownBits should handle
5306 // scalar cases.
5307 Type *CstTy = Cst->getType();
5308 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5309 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5310 VTBits == CstTy->getScalarSizeInBits()) {
5311 Tmp = VTBits;
5312 for (unsigned i = 0; i != NumElts; ++i) {
5313 if (!DemandedElts[i])
5314 continue;
5315 if (Constant *Elt = Cst->getAggregateElement(i)) {
5316 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5317 const APInt &Value = CInt->getValue();
5318 Tmp = std::min(Tmp, Value.getNumSignBits());
5319 continue;
5320 }
5321 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5322 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5323 Tmp = std::min(Tmp, Value.getNumSignBits());
5324 continue;
5325 }
5326 }
5327 // Unknown type. Conservatively assume no bits match sign bit.
5328 return 1;
5329 }
5330 return Tmp;
5331 }
5332 }
5333 break;
5334 }
5335 }
5336 }
5337
5338 // Allow the target to implement this method for its nodes.
5339 if (Opcode >= ISD::BUILTIN_OP_END ||
5340 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5341 Opcode == ISD::INTRINSIC_W_CHAIN ||
5342 Opcode == ISD::INTRINSIC_VOID) {
5343 // TODO: This can probably be removed once target code is audited. This
5344 // is here purely to reduce patch size and review complexity.
5345 if (!VT.isScalableVector()) {
5346 unsigned NumBits =
5347 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5348 if (NumBits > 1)
5349 FirstAnswer = std::max(FirstAnswer, NumBits);
5350 }
5351 }
5352
5353 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5354 // use this information.
5355 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5356 return std::max(FirstAnswer, Known.countMinSignBits());
5357}
5358
5360 unsigned Depth) const {
5361 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5362 return Op.getScalarValueSizeInBits() - SignBits + 1;
5363}
5364
5366 const APInt &DemandedElts,
5367 unsigned Depth) const {
5368 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5369 return Op.getScalarValueSizeInBits() - SignBits + 1;
5370}
5371
5373 unsigned Depth) const {
5374 // Early out for FREEZE.
5375 if (Op.getOpcode() == ISD::FREEZE)
5376 return true;
5377
5378 EVT VT = Op.getValueType();
5379 APInt DemandedElts = VT.isFixedLengthVector()
5381 : APInt(1, 1);
5382 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
5383}
5384
5386 const APInt &DemandedElts,
5387 bool PoisonOnly,
5388 unsigned Depth) const {
5389 unsigned Opcode = Op.getOpcode();
5390
5391 // Early out for FREEZE.
5392 if (Opcode == ISD::FREEZE)
5393 return true;
5394
5395 if (Depth >= MaxRecursionDepth)
5396 return false; // Limit search depth.
5397
5398 if (isIntOrFPConstant(Op))
5399 return true;
5400
5401 switch (Opcode) {
5402 case ISD::CONDCODE:
5403 case ISD::VALUETYPE:
5404 case ISD::FrameIndex:
5406 case ISD::CopyFromReg:
5407 return true;
5408
5409 case ISD::POISON:
5410 return false;
5411
5412 case ISD::UNDEF:
5413 return PoisonOnly;
5414
5415 case ISD::BUILD_VECTOR:
5416 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5417 // this shouldn't affect the result.
5418 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5419 if (!DemandedElts[i])
5420 continue;
5422 Depth + 1))
5423 return false;
5424 }
5425 return true;
5426
5428 SDValue Src = Op.getOperand(0);
5429 if (Src.getValueType().isScalableVector())
5430 break;
5431 uint64_t Idx = Op.getConstantOperandVal(1);
5432 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5433 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5434 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, PoisonOnly,
5435 Depth + 1);
5436 }
5437
5438 case ISD::INSERT_SUBVECTOR: {
5439 if (Op.getValueType().isScalableVector())
5440 break;
5441 SDValue Src = Op.getOperand(0);
5442 SDValue Sub = Op.getOperand(1);
5443 uint64_t Idx = Op.getConstantOperandVal(2);
5444 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5445 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5446 APInt DemandedSrcElts = DemandedElts;
5447 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5448
5449 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5450 Sub, DemandedSubElts, PoisonOnly, Depth + 1))
5451 return false;
5452 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5453 Src, DemandedSrcElts, PoisonOnly, Depth + 1))
5454 return false;
5455 return true;
5456 }
5457
5459 SDValue Src = Op.getOperand(0);
5460 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5461 EVT SrcVT = Src.getValueType();
5462 if (SrcVT.isFixedLengthVector() && IndexC &&
5463 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5464 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5465 IndexC->getZExtValue());
5466 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, PoisonOnly,
5467 Depth + 1);
5468 }
5469 break;
5470 }
5471
5473 SDValue InVec = Op.getOperand(0);
5474 SDValue InVal = Op.getOperand(1);
5475 SDValue EltNo = Op.getOperand(2);
5476 EVT VT = InVec.getValueType();
5477 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5478 if (IndexC && VT.isFixedLengthVector() &&
5479 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5480 if (DemandedElts[IndexC->getZExtValue()] &&
5482 return false;
5483 APInt InVecDemandedElts = DemandedElts;
5484 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5485 if (!!InVecDemandedElts &&
5487 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5488 InVecDemandedElts, PoisonOnly, Depth + 1))
5489 return false;
5490 return true;
5491 }
5492 break;
5493 }
5494
5496 // Check upper (known undef) elements.
5497 if (DemandedElts.ugt(1) && !PoisonOnly)
5498 return false;
5499 // Check element zero.
5500 if (DemandedElts[0] && !isGuaranteedNotToBeUndefOrPoison(
5501 Op.getOperand(0), PoisonOnly, Depth + 1))
5502 return false;
5503 return true;
5504
5505 case ISD::SPLAT_VECTOR:
5506 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), PoisonOnly,
5507 Depth + 1);
5508
5509 case ISD::VECTOR_SHUFFLE: {
5510 APInt DemandedLHS, DemandedRHS;
5511 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5512 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5513 DemandedElts, DemandedLHS, DemandedRHS,
5514 /*AllowUndefElts=*/false))
5515 return false;
5516 if (!DemandedLHS.isZero() &&
5517 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS,
5518 PoisonOnly, Depth + 1))
5519 return false;
5520 if (!DemandedRHS.isZero() &&
5521 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS,
5522 PoisonOnly, Depth + 1))
5523 return false;
5524 return true;
5525 }
5526
5527 case ISD::SHL:
5528 case ISD::SRL:
5529 case ISD::SRA:
5530 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5531 // enough to check operand 0 if Op can't create undef/poison.
5532 return !canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly,
5533 /*ConsiderFlags*/ true, Depth) &&
5534 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5535 PoisonOnly, Depth + 1);
5536
5537 case ISD::BSWAP:
5538 case ISD::CTPOP:
5539 case ISD::BITREVERSE:
5540 case ISD::AND:
5541 case ISD::OR:
5542 case ISD::XOR:
5543 case ISD::ADD:
5544 case ISD::SUB:
5545 case ISD::MUL:
5546 case ISD::SADDSAT:
5547 case ISD::UADDSAT:
5548 case ISD::SSUBSAT:
5549 case ISD::USUBSAT:
5550 case ISD::SSHLSAT:
5551 case ISD::USHLSAT:
5552 case ISD::SMIN:
5553 case ISD::SMAX:
5554 case ISD::UMIN:
5555 case ISD::UMAX:
5556 case ISD::ZERO_EXTEND:
5557 case ISD::SIGN_EXTEND:
5558 case ISD::ANY_EXTEND:
5559 case ISD::TRUNCATE:
5560 case ISD::VSELECT: {
5561 // If Op can't create undef/poison and none of its operands are undef/poison
5562 // then Op is never undef/poison. A difference from the more common check
5563 // below, outside the switch, is that we handle elementwise operations for
5564 // which the DemandedElts mask is valid for all operands here.
5565 return !canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly,
5566 /*ConsiderFlags*/ true, Depth) &&
5567 all_of(Op->ops(), [&](SDValue V) {
5568 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts,
5569 PoisonOnly, Depth + 1);
5570 });
5571 }
5572
5573 // TODO: Search for noundef attributes from library functions.
5574
5575 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5576
5577 default:
5578 // Allow the target to implement this method for its nodes.
5579 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5580 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5581 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5582 Op, DemandedElts, *this, PoisonOnly, Depth);
5583 break;
5584 }
5585
5586 // If Op can't create undef/poison and none of its operands are undef/poison
5587 // then Op is never undef/poison.
5588 // NOTE: TargetNodes can handle this in themselves in
5589 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5590 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5591 return !canCreateUndefOrPoison(Op, PoisonOnly, /*ConsiderFlags*/ true,
5592 Depth) &&
5593 all_of(Op->ops(), [&](SDValue V) {
5594 return isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, Depth + 1);
5595 });
5596}
5597
5599 bool ConsiderFlags,
5600 unsigned Depth) const {
5601 EVT VT = Op.getValueType();
5602 APInt DemandedElts = VT.isFixedLengthVector()
5604 : APInt(1, 1);
5605 return canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly, ConsiderFlags,
5606 Depth);
5607}
5608
5610 bool PoisonOnly, bool ConsiderFlags,
5611 unsigned Depth) const {
5612 if (ConsiderFlags && Op->hasPoisonGeneratingFlags())
5613 return true;
5614
5615 unsigned Opcode = Op.getOpcode();
5616 switch (Opcode) {
5617 case ISD::AssertSext:
5618 case ISD::AssertZext:
5619 case ISD::AssertAlign:
5621 // Assertion nodes can create poison if the assertion fails.
5622 return true;
5623
5624 case ISD::FREEZE:
5628 case ISD::SADDSAT:
5629 case ISD::UADDSAT:
5630 case ISD::SSUBSAT:
5631 case ISD::USUBSAT:
5632 case ISD::MULHU:
5633 case ISD::MULHS:
5634 case ISD::AVGFLOORS:
5635 case ISD::AVGFLOORU:
5636 case ISD::AVGCEILS:
5637 case ISD::AVGCEILU:
5638 case ISD::ABDU:
5639 case ISD::ABDS:
5640 case ISD::SMIN:
5641 case ISD::SMAX:
5642 case ISD::SCMP:
5643 case ISD::UMIN:
5644 case ISD::UMAX:
5645 case ISD::UCMP:
5646 case ISD::AND:
5647 case ISD::XOR:
5648 case ISD::ROTL:
5649 case ISD::ROTR:
5650 case ISD::FSHL:
5651 case ISD::FSHR:
5652 case ISD::BSWAP:
5653 case ISD::CTTZ:
5654 case ISD::CTLZ:
5655 case ISD::CTPOP:
5656 case ISD::BITREVERSE:
5657 case ISD::PARITY:
5658 case ISD::SIGN_EXTEND:
5659 case ISD::TRUNCATE:
5663 case ISD::BITCAST:
5664 case ISD::BUILD_VECTOR:
5665 case ISD::BUILD_PAIR:
5666 case ISD::SPLAT_VECTOR:
5667 case ISD::FABS:
5668 return false;
5669
5670 case ISD::ABS:
5671 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
5672 // Different to Intrinsic::abs.
5673 return false;
5674
5675 case ISD::ADDC:
5676 case ISD::SUBC:
5677 case ISD::ADDE:
5678 case ISD::SUBE:
5679 case ISD::SADDO:
5680 case ISD::SSUBO:
5681 case ISD::SMULO:
5682 case ISD::SADDO_CARRY:
5683 case ISD::SSUBO_CARRY:
5684 case ISD::UADDO:
5685 case ISD::USUBO:
5686 case ISD::UMULO:
5687 case ISD::UADDO_CARRY:
5688 case ISD::USUBO_CARRY:
5689 // No poison on result or overflow flags.
5690 return false;
5691
5692 case ISD::SELECT_CC:
5693 case ISD::SETCC: {
5694 // Integer setcc cannot create undef or poison.
5695 if (Op.getOperand(0).getValueType().isInteger())
5696 return false;
5697
5698 // FP compares are more complicated. They can create poison for nan/infinity
5699 // based on options and flags. The options and flags also cause special
5700 // nonan condition codes to be used. Those condition codes may be preserved
5701 // even if the nonan flag is dropped somewhere.
5702 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
5703 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
5704 return (unsigned)CCCode & 0x10U;
5705 }
5706
5707 case ISD::OR:
5708 case ISD::ZERO_EXTEND:
5709 case ISD::SELECT:
5710 case ISD::VSELECT:
5711 case ISD::ADD:
5712 case ISD::SUB:
5713 case ISD::MUL:
5714 case ISD::FNEG:
5715 case ISD::FADD:
5716 case ISD::FSUB:
5717 case ISD::FMUL:
5718 case ISD::FDIV:
5719 case ISD::FREM:
5720 case ISD::FCOPYSIGN:
5721 case ISD::FMA:
5722 case ISD::FMAD:
5723 case ISD::FMULADD:
5724 case ISD::FP_EXTEND:
5727 // No poison except from flags (which is handled above)
5728 return false;
5729
5730 case ISD::SHL:
5731 case ISD::SRL:
5732 case ISD::SRA:
5733 // If the max shift amount isn't in range, then the shift can
5734 // create poison.
5735 return !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
5736
5739 // If the amount is zero then the result will be poison.
5740 // TODO: Add isKnownNeverZero DemandedElts handling.
5741 return !isKnownNeverZero(Op.getOperand(0), Depth + 1);
5742
5744 // Check if we demand any upper (undef) elements.
5745 return !PoisonOnly && DemandedElts.ugt(1);
5746
5749 // Ensure that the element index is in bounds.
5750 EVT VecVT = Op.getOperand(0).getValueType();
5751 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
5752 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
5753 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
5754 }
5755
5756 case ISD::VECTOR_SHUFFLE: {
5757 // Check for any demanded shuffle element that is undef.
5758 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5759 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
5760 if (Elt < 0 && DemandedElts[Idx])
5761 return true;
5762 return false;
5763 }
5764
5766 return false;
5767
5768 default:
5769 // Allow the target to implement this method for its nodes.
5770 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5771 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5772 return TLI->canCreateUndefOrPoisonForTargetNode(
5773 Op, DemandedElts, *this, PoisonOnly, ConsiderFlags, Depth);
5774 break;
5775 }
5776
5777 // Be conservative and return true.
5778 return true;
5779}
5780
5781bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
5782 unsigned Opcode = Op.getOpcode();
5783 if (Opcode == ISD::OR)
5784 return Op->getFlags().hasDisjoint() ||
5785 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
5786 if (Opcode == ISD::XOR)
5787 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
5788 return false;
5789}
5790
5792 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
5793 (Op.isAnyAdd() || isADDLike(Op));
5794}
5795
5797 unsigned Depth) const {
5798 EVT VT = Op.getValueType();
5799
5800 // Since the number of lanes in a scalable vector is unknown at compile time,
5801 // we track one bit which is implicitly broadcast to all lanes. This means
5802 // that all lanes in a scalable vector are considered demanded.
5803 APInt DemandedElts = VT.isFixedLengthVector()
5805 : APInt(1, 1);
5806
5807 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
5808}
5809
5811 bool SNaN, unsigned Depth) const {
5812 assert(!DemandedElts.isZero() && "No demanded elements");
5813
5814 // If we're told that NaNs won't happen, assume they won't.
5815 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
5816 return true;
5817
5818 if (Depth >= MaxRecursionDepth)
5819 return false; // Limit search depth.
5820
5821 // If the value is a constant, we can obviously see if it is a NaN or not.
5823 return !C->getValueAPF().isNaN() ||
5824 (SNaN && !C->getValueAPF().isSignaling());
5825 }
5826
5827 unsigned Opcode = Op.getOpcode();
5828 switch (Opcode) {
5829 case ISD::FADD:
5830 case ISD::FSUB:
5831 case ISD::FMUL:
5832 case ISD::FDIV:
5833 case ISD::FREM:
5834 case ISD::FSIN:
5835 case ISD::FCOS:
5836 case ISD::FTAN:
5837 case ISD::FASIN:
5838 case ISD::FACOS:
5839 case ISD::FATAN:
5840 case ISD::FATAN2:
5841 case ISD::FSINH:
5842 case ISD::FCOSH:
5843 case ISD::FTANH:
5844 case ISD::FMA:
5845 case ISD::FMULADD:
5846 case ISD::FMAD: {
5847 if (SNaN)
5848 return true;
5849 // TODO: Need isKnownNeverInfinity
5850 return false;
5851 }
5852 case ISD::FCANONICALIZE:
5853 case ISD::FEXP:
5854 case ISD::FEXP2:
5855 case ISD::FEXP10:
5856 case ISD::FTRUNC:
5857 case ISD::FFLOOR:
5858 case ISD::FCEIL:
5859 case ISD::FROUND:
5860 case ISD::FROUNDEVEN:
5861 case ISD::LROUND:
5862 case ISD::LLROUND:
5863 case ISD::FRINT:
5864 case ISD::LRINT:
5865 case ISD::LLRINT:
5866 case ISD::FNEARBYINT:
5867 case ISD::FLDEXP: {
5868 if (SNaN)
5869 return true;
5870 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
5871 }
5872 case ISD::FABS:
5873 case ISD::FNEG:
5874 case ISD::FCOPYSIGN: {
5875 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
5876 }
5877 case ISD::SELECT:
5878 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
5879 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
5880 case ISD::FP_EXTEND:
5881 case ISD::FP_ROUND: {
5882 if (SNaN)
5883 return true;
5884 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
5885 }
5886 case ISD::SINT_TO_FP:
5887 case ISD::UINT_TO_FP:
5888 return true;
5889 case ISD::FSQRT: // Need is known positive
5890 case ISD::FLOG:
5891 case ISD::FLOG2:
5892 case ISD::FLOG10:
5893 case ISD::FPOWI:
5894 case ISD::FPOW: {
5895 if (SNaN)
5896 return true;
5897 // TODO: Refine on operand
5898 return false;
5899 }
5900 case ISD::FMINNUM:
5901 case ISD::FMAXNUM:
5902 case ISD::FMINIMUMNUM:
5903 case ISD::FMAXIMUMNUM: {
5904 // Only one needs to be known not-nan, since it will be returned if the
5905 // other ends up being one.
5906 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
5907 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
5908 }
5909 case ISD::FMINNUM_IEEE:
5910 case ISD::FMAXNUM_IEEE: {
5911 if (SNaN)
5912 return true;
5913 // This can return a NaN if either operand is an sNaN, or if both operands
5914 // are NaN.
5915 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
5916 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
5917 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
5918 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
5919 }
5920 case ISD::FMINIMUM:
5921 case ISD::FMAXIMUM: {
5922 // TODO: Does this quiet or return the origina NaN as-is?
5923 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
5924 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
5925 }
5927 SDValue Src = Op.getOperand(0);
5928 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5929 EVT SrcVT = Src.getValueType();
5930 if (SrcVT.isFixedLengthVector() && Idx &&
5931 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5932 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5933 Idx->getZExtValue());
5934 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
5935 }
5936 return isKnownNeverNaN(Src, SNaN, Depth + 1);
5937 }
5939 SDValue Src = Op.getOperand(0);
5940 if (Src.getValueType().isFixedLengthVector()) {
5941 unsigned Idx = Op.getConstantOperandVal(1);
5942 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5943 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5944 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
5945 }
5946 return isKnownNeverNaN(Src, SNaN, Depth + 1);
5947 }
5948 case ISD::INSERT_SUBVECTOR: {
5949 SDValue BaseVector = Op.getOperand(0);
5950 SDValue SubVector = Op.getOperand(1);
5951 EVT BaseVectorVT = BaseVector.getValueType();
5952 if (BaseVectorVT.isFixedLengthVector()) {
5953 unsigned Idx = Op.getConstantOperandVal(2);
5954 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
5955 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
5956
5957 // Clear/Extract the bits at the position where the subvector will be
5958 // inserted.
5959 APInt DemandedMask =
5960 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
5961 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
5962 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5963
5964 bool NeverNaN = true;
5965 if (!DemandedSrcElts.isZero())
5966 NeverNaN &=
5967 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
5968 if (NeverNaN && !DemandedSubElts.isZero())
5969 NeverNaN &=
5970 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
5971 return NeverNaN;
5972 }
5973 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
5974 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
5975 }
5976 case ISD::BUILD_VECTOR: {
5977 unsigned NumElts = Op.getNumOperands();
5978 for (unsigned I = 0; I != NumElts; ++I)
5979 if (DemandedElts[I] &&
5980 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
5981 return false;
5982 return true;
5983 }
5984 case ISD::AssertNoFPClass: {
5985 FPClassTest NoFPClass =
5986 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
5987 if ((NoFPClass & fcNan) == fcNan)
5988 return true;
5989 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
5990 return true;
5991 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
5992 }
5993 default:
5994 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5995 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
5996 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
5997 Depth);
5998 }
5999
6000 return false;
6001 }
6002}
6003
6005 assert(Op.getValueType().isFloatingPoint() &&
6006 "Floating point type expected");
6007
6008 // If the value is a constant, we can obviously see if it is a zero or not.
6010 Op, [](ConstantFPSDNode *C) { return !C->isZero(); });
6011}
6012
6014 if (Depth >= MaxRecursionDepth)
6015 return false; // Limit search depth.
6016
6017 assert(!Op.getValueType().isFloatingPoint() &&
6018 "Floating point types unsupported - use isKnownNeverZeroFloat");
6019
6020 // If the value is a constant, we can obviously see if it is a zero or not.
6022 [](ConstantSDNode *C) { return !C->isZero(); }))
6023 return true;
6024
6025 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6026 // some degree.
6027 switch (Op.getOpcode()) {
6028 default:
6029 break;
6030
6031 case ISD::OR:
6032 return isKnownNeverZero(Op.getOperand(1), Depth + 1) ||
6033 isKnownNeverZero(Op.getOperand(0), Depth + 1);
6034
6035 case ISD::VSELECT:
6036 case ISD::SELECT:
6037 return isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6038 isKnownNeverZero(Op.getOperand(2), Depth + 1);
6039
6040 case ISD::SHL: {
6041 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6042 return isKnownNeverZero(Op.getOperand(0), Depth + 1);
6043 KnownBits ValKnown = computeKnownBits(Op.getOperand(0), Depth + 1);
6044 // 1 << X is never zero.
6045 if (ValKnown.One[0])
6046 return true;
6047 // If max shift cnt of known ones is non-zero, result is non-zero.
6048 APInt MaxCnt = computeKnownBits(Op.getOperand(1), Depth + 1).getMaxValue();
6049 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6050 !ValKnown.One.shl(MaxCnt).isZero())
6051 return true;
6052 break;
6053 }
6054 case ISD::UADDSAT:
6055 case ISD::UMAX:
6056 return isKnownNeverZero(Op.getOperand(1), Depth + 1) ||
6057 isKnownNeverZero(Op.getOperand(0), Depth + 1);
6058
6059 // For smin/smax: If either operand is known negative/positive
6060 // respectively we don't need the other to be known at all.
6061 case ISD::SMAX: {
6062 KnownBits Op1 = computeKnownBits(Op.getOperand(1), Depth + 1);
6063 if (Op1.isStrictlyPositive())
6064 return true;
6065
6066 KnownBits Op0 = computeKnownBits(Op.getOperand(0), Depth + 1);
6067 if (Op0.isStrictlyPositive())
6068 return true;
6069
6070 if (Op1.isNonZero() && Op0.isNonZero())
6071 return true;
6072
6073 return isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6074 isKnownNeverZero(Op.getOperand(0), Depth + 1);
6075 }
6076 case ISD::SMIN: {
6077 KnownBits Op1 = computeKnownBits(Op.getOperand(1), Depth + 1);
6078 if (Op1.isNegative())
6079 return true;
6080
6081 KnownBits Op0 = computeKnownBits(Op.getOperand(0), Depth + 1);
6082 if (Op0.isNegative())
6083 return true;
6084
6085 if (Op1.isNonZero() && Op0.isNonZero())
6086 return true;
6087
6088 return isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6089 isKnownNeverZero(Op.getOperand(0), Depth + 1);
6090 }
6091 case ISD::UMIN:
6092 return isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6093 isKnownNeverZero(Op.getOperand(0), Depth + 1);
6094
6095 case ISD::ROTL:
6096 case ISD::ROTR:
6097 case ISD::BITREVERSE:
6098 case ISD::BSWAP:
6099 case ISD::CTPOP:
6100 case ISD::ABS:
6101 return isKnownNeverZero(Op.getOperand(0), Depth + 1);
6102
6103 case ISD::SRA:
6104 case ISD::SRL: {
6105 if (Op->getFlags().hasExact())
6106 return isKnownNeverZero(Op.getOperand(0), Depth + 1);
6107 KnownBits ValKnown = computeKnownBits(Op.getOperand(0), Depth + 1);
6108 if (ValKnown.isNegative())
6109 return true;
6110 // If max shift cnt of known ones is non-zero, result is non-zero.
6111 APInt MaxCnt = computeKnownBits(Op.getOperand(1), Depth + 1).getMaxValue();
6112 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6113 !ValKnown.One.lshr(MaxCnt).isZero())
6114 return true;
6115 break;
6116 }
6117 case ISD::UDIV:
6118 case ISD::SDIV:
6119 // div exact can only produce a zero if the dividend is zero.
6120 // TODO: For udiv this is also true if Op1 u<= Op0
6121 if (Op->getFlags().hasExact())
6122 return isKnownNeverZero(Op.getOperand(0), Depth + 1);
6123 break;
6124
6125 case ISD::ADD:
6126 if (Op->getFlags().hasNoUnsignedWrap())
6127 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) ||
6128 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6129 return true;
6130 // TODO: There are a lot more cases we can prove for add.
6131 break;
6132
6133 case ISD::SUB: {
6134 if (isNullConstant(Op.getOperand(0)))
6135 return isKnownNeverZero(Op.getOperand(1), Depth + 1);
6136
6137 std::optional<bool> ne =
6138 KnownBits::ne(computeKnownBits(Op.getOperand(0), Depth + 1),
6139 computeKnownBits(Op.getOperand(1), Depth + 1));
6140 return ne && *ne;
6141 }
6142
6143 case ISD::MUL:
6144 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6145 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6146 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6147 return true;
6148 break;
6149
6150 case ISD::ZERO_EXTEND:
6151 case ISD::SIGN_EXTEND:
6152 return isKnownNeverZero(Op.getOperand(0), Depth + 1);
6153 case ISD::VSCALE: {
6155 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6156 ConstantRange CR =
6157 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6158 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6159 return true;
6160 break;
6161 }
6162 }
6163
6165}
6166
6168 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6169 return !C1->isNegative();
6170
6171 switch (Op.getOpcode()) {
6172 case ISD::FABS:
6173 case ISD::FEXP:
6174 case ISD::FEXP2:
6175 case ISD::FEXP10:
6176 return true;
6177 default:
6178 return false;
6179 }
6180
6181 llvm_unreachable("covered opcode switch");
6182}
6183
6185 assert(Use.getValueType().isFloatingPoint());
6186 const SDNode *User = Use.getUser();
6187 unsigned OperandNo = Use.getOperandNo();
6188 // Check if this use is insensitive to the sign of zero
6189 switch (User->getOpcode()) {
6190 case ISD::SETCC:
6191 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6192 case ISD::FABS:
6193 // fabs always produces +0.0.
6194 return true;
6195 case ISD::FCOPYSIGN:
6196 // copysign overwrites the sign bit of the first operand.
6197 return OperandNo == 0;
6198 case ISD::FADD:
6199 case ISD::FSUB: {
6200 // Arithmetic with non-zero constants fixes the uncertainty around the
6201 // sign bit.
6202 SDValue Other = User->getOperand(1 - OperandNo);
6204 }
6205 case ISD::FP_TO_SINT:
6206 case ISD::FP_TO_UINT:
6207 // fp-to-int conversions normalize signed zeros.
6208 return true;
6209 default:
6210 return false;
6211 }
6212}
6213
6215 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6216 // regression. Ideally, this should be implemented as a demanded-bits
6217 // optimization that stems from the users.
6218 if (Op->use_size() > 2)
6219 return false;
6220 return all_of(Op->uses(),
6221 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6222}
6223
6225 // Check the obvious case.
6226 if (A == B) return true;
6227
6228 // For negative and positive zero.
6231 if (CA->isZero() && CB->isZero()) return true;
6232
6233 // Otherwise they may not be equal.
6234 return false;
6235}
6236
6237// Only bits set in Mask must be negated, other bits may be arbitrary.
6239 if (isBitwiseNot(V, AllowUndefs))
6240 return V.getOperand(0);
6241
6242 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6243 // bits in the non-extended part.
6244 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6245 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6246 return SDValue();
6247 SDValue ExtArg = V.getOperand(0);
6248 if (ExtArg.getScalarValueSizeInBits() >=
6249 MaskC->getAPIntValue().getActiveBits() &&
6250 isBitwiseNot(ExtArg, AllowUndefs) &&
6251 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6252 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6253 return ExtArg.getOperand(0).getOperand(0);
6254 return SDValue();
6255}
6256
6258 // Match masked merge pattern (X & ~M) op (Y & M)
6259 // Including degenerate case (X & ~M) op M
6260 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6261 SDValue Other) {
6262 if (SDValue NotOperand =
6263 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6264 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6265 NotOperand->getOpcode() == ISD::TRUNCATE)
6266 NotOperand = NotOperand->getOperand(0);
6267
6268 if (Other == NotOperand)
6269 return true;
6270 if (Other->getOpcode() == ISD::AND)
6271 return NotOperand == Other->getOperand(0) ||
6272 NotOperand == Other->getOperand(1);
6273 }
6274 return false;
6275 };
6276
6277 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6278 A = A->getOperand(0);
6279
6280 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6281 B = B->getOperand(0);
6282
6283 if (A->getOpcode() == ISD::AND)
6284 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6285 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6286 return false;
6287}
6288
6289// FIXME: unify with llvm::haveNoCommonBitsSet.
6291 assert(A.getValueType() == B.getValueType() &&
6292 "Values must have the same type");
6295 return true;
6298}
6299
6300static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6301 SelectionDAG &DAG) {
6302 if (cast<ConstantSDNode>(Step)->isZero())
6303 return DAG.getConstant(0, DL, VT);
6304
6305 return SDValue();
6306}
6307
6310 SelectionDAG &DAG) {
6311 int NumOps = Ops.size();
6312 assert(NumOps != 0 && "Can't build an empty vector!");
6313 assert(!VT.isScalableVector() &&
6314 "BUILD_VECTOR cannot be used with scalable types");
6315 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6316 "Incorrect element count in BUILD_VECTOR!");
6317
6318 // BUILD_VECTOR of UNDEFs is UNDEF.
6319 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
6320 return DAG.getUNDEF(VT);
6321
6322 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6323 SDValue IdentitySrc;
6324 bool IsIdentity = true;
6325 for (int i = 0; i != NumOps; ++i) {
6327 Ops[i].getOperand(0).getValueType() != VT ||
6328 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6329 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6330 Ops[i].getConstantOperandAPInt(1) != i) {
6331 IsIdentity = false;
6332 break;
6333 }
6334 IdentitySrc = Ops[i].getOperand(0);
6335 }
6336 if (IsIdentity)
6337 return IdentitySrc;
6338
6339 return SDValue();
6340}
6341
6342/// Try to simplify vector concatenation to an input value, undef, or build
6343/// vector.
6346 SelectionDAG &DAG) {
6347 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6349 [Ops](SDValue Op) {
6350 return Ops[0].getValueType() == Op.getValueType();
6351 }) &&
6352 "Concatenation of vectors with inconsistent value types!");
6353 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6354 VT.getVectorElementCount() &&
6355 "Incorrect element count in vector concatenation!");
6356
6357 if (Ops.size() == 1)
6358 return Ops[0];
6359
6360 // Concat of UNDEFs is UNDEF.
6361 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
6362 return DAG.getUNDEF(VT);
6363
6364 // Scan the operands and look for extract operations from a single source
6365 // that correspond to insertion at the same location via this concatenation:
6366 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
6367 SDValue IdentitySrc;
6368 bool IsIdentity = true;
6369 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
6370 SDValue Op = Ops[i];
6371 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
6372 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6373 Op.getOperand(0).getValueType() != VT ||
6374 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
6375 Op.getConstantOperandVal(1) != IdentityIndex) {
6376 IsIdentity = false;
6377 break;
6378 }
6379 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
6380 "Unexpected identity source vector for concat of extracts");
6381 IdentitySrc = Op.getOperand(0);
6382 }
6383 if (IsIdentity) {
6384 assert(IdentitySrc && "Failed to set source vector of extracts");
6385 return IdentitySrc;
6386 }
6387
6388 // The code below this point is only designed to work for fixed width
6389 // vectors, so we bail out for now.
6390 if (VT.isScalableVector())
6391 return SDValue();
6392
6393 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
6394 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
6395 // BUILD_VECTOR.
6396 // FIXME: Add support for SCALAR_TO_VECTOR as well.
6397 EVT SVT = VT.getScalarType();
6399 for (SDValue Op : Ops) {
6400 EVT OpVT = Op.getValueType();
6401 if (Op.isUndef())
6402 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
6403 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
6404 Elts.append(Op->op_begin(), Op->op_end());
6405 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
6406 OpVT.getVectorNumElements() == 1 &&
6407 isNullConstant(Op.getOperand(2)))
6408 Elts.push_back(Op.getOperand(1));
6409 else
6410 return SDValue();
6411 }
6412
6413 // BUILD_VECTOR requires all inputs to be of the same type, find the
6414 // maximum type and extend them all.
6415 for (SDValue Op : Elts)
6416 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
6417
6418 if (SVT.bitsGT(VT.getScalarType())) {
6419 for (SDValue &Op : Elts) {
6420 if (Op.isUndef())
6421 Op = DAG.getUNDEF(SVT);
6422 else
6423 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
6424 ? DAG.getZExtOrTrunc(Op, DL, SVT)
6425 : DAG.getSExtOrTrunc(Op, DL, SVT);
6426 }
6427 }
6428
6429 SDValue V = DAG.getBuildVector(VT, DL, Elts);
6430 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
6431 return V;
6432}
6433
6434/// Gets or creates the specified node.
6435SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
6436 SDVTList VTs = getVTList(VT);
6438 AddNodeIDNode(ID, Opcode, VTs, {});
6439 void *IP = nullptr;
6440 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6441 return SDValue(E, 0);
6442
6443 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6444 CSEMap.InsertNode(N, IP);
6445
6446 InsertNode(N);
6447 SDValue V = SDValue(N, 0);
6448 NewSDValueDbgMsg(V, "Creating new node: ", this);
6449 return V;
6450}
6451
6452SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6453 SDValue N1) {
6454 SDNodeFlags Flags;
6455 if (Inserter)
6456 Flags = Inserter->getFlags();
6457 return getNode(Opcode, DL, VT, N1, Flags);
6458}
6459
6460SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6461 SDValue N1, const SDNodeFlags Flags) {
6462 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
6463
6464 // Constant fold unary operations with a vector integer or float operand.
6465 switch (Opcode) {
6466 default:
6467 // FIXME: Entirely reasonable to perform folding of other unary
6468 // operations here as the need arises.
6469 break;
6470 case ISD::FNEG:
6471 case ISD::FABS:
6472 case ISD::FCEIL:
6473 case ISD::FTRUNC:
6474 case ISD::FFLOOR:
6475 case ISD::FP_EXTEND:
6476 case ISD::FP_TO_SINT:
6477 case ISD::FP_TO_UINT:
6478 case ISD::FP_TO_FP16:
6479 case ISD::FP_TO_BF16:
6480 case ISD::TRUNCATE:
6481 case ISD::ANY_EXTEND:
6482 case ISD::ZERO_EXTEND:
6483 case ISD::SIGN_EXTEND:
6484 case ISD::UINT_TO_FP:
6485 case ISD::SINT_TO_FP:
6486 case ISD::FP16_TO_FP:
6487 case ISD::BF16_TO_FP:
6488 case ISD::BITCAST:
6489 case ISD::ABS:
6490 case ISD::BITREVERSE:
6491 case ISD::BSWAP:
6492 case ISD::CTLZ:
6494 case ISD::CTTZ:
6496 case ISD::CTPOP:
6497 case ISD::STEP_VECTOR: {
6498 SDValue Ops = {N1};
6499 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
6500 return Fold;
6501 }
6502 }
6503
6504 unsigned OpOpcode = N1.getNode()->getOpcode();
6505 switch (Opcode) {
6506 case ISD::STEP_VECTOR:
6507 assert(VT.isScalableVector() &&
6508 "STEP_VECTOR can only be used with scalable types");
6509 assert(OpOpcode == ISD::TargetConstant &&
6510 VT.getVectorElementType() == N1.getValueType() &&
6511 "Unexpected step operand");
6512 break;
6513 case ISD::FREEZE:
6514 assert(VT == N1.getValueType() && "Unexpected VT!");
6515 if (isGuaranteedNotToBeUndefOrPoison(N1, /*PoisonOnly=*/false))
6516 return N1;
6517 break;
6518 case ISD::TokenFactor:
6519 case ISD::MERGE_VALUES:
6521 return N1; // Factor, merge or concat of one node? No need.
6522 case ISD::BUILD_VECTOR: {
6523 // Attempt to simplify BUILD_VECTOR.
6524 SDValue Ops[] = {N1};
6525 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6526 return V;
6527 break;
6528 }
6529 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
6530 case ISD::FP_EXTEND:
6532 "Invalid FP cast!");
6533 if (N1.getValueType() == VT) return N1; // noop conversion.
6534 assert((!VT.isVector() || VT.getVectorElementCount() ==
6536 "Vector element count mismatch!");
6537 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
6538 if (N1.isUndef())
6539 return getUNDEF(VT);
6540 break;
6541 case ISD::FP_TO_SINT:
6542 case ISD::FP_TO_UINT:
6543 if (N1.isUndef())
6544 return getUNDEF(VT);
6545 break;
6546 case ISD::SINT_TO_FP:
6547 case ISD::UINT_TO_FP:
6548 // [us]itofp(undef) = 0, because the result value is bounded.
6549 if (N1.isUndef())
6550 return getConstantFP(0.0, DL, VT);
6551 break;
6552 case ISD::SIGN_EXTEND:
6553 assert(VT.isInteger() && N1.getValueType().isInteger() &&
6554 "Invalid SIGN_EXTEND!");
6555 assert(VT.isVector() == N1.getValueType().isVector() &&
6556 "SIGN_EXTEND result type type should be vector iff the operand "
6557 "type is vector!");
6558 if (N1.getValueType() == VT) return N1; // noop extension
6559 assert((!VT.isVector() || VT.getVectorElementCount() ==
6561 "Vector element count mismatch!");
6562 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
6563 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
6564 SDNodeFlags Flags;
6565 if (OpOpcode == ISD::ZERO_EXTEND)
6566 Flags.setNonNeg(N1->getFlags().hasNonNeg());
6567 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
6568 transferDbgValues(N1, NewVal);
6569 return NewVal;
6570 }
6571
6572 if (OpOpcode == ISD::POISON)
6573 return getPOISON(VT);
6574
6575 if (N1.isUndef())
6576 // sext(undef) = 0, because the top bits will all be the same.
6577 return getConstant(0, DL, VT);
6578
6579 // Skip unnecessary sext_inreg pattern:
6580 // (sext (trunc x)) -> x iff the upper bits are all signbits.
6581 if (OpOpcode == ISD::TRUNCATE) {
6582 SDValue OpOp = N1.getOperand(0);
6583 if (OpOp.getValueType() == VT) {
6584 unsigned NumSignExtBits =
6586 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
6587 transferDbgValues(N1, OpOp);
6588 return OpOp;
6589 }
6590 }
6591 }
6592 break;
6593 case ISD::ZERO_EXTEND:
6594 assert(VT.isInteger() && N1.getValueType().isInteger() &&
6595 "Invalid ZERO_EXTEND!");
6596 assert(VT.isVector() == N1.getValueType().isVector() &&
6597 "ZERO_EXTEND result type type should be vector iff the operand "
6598 "type is vector!");
6599 if (N1.getValueType() == VT) return N1; // noop extension
6600 assert((!VT.isVector() || VT.getVectorElementCount() ==
6602 "Vector element count mismatch!");
6603 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
6604 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
6605 SDNodeFlags Flags;
6606 Flags.setNonNeg(N1->getFlags().hasNonNeg());
6607 SDValue NewVal =
6608 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
6609 transferDbgValues(N1, NewVal);
6610 return NewVal;
6611 }
6612
6613 if (OpOpcode == ISD::POISON)
6614 return getPOISON(VT);
6615
6616 if (N1.isUndef())
6617 // zext(undef) = 0, because the top bits will be zero.
6618 return getConstant(0, DL, VT);
6619
6620 // Skip unnecessary zext_inreg pattern:
6621 // (zext (trunc x)) -> x iff the upper bits are known zero.
6622 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
6623 // use to recognise zext_inreg patterns.
6624 if (OpOpcode == ISD::TRUNCATE) {
6625 SDValue OpOp = N1.getOperand(0);
6626 if (OpOp.getValueType() == VT) {
6627 if (OpOp.getOpcode() != ISD::AND) {
6630 if (MaskedValueIsZero(OpOp, HiBits)) {
6631 transferDbgValues(N1, OpOp);
6632 return OpOp;
6633 }
6634 }
6635 }
6636 }
6637 break;
6638 case ISD::ANY_EXTEND:
6639 assert(VT.isInteger() && N1.getValueType().isInteger() &&
6640 "Invalid ANY_EXTEND!");
6641 assert(VT.isVector() == N1.getValueType().isVector() &&
6642 "ANY_EXTEND result type type should be vector iff the operand "
6643 "type is vector!");
6644 if (N1.getValueType() == VT) return N1; // noop extension
6645 assert((!VT.isVector() || VT.getVectorElementCount() ==
6647 "Vector element count mismatch!");
6648 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
6649
6650 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
6651 OpOpcode == ISD::ANY_EXTEND) {
6652 SDNodeFlags Flags;
6653 if (OpOpcode == ISD::ZERO_EXTEND)
6654 Flags.setNonNeg(N1->getFlags().hasNonNeg());
6655 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
6656 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
6657 }
6658 if (N1.isUndef())
6659 return getUNDEF(VT);
6660
6661 // (ext (trunc x)) -> x
6662 if (OpOpcode == ISD::TRUNCATE) {
6663 SDValue OpOp = N1.getOperand(0);
6664 if (OpOp.getValueType() == VT) {
6665 transferDbgValues(N1, OpOp);
6666 return OpOp;
6667 }
6668 }
6669 break;
6670 case ISD::TRUNCATE:
6671 assert(VT.isInteger() && N1.getValueType().isInteger() &&
6672 "Invalid TRUNCATE!");
6673 assert(VT.isVector() == N1.getValueType().isVector() &&
6674 "TRUNCATE result type type should be vector iff the operand "
6675 "type is vector!");
6676 if (N1.getValueType() == VT) return N1; // noop truncate
6677 assert((!VT.isVector() || VT.getVectorElementCount() ==
6679 "Vector element count mismatch!");
6680 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
6681 if (OpOpcode == ISD::TRUNCATE)
6682 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
6683 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
6684 OpOpcode == ISD::ANY_EXTEND) {
6685 // If the source is smaller than the dest, we still need an extend.
6687 VT.getScalarType())) {
6688 SDNodeFlags Flags;
6689 if (OpOpcode == ISD::ZERO_EXTEND)
6690 Flags.setNonNeg(N1->getFlags().hasNonNeg());
6691 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
6692 }
6693 if (N1.getOperand(0).getValueType().bitsGT(VT))
6694 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
6695 return N1.getOperand(0);
6696 }
6697 if (N1.isUndef())
6698 return getUNDEF(VT);
6699 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
6700 return getVScale(DL, VT,
6702 break;
6706 assert(VT.isVector() && "This DAG node is restricted to vector types.");
6707 assert(N1.getValueType().bitsLE(VT) &&
6708 "The input must be the same size or smaller than the result.");
6711 "The destination vector type must have fewer lanes than the input.");
6712 break;
6713 case ISD::ABS:
6714 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
6715 if (N1.isUndef())
6716 return getConstant(0, DL, VT);
6717 break;
6718 case ISD::BSWAP:
6719 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
6720 assert((VT.getScalarSizeInBits() % 16 == 0) &&
6721 "BSWAP types must be a multiple of 16 bits!");
6722 if (N1.isUndef())
6723 return getUNDEF(VT);
6724 // bswap(bswap(X)) -> X.
6725 if (OpOpcode == ISD::BSWAP)
6726 return N1.getOperand(0);
6727 break;
6728 case ISD::BITREVERSE:
6729 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
6730 if (N1.isUndef())
6731 return getUNDEF(VT);
6732 break;
6733 case ISD::BITCAST:
6735 "Cannot BITCAST between types of different sizes!");
6736 if (VT == N1.getValueType()) return N1; // noop conversion.
6737 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
6738 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
6739 if (N1.isUndef())
6740 return getUNDEF(VT);
6741 break;
6743 assert(VT.isVector() && !N1.getValueType().isVector() &&
6744 (VT.getVectorElementType() == N1.getValueType() ||
6746 N1.getValueType().isInteger() &&
6748 "Illegal SCALAR_TO_VECTOR node!");
6749 if (N1.isUndef())
6750 return getUNDEF(VT);
6751 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
6752 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
6754 N1.getConstantOperandVal(1) == 0 &&
6755 N1.getOperand(0).getValueType() == VT)
6756 return N1.getOperand(0);
6757 break;
6758 case ISD::FNEG:
6759 // Negation of an unknown bag of bits is still completely undefined.
6760 if (N1.isUndef())
6761 return getUNDEF(VT);
6762
6763 if (OpOpcode == ISD::FNEG) // --X -> X
6764 return N1.getOperand(0);
6765 break;
6766 case ISD::FABS:
6767 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
6768 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
6769 break;
6770 case ISD::VSCALE:
6771 assert(VT == N1.getValueType() && "Unexpected VT!");
6772 break;
6773 case ISD::CTPOP:
6774 if (N1.getValueType().getScalarType() == MVT::i1)
6775 return N1;
6776 break;
6777 case ISD::CTLZ:
6778 case ISD::CTTZ:
6779 if (N1.getValueType().getScalarType() == MVT::i1)
6780 return getNOT(DL, N1, N1.getValueType());
6781 break;
6782 case ISD::VECREDUCE_ADD:
6783 if (N1.getValueType().getScalarType() == MVT::i1)
6784 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
6785 break;
6788 if (N1.getValueType().getScalarType() == MVT::i1)
6789 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
6790 break;
6793 if (N1.getValueType().getScalarType() == MVT::i1)
6794 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
6795 break;
6796 case ISD::SPLAT_VECTOR:
6797 assert(VT.isVector() && "Wrong return type!");
6798 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
6799 // that for now.
6801 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
6803 N1.getValueType().isInteger() &&
6805 "Wrong operand type!");
6806 break;
6807 }
6808
6809 SDNode *N;
6810 SDVTList VTs = getVTList(VT);
6811 SDValue Ops[] = {N1};
6812 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
6814 AddNodeIDNode(ID, Opcode, VTs, Ops);
6815 void *IP = nullptr;
6816 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6817 E->intersectFlagsWith(Flags);
6818 return SDValue(E, 0);
6819 }
6820
6821 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6822 N->setFlags(Flags);
6823 createOperands(N, Ops);
6824 CSEMap.InsertNode(N, IP);
6825 } else {
6826 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6827 createOperands(N, Ops);
6828 }
6829
6830 InsertNode(N);
6831 SDValue V = SDValue(N, 0);
6832 NewSDValueDbgMsg(V, "Creating new node: ", this);
6833 return V;
6834}
6835
6836static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
6837 const APInt &C2) {
6838 switch (Opcode) {
6839 case ISD::ADD: return C1 + C2;
6840 case ISD::SUB: return C1 - C2;
6841 case ISD::MUL: return C1 * C2;
6842 case ISD::AND: return C1 & C2;
6843 case ISD::OR: return C1 | C2;
6844 case ISD::XOR: return C1 ^ C2;
6845 case ISD::SHL: return C1 << C2;
6846 case ISD::SRL: return C1.lshr(C2);
6847 case ISD::SRA: return C1.ashr(C2);
6848 case ISD::ROTL: return C1.rotl(C2);
6849 case ISD::ROTR: return C1.rotr(C2);
6850 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
6851 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
6852 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
6853 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
6854 case ISD::SADDSAT: return C1.sadd_sat(C2);
6855 case ISD::UADDSAT: return C1.uadd_sat(C2);
6856 case ISD::SSUBSAT: return C1.ssub_sat(C2);
6857 case ISD::USUBSAT: return C1.usub_sat(C2);
6858 case ISD::SSHLSAT: return C1.sshl_sat(C2);
6859 case ISD::USHLSAT: return C1.ushl_sat(C2);
6860 case ISD::UDIV:
6861 if (!C2.getBoolValue())
6862 break;
6863 return C1.udiv(C2);
6864 case ISD::UREM:
6865 if (!C2.getBoolValue())
6866 break;
6867 return C1.urem(C2);
6868 case ISD::SDIV:
6869 if (!C2.getBoolValue())
6870 break;
6871 return C1.sdiv(C2);
6872 case ISD::SREM:
6873 if (!C2.getBoolValue())
6874 break;
6875 return C1.srem(C2);
6876 case ISD::AVGFLOORS:
6877 return APIntOps::avgFloorS(C1, C2);
6878 case ISD::AVGFLOORU:
6879 return APIntOps::avgFloorU(C1, C2);
6880 case ISD::AVGCEILS:
6881 return APIntOps::avgCeilS(C1, C2);
6882 case ISD::AVGCEILU:
6883 return APIntOps::avgCeilU(C1, C2);
6884 case ISD::ABDS:
6885 return APIntOps::abds(C1, C2);
6886 case ISD::ABDU:
6887 return APIntOps::abdu(C1, C2);
6888 case ISD::MULHS:
6889 return APIntOps::mulhs(C1, C2);
6890 case ISD::MULHU:
6891 return APIntOps::mulhu(C1, C2);
6892 }
6893 return std::nullopt;
6894}
6895// Handle constant folding with UNDEF.
6896// TODO: Handle more cases.
6897static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
6898 bool IsUndef1, const APInt &C2,
6899 bool IsUndef2) {
6900 if (!(IsUndef1 || IsUndef2))
6901 return FoldValue(Opcode, C1, C2);
6902
6903 // Fold and(x, undef) -> 0
6904 // Fold mul(x, undef) -> 0
6905 if (Opcode == ISD::AND || Opcode == ISD::MUL)
6906 return APInt::getZero(C1.getBitWidth());
6907
6908 return std::nullopt;
6909}
6910
6912 const GlobalAddressSDNode *GA,
6913 const SDNode *N2) {
6914 if (GA->getOpcode() != ISD::GlobalAddress)
6915 return SDValue();
6916 if (!TLI->isOffsetFoldingLegal(GA))
6917 return SDValue();
6918 auto *C2 = dyn_cast<ConstantSDNode>(N2);
6919 if (!C2)
6920 return SDValue();
6921 int64_t Offset = C2->getSExtValue();
6922 switch (Opcode) {
6923 case ISD::ADD:
6924 case ISD::PTRADD:
6925 break;
6926 case ISD::SUB: Offset = -uint64_t(Offset); break;
6927 default: return SDValue();
6928 }
6929 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
6930 GA->getOffset() + uint64_t(Offset));
6931}
6932
6934 switch (Opcode) {
6935 case ISD::SDIV:
6936 case ISD::UDIV:
6937 case ISD::SREM:
6938 case ISD::UREM: {
6939 // If a divisor is zero/undef or any element of a divisor vector is
6940 // zero/undef, the whole op is undef.
6941 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
6942 SDValue Divisor = Ops[1];
6943 if (Divisor.isUndef() || isNullConstant(Divisor))
6944 return true;
6945
6946 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
6947 llvm::any_of(Divisor->op_values(),
6948 [](SDValue V) { return V.isUndef() ||
6949 isNullConstant(V); });
6950 // TODO: Handle signed overflow.
6951 }
6952 // TODO: Handle oversized shifts.
6953 default:
6954 return false;
6955 }
6956}
6957
6960 SDNodeFlags Flags) {
6961 // If the opcode is a target-specific ISD node, there's nothing we can
6962 // do here and the operand rules may not line up with the below, so
6963 // bail early.
6964 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
6965 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
6966 // foldCONCAT_VECTORS in getNode before this is called.
6967 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
6968 return SDValue();
6969
6970 unsigned NumOps = Ops.size();
6971 if (NumOps == 0)
6972 return SDValue();
6973
6974 if (isUndef(Opcode, Ops))
6975 return getUNDEF(VT);
6976
6977 // Handle unary special cases.
6978 if (NumOps == 1) {
6979 SDValue N1 = Ops[0];
6980
6981 // Constant fold unary operations with an integer constant operand. Even
6982 // opaque constant will be folded, because the folding of unary operations
6983 // doesn't create new constants with different values. Nevertheless, the
6984 // opaque flag is preserved during folding to prevent future folding with
6985 // other constants.
6986 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
6987 const APInt &Val = C->getAPIntValue();
6988 switch (Opcode) {
6989 case ISD::SIGN_EXTEND:
6990 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
6991 C->isTargetOpcode(), C->isOpaque());
6992 case ISD::TRUNCATE:
6993 if (C->isOpaque())
6994 break;
6995 [[fallthrough]];
6996 case ISD::ZERO_EXTEND:
6997 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
6998 C->isTargetOpcode(), C->isOpaque());
6999 case ISD::ANY_EXTEND:
7000 // Some targets like RISCV prefer to sign extend some types.
7001 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7002 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7003 C->isTargetOpcode(), C->isOpaque());
7004 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7005 C->isTargetOpcode(), C->isOpaque());
7006 case ISD::ABS:
7007 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7008 C->isOpaque());
7009 case ISD::BITREVERSE:
7010 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7011 C->isOpaque());
7012 case ISD::BSWAP:
7013 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7014 C->isOpaque());
7015 case ISD::CTPOP:
7016 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7017 C->isOpaque());
7018 case ISD::CTLZ:
7020 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7021 C->isOpaque());
7022 case ISD::CTTZ:
7024 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7025 C->isOpaque());
7026 case ISD::UINT_TO_FP:
7027 case ISD::SINT_TO_FP: {
7029 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7031 return getConstantFP(FPV, DL, VT);
7032 }
7033 case ISD::FP16_TO_FP:
7034 case ISD::BF16_TO_FP: {
7035 bool Ignored;
7036 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7037 : APFloat::BFloat(),
7038 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7039
7040 // This can return overflow, underflow, or inexact; we don't care.
7041 // FIXME need to be more flexible about rounding mode.
7043 &Ignored);
7044 return getConstantFP(FPV, DL, VT);
7045 }
7046 case ISD::STEP_VECTOR:
7047 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7048 return V;
7049 break;
7050 case ISD::BITCAST:
7051 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7052 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7053 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7054 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7055 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7056 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7057 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7058 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7059 break;
7060 }
7061 }
7062
7063 // Constant fold unary operations with a floating point constant operand.
7064 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7065 APFloat V = C->getValueAPF(); // make copy
7066 switch (Opcode) {
7067 case ISD::FNEG:
7068 V.changeSign();
7069 return getConstantFP(V, DL, VT);
7070 case ISD::FABS:
7071 V.clearSign();
7072 return getConstantFP(V, DL, VT);
7073 case ISD::FCEIL: {
7074 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7076 return getConstantFP(V, DL, VT);
7077 return SDValue();
7078 }
7079 case ISD::FTRUNC: {
7080 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7082 return getConstantFP(V, DL, VT);
7083 return SDValue();
7084 }
7085 case ISD::FFLOOR: {
7086 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7088 return getConstantFP(V, DL, VT);
7089 return SDValue();
7090 }
7091 case ISD::FP_EXTEND: {
7092 bool ignored;
7093 // This can return overflow, underflow, or inexact; we don't care.
7094 // FIXME need to be more flexible about rounding mode.
7095 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7096 &ignored);
7097 return getConstantFP(V, DL, VT);
7098 }
7099 case ISD::FP_TO_SINT:
7100 case ISD::FP_TO_UINT: {
7101 bool ignored;
7102 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7103 // FIXME need to be more flexible about rounding mode.
7105 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7106 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7107 break;
7108 return getConstant(IntVal, DL, VT);
7109 }
7110 case ISD::FP_TO_FP16:
7111 case ISD::FP_TO_BF16: {
7112 bool Ignored;
7113 // This can return overflow, underflow, or inexact; we don't care.
7114 // FIXME need to be more flexible about rounding mode.
7115 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7116 : APFloat::BFloat(),
7118 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7119 }
7120 case ISD::BITCAST:
7121 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7122 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7123 VT);
7124 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7125 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7126 VT);
7127 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7128 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7129 VT);
7130 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7131 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7132 break;
7133 }
7134 }
7135
7136 // Early-out if we failed to constant fold a bitcast.
7137 if (Opcode == ISD::BITCAST)
7138 return SDValue();
7139 }
7140
7141 // Handle binops special cases.
7142 if (NumOps == 2) {
7143 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7144 return CFP;
7145
7146 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7147 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7148 if (C1->isOpaque() || C2->isOpaque())
7149 return SDValue();
7150
7151 std::optional<APInt> FoldAttempt =
7152 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7153 if (!FoldAttempt)
7154 return SDValue();
7155
7156 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7157 assert((!Folded || !VT.isVector()) &&
7158 "Can't fold vectors ops with scalar operands");
7159 return Folded;
7160 }
7161 }
7162
7163 // fold (add Sym, c) -> Sym+c
7165 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7166 if (TLI->isCommutativeBinOp(Opcode))
7168 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7169
7170 // fold (sext_in_reg c1) -> c2
7171 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7172 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7173
7174 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7175 unsigned FromBits = EVT.getScalarSizeInBits();
7176 Val <<= Val.getBitWidth() - FromBits;
7177 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7178 return getConstant(Val, DL, ConstantVT);
7179 };
7180
7181 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7182 const APInt &Val = C1->getAPIntValue();
7183 return SignExtendInReg(Val, VT);
7184 }
7185
7187 SmallVector<SDValue, 8> ScalarOps;
7188 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7189 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7190 SDValue Op = Ops[0].getOperand(I);
7191 if (Op.isUndef()) {
7192 ScalarOps.push_back(getUNDEF(OpVT));
7193 continue;
7194 }
7195 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7196 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7197 }
7198 return getBuildVector(VT, DL, ScalarOps);
7199 }
7200
7201 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7202 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7203 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7204 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7205 Ops[0].getOperand(0).getValueType()));
7206 }
7207 }
7208
7209 // Handle fshl/fshr special cases.
7210 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7211 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7212 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7213 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7214
7215 if (C1 && C2 && C3) {
7216 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7217 return SDValue();
7218 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7219 &V3 = C3->getAPIntValue();
7220
7221 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7222 : APIntOps::fshr(V1, V2, V3);
7223 return getConstant(FoldedVal, DL, VT);
7224 }
7225 }
7226
7227 // Handle fma/fmad special cases.
7228 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7229 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7230 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7231 Ops[2].getValueType() == VT && "FMA types must match!");
7235 if (C1 && C2 && C3) {
7236 APFloat V1 = C1->getValueAPF();
7237 const APFloat &V2 = C2->getValueAPF();
7238 const APFloat &V3 = C3->getValueAPF();
7239 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7242 } else
7244 return getConstantFP(V1, DL, VT);
7245 }
7246 }
7247
7248 // This is for vector folding only from here on.
7249 if (!VT.isVector())
7250 return SDValue();
7251
7252 ElementCount NumElts = VT.getVectorElementCount();
7253
7254 // See if we can fold through any bitcasted integer ops.
7255 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
7256 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7257 (Ops[0].getOpcode() == ISD::BITCAST ||
7258 Ops[1].getOpcode() == ISD::BITCAST)) {
7261 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7262 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
7263 if (BV1 && BV2 && N1.getValueType().isInteger() &&
7264 N2.getValueType().isInteger()) {
7265 bool IsLE = getDataLayout().isLittleEndian();
7266 unsigned EltBits = VT.getScalarSizeInBits();
7267 SmallVector<APInt> RawBits1, RawBits2;
7268 BitVector UndefElts1, UndefElts2;
7269 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
7270 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
7271 SmallVector<APInt> RawBits;
7272 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
7273 std::optional<APInt> Fold = FoldValueWithUndef(
7274 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
7275 if (!Fold)
7276 break;
7277 RawBits.push_back(*Fold);
7278 }
7279 if (RawBits.size() == NumElts.getFixedValue()) {
7280 // We have constant folded, but we might need to cast this again back
7281 // to the original (possibly legalized) type.
7282 EVT BVVT, BVEltVT;
7283 if (N1.getValueType() == VT) {
7284 BVVT = N1.getValueType();
7285 BVEltVT = BV1->getOperand(0).getValueType();
7286 } else {
7287 BVVT = N2.getValueType();
7288 BVEltVT = BV2->getOperand(0).getValueType();
7289 }
7290 unsigned BVEltBits = BVEltVT.getSizeInBits();
7291 SmallVector<APInt> DstBits;
7292 BitVector DstUndefs;
7294 DstBits, RawBits, DstUndefs,
7295 BitVector(RawBits.size(), false));
7296 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
7297 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
7298 if (DstUndefs[I])
7299 continue;
7300 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
7301 }
7302 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
7303 }
7304 }
7305 }
7306 }
7307
7308 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
7309 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
7310 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
7311 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
7312 APInt RHSVal;
7313 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
7314 APInt NewStep = Opcode == ISD::MUL
7315 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
7316 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
7317 return getStepVector(DL, VT, NewStep);
7318 }
7319 }
7320
7321 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
7322 return !Op.getValueType().isVector() ||
7323 Op.getValueType().getVectorElementCount() == NumElts;
7324 };
7325
7326 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
7327 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
7328 Op.getOpcode() == ISD::BUILD_VECTOR ||
7329 Op.getOpcode() == ISD::SPLAT_VECTOR;
7330 };
7331
7332 // All operands must be vector types with the same number of elements as
7333 // the result type and must be either UNDEF or a build/splat vector
7334 // or UNDEF scalars.
7335 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
7336 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
7337 return SDValue();
7338
7339 // If we are comparing vectors, then the result needs to be a i1 boolean that
7340 // is then extended back to the legal result type depending on how booleans
7341 // are represented.
7342 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
7343 ISD::NodeType ExtendCode =
7344 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
7345 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
7347
7348 // Find legal integer scalar type for constant promotion and
7349 // ensure that its scalar size is at least as large as source.
7350 EVT LegalSVT = VT.getScalarType();
7351 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
7352 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
7353 if (LegalSVT.bitsLT(VT.getScalarType()))
7354 return SDValue();
7355 }
7356
7357 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
7358 // only have one operand to check. For fixed-length vector types we may have
7359 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
7360 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
7361
7362 // Constant fold each scalar lane separately.
7363 SmallVector<SDValue, 4> ScalarResults;
7364 for (unsigned I = 0; I != NumVectorElts; I++) {
7365 SmallVector<SDValue, 4> ScalarOps;
7366 for (SDValue Op : Ops) {
7367 EVT InSVT = Op.getValueType().getScalarType();
7368 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
7369 Op.getOpcode() != ISD::SPLAT_VECTOR) {
7370 if (Op.isUndef())
7371 ScalarOps.push_back(getUNDEF(InSVT));
7372 else
7373 ScalarOps.push_back(Op);
7374 continue;
7375 }
7376
7377 SDValue ScalarOp =
7378 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
7379 EVT ScalarVT = ScalarOp.getValueType();
7380
7381 // Build vector (integer) scalar operands may need implicit
7382 // truncation - do this before constant folding.
7383 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
7384 // Don't create illegally-typed nodes unless they're constants or undef
7385 // - if we fail to constant fold we can't guarantee the (dead) nodes
7386 // we're creating will be cleaned up before being visited for
7387 // legalization.
7388 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
7389 !isa<ConstantSDNode>(ScalarOp) &&
7390 TLI->getTypeAction(*getContext(), InSVT) !=
7392 return SDValue();
7393 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
7394 }
7395
7396 ScalarOps.push_back(ScalarOp);
7397 }
7398
7399 // Constant fold the scalar operands.
7400 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
7401
7402 // Scalar folding only succeeded if the result is a constant or UNDEF.
7403 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
7404 ScalarResult.getOpcode() != ISD::ConstantFP)
7405 return SDValue();
7406
7407 // Legalize the (integer) scalar constant if necessary. We only do
7408 // this once we know the folding succeeded, since otherwise we would
7409 // get a node with illegal type which has a user.
7410 if (LegalSVT != SVT)
7411 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
7412
7413 ScalarResults.push_back(ScalarResult);
7414 }
7415
7416 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
7417 : getBuildVector(VT, DL, ScalarResults);
7418 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
7419 return V;
7420}
7421
7424 // TODO: Add support for unary/ternary fp opcodes.
7425 if (Ops.size() != 2)
7426 return SDValue();
7427
7428 // TODO: We don't do any constant folding for strict FP opcodes here, but we
7429 // should. That will require dealing with a potentially non-default
7430 // rounding mode, checking the "opStatus" return value from the APFloat
7431 // math calculations, and possibly other variations.
7432 SDValue N1 = Ops[0];
7433 SDValue N2 = Ops[1];
7434 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
7435 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
7436 if (N1CFP && N2CFP) {
7437 APFloat C1 = N1CFP->getValueAPF(); // make copy
7438 const APFloat &C2 = N2CFP->getValueAPF();
7439 switch (Opcode) {
7440 case ISD::FADD:
7442 return getConstantFP(C1, DL, VT);
7443 case ISD::FSUB:
7445 return getConstantFP(C1, DL, VT);
7446 case ISD::FMUL:
7448 return getConstantFP(C1, DL, VT);
7449 case ISD::FDIV:
7451 return getConstantFP(C1, DL, VT);
7452 case ISD::FREM:
7453 C1.mod(C2);
7454 return getConstantFP(C1, DL, VT);
7455 case ISD::FCOPYSIGN:
7456 C1.copySign(C2);
7457 return getConstantFP(C1, DL, VT);
7458 case ISD::FMINNUM:
7459 if (C1.isSignaling() || C2.isSignaling())
7460 return SDValue();
7461 return getConstantFP(minnum(C1, C2), DL, VT);
7462 case ISD::FMAXNUM:
7463 if (C1.isSignaling() || C2.isSignaling())
7464 return SDValue();
7465 return getConstantFP(maxnum(C1, C2), DL, VT);
7466 case ISD::FMINIMUM:
7467 return getConstantFP(minimum(C1, C2), DL, VT);
7468 case ISD::FMAXIMUM:
7469 return getConstantFP(maximum(C1, C2), DL, VT);
7470 case ISD::FMINIMUMNUM:
7471 return getConstantFP(minimumnum(C1, C2), DL, VT);
7472 case ISD::FMAXIMUMNUM:
7473 return getConstantFP(maximumnum(C1, C2), DL, VT);
7474 default: break;
7475 }
7476 }
7477 if (N1CFP && Opcode == ISD::FP_ROUND) {
7478 APFloat C1 = N1CFP->getValueAPF(); // make copy
7479 bool Unused;
7480 // This can return overflow, underflow, or inexact; we don't care.
7481 // FIXME need to be more flexible about rounding mode.
7483 &Unused);
7484 return getConstantFP(C1, DL, VT);
7485 }
7486
7487 switch (Opcode) {
7488 case ISD::FSUB:
7489 // -0.0 - undef --> undef (consistent with "fneg undef")
7490 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
7491 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
7492 return getUNDEF(VT);
7493 [[fallthrough]];
7494
7495 case ISD::FADD:
7496 case ISD::FMUL:
7497 case ISD::FDIV:
7498 case ISD::FREM:
7499 // If both operands are undef, the result is undef. If 1 operand is undef,
7500 // the result is NaN. This should match the behavior of the IR optimizer.
7501 if (N1.isUndef() && N2.isUndef())
7502 return getUNDEF(VT);
7503 if (N1.isUndef() || N2.isUndef())
7505 }
7506 return SDValue();
7507}
7508
7510 const SDLoc &DL, EVT DstEltVT) {
7511 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7512
7513 // If this is already the right type, we're done.
7514 if (SrcEltVT == DstEltVT)
7515 return SDValue(BV, 0);
7516
7517 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7518 unsigned DstBitSize = DstEltVT.getSizeInBits();
7519
7520 // If this is a conversion of N elements of one type to N elements of another
7521 // type, convert each element. This handles FP<->INT cases.
7522 if (SrcBitSize == DstBitSize) {
7524 for (SDValue Op : BV->op_values()) {
7525 // If the vector element type is not legal, the BUILD_VECTOR operands
7526 // are promoted and implicitly truncated. Make that explicit here.
7527 if (Op.getValueType() != SrcEltVT)
7528 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
7529 Ops.push_back(getBitcast(DstEltVT, Op));
7530 }
7531 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
7533 return getBuildVector(VT, DL, Ops);
7534 }
7535
7536 // Otherwise, we're growing or shrinking the elements. To avoid having to
7537 // handle annoying details of growing/shrinking FP values, we convert them to
7538 // int first.
7539 if (SrcEltVT.isFloatingPoint()) {
7540 // Convert the input float vector to a int vector where the elements are the
7541 // same sizes.
7542 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
7543 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
7545 DstEltVT);
7546 return SDValue();
7547 }
7548
7549 // Now we know the input is an integer vector. If the output is a FP type,
7550 // convert to integer first, then to FP of the right size.
7551 if (DstEltVT.isFloatingPoint()) {
7552 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
7553 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
7555 DstEltVT);
7556 return SDValue();
7557 }
7558
7559 // Okay, we know the src/dst types are both integers of differing types.
7560 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7561
7562 // Extract the constant raw bit data.
7563 BitVector UndefElements;
7564 SmallVector<APInt> RawBits;
7565 bool IsLE = getDataLayout().isLittleEndian();
7566 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
7567 return SDValue();
7568
7570 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
7571 if (UndefElements[I])
7572 Ops.push_back(getUNDEF(DstEltVT));
7573 else
7574 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
7575 }
7576
7577 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
7578 return getBuildVector(VT, DL, Ops);
7579}
7580
7582 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
7583
7584 // There's no need to assert on a byte-aligned pointer. All pointers are at
7585 // least byte aligned.
7586 if (A == Align(1))
7587 return Val;
7588
7589 SDVTList VTs = getVTList(Val.getValueType());
7591 AddNodeIDNode(ID, ISD::AssertAlign, VTs, {Val});
7592 ID.AddInteger(A.value());
7593
7594 void *IP = nullptr;
7595 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7596 return SDValue(E, 0);
7597
7598 auto *N =
7599 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
7600 createOperands(N, {Val});
7601
7602 CSEMap.InsertNode(N, IP);
7603 InsertNode(N);
7604
7605 SDValue V(N, 0);
7606 NewSDValueDbgMsg(V, "Creating new node: ", this);
7607 return V;
7608}
7609
7610SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7611 SDValue N1, SDValue N2) {
7612 SDNodeFlags Flags;
7613 if (Inserter)
7614 Flags = Inserter->getFlags();
7615 return getNode(Opcode, DL, VT, N1, N2, Flags);
7616}
7617
7619 SDValue &N2) const {
7620 if (!TLI->isCommutativeBinOp(Opcode))
7621 return;
7622
7623 // Canonicalize:
7624 // binop(const, nonconst) -> binop(nonconst, const)
7627 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
7628 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
7629 if ((N1C && !N2C) || (N1CFP && !N2CFP))
7630 std::swap(N1, N2);
7631
7632 // Canonicalize:
7633 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
7634 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
7636 std::swap(N1, N2);
7637}
7638
7639SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7640 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
7642 N2.getOpcode() != ISD::DELETED_NODE &&
7643 "Operand is DELETED_NODE!");
7644
7645 canonicalizeCommutativeBinop(Opcode, N1, N2);
7646
7647 auto *N1C = dyn_cast<ConstantSDNode>(N1);
7648 auto *N2C = dyn_cast<ConstantSDNode>(N2);
7649
7650 // Don't allow undefs in vector splats - we might be returning N2 when folding
7651 // to zero etc.
7652 ConstantSDNode *N2CV =
7653 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
7654
7655 switch (Opcode) {
7656 default: break;
7657 case ISD::TokenFactor:
7658 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
7659 N2.getValueType() == MVT::Other && "Invalid token factor!");
7660 // Fold trivial token factors.
7661 if (N1.getOpcode() == ISD::EntryToken) return N2;
7662 if (N2.getOpcode() == ISD::EntryToken) return N1;
7663 if (N1 == N2) return N1;
7664 break;
7665 case ISD::BUILD_VECTOR: {
7666 // Attempt to simplify BUILD_VECTOR.
7667 SDValue Ops[] = {N1, N2};
7668 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7669 return V;
7670 break;
7671 }
7672 case ISD::CONCAT_VECTORS: {
7673 SDValue Ops[] = {N1, N2};
7674 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7675 return V;
7676 break;
7677 }
7678 case ISD::AND:
7679 assert(VT.isInteger() && "This operator does not apply to FP types!");
7680 assert(N1.getValueType() == N2.getValueType() &&
7681 N1.getValueType() == VT && "Binary operator types must match!");
7682 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
7683 // worth handling here.
7684 if (N2CV && N2CV->isZero())
7685 return N2;
7686 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
7687 return N1;
7688 break;
7689 case ISD::OR:
7690 case ISD::XOR:
7691 case ISD::ADD:
7692 case ISD::PTRADD:
7693 case ISD::SUB:
7694 assert(VT.isInteger() && "This operator does not apply to FP types!");
7695 assert(N1.getValueType() == N2.getValueType() &&
7696 N1.getValueType() == VT && "Binary operator types must match!");
7697 // The equal operand types requirement is unnecessarily strong for PTRADD.
7698 // However, the SelectionDAGBuilder does not generate PTRADDs with different
7699 // operand types, and we'd need to re-implement GEP's non-standard wrapping
7700 // logic everywhere where PTRADDs may be folded or combined to properly
7701 // support them. If/when we introduce pointer types to the SDAG, we will
7702 // need to relax this constraint.
7703
7704 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
7705 // it's worth handling here.
7706 if (N2CV && N2CV->isZero())
7707 return N1;
7708 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
7709 VT.getScalarType() == MVT::i1)
7710 return getNode(ISD::XOR, DL, VT, N1, N2);
7711 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
7712 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
7713 N2.getOpcode() == ISD::VSCALE) {
7714 const APInt &C1 = N1->getConstantOperandAPInt(0);
7715 const APInt &C2 = N2->getConstantOperandAPInt(0);
7716 return getVScale(DL, VT, C1 + C2);
7717 }
7718 break;
7719 case ISD::MUL:
7720 assert(VT.isInteger() && "This operator does not apply to FP types!");
7721 assert(N1.getValueType() == N2.getValueType() &&
7722 N1.getValueType() == VT && "Binary operator types must match!");
7723 if (VT.getScalarType() == MVT::i1)
7724 return getNode(ISD::AND, DL, VT, N1, N2);
7725 if (N2CV && N2CV->isZero())
7726 return N2;
7727 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
7728 const APInt &MulImm = N1->getConstantOperandAPInt(0);
7729 const APInt &N2CImm = N2C->getAPIntValue();
7730 return getVScale(DL, VT, MulImm * N2CImm);
7731 }
7732 break;
7733 case ISD::UDIV:
7734 case ISD::UREM:
7735 case ISD::MULHU:
7736 case ISD::MULHS:
7737 case ISD::SDIV:
7738 case ISD::SREM:
7739 case ISD::SADDSAT:
7740 case ISD::SSUBSAT:
7741 case ISD::UADDSAT:
7742 case ISD::USUBSAT:
7743 assert(VT.isInteger() && "This operator does not apply to FP types!");
7744 assert(N1.getValueType() == N2.getValueType() &&
7745 N1.getValueType() == VT && "Binary operator types must match!");
7746 if (VT.getScalarType() == MVT::i1) {
7747 // fold (add_sat x, y) -> (or x, y) for bool types.
7748 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
7749 return getNode(ISD::OR, DL, VT, N1, N2);
7750 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
7751 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
7752 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
7753 }
7754 break;
7755 case ISD::SCMP:
7756 case ISD::UCMP:
7757 assert(N1.getValueType() == N2.getValueType() &&
7758 "Types of operands of UCMP/SCMP must match");
7759 assert(N1.getValueType().isVector() == VT.isVector() &&
7760 "Operands and return type of must both be scalars or vectors");
7761 if (VT.isVector())
7764 "Result and operands must have the same number of elements");
7765 break;
7766 case ISD::AVGFLOORS:
7767 case ISD::AVGFLOORU:
7768 case ISD::AVGCEILS:
7769 case ISD::AVGCEILU:
7770 assert(VT.isInteger() && "This operator does not apply to FP types!");
7771 assert(N1.getValueType() == N2.getValueType() &&
7772 N1.getValueType() == VT && "Binary operator types must match!");
7773 break;
7774 case ISD::ABDS:
7775 case ISD::ABDU:
7776 assert(VT.isInteger() && "This operator does not apply to FP types!");
7777 assert(N1.getValueType() == N2.getValueType() &&
7778 N1.getValueType() == VT && "Binary operator types must match!");
7779 if (VT.getScalarType() == MVT::i1)
7780 return getNode(ISD::XOR, DL, VT, N1, N2);
7781 break;
7782 case ISD::SMIN:
7783 case ISD::UMAX:
7784 assert(VT.isInteger() && "This operator does not apply to FP types!");
7785 assert(N1.getValueType() == N2.getValueType() &&
7786 N1.getValueType() == VT && "Binary operator types must match!");
7787 if (VT.getScalarType() == MVT::i1)
7788 return getNode(ISD::OR, DL, VT, N1, N2);
7789 break;
7790 case ISD::SMAX:
7791 case ISD::UMIN:
7792 assert(VT.isInteger() && "This operator does not apply to FP types!");
7793 assert(N1.getValueType() == N2.getValueType() &&
7794 N1.getValueType() == VT && "Binary operator types must match!");
7795 if (VT.getScalarType() == MVT::i1)
7796 return getNode(ISD::AND, DL, VT, N1, N2);
7797 break;
7798 case ISD::FADD:
7799 case ISD::FSUB:
7800 case ISD::FMUL:
7801 case ISD::FDIV:
7802 case ISD::FREM:
7803 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7804 assert(N1.getValueType() == N2.getValueType() &&
7805 N1.getValueType() == VT && "Binary operator types must match!");
7806 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
7807 return V;
7808 break;
7809 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
7810 assert(N1.getValueType() == VT &&
7813 "Invalid FCOPYSIGN!");
7814 break;
7815 case ISD::SHL:
7816 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
7817 const APInt &MulImm = N1->getConstantOperandAPInt(0);
7818 const APInt &ShiftImm = N2C->getAPIntValue();
7819 return getVScale(DL, VT, MulImm << ShiftImm);
7820 }
7821 [[fallthrough]];
7822 case ISD::SRA:
7823 case ISD::SRL:
7824 if (SDValue V = simplifyShift(N1, N2))
7825 return V;
7826 [[fallthrough]];
7827 case ISD::ROTL:
7828 case ISD::ROTR:
7829 case ISD::SSHLSAT:
7830 case ISD::USHLSAT:
7831 assert(VT == N1.getValueType() &&
7832 "Shift operators return type must be the same as their first arg");
7833 assert(VT.isInteger() && N2.getValueType().isInteger() &&
7834 "Shifts only work on integers");
7835 assert((!VT.isVector() || VT == N2.getValueType()) &&
7836 "Vector shift amounts must be in the same as their first arg");
7837 // Verify that the shift amount VT is big enough to hold valid shift
7838 // amounts. This catches things like trying to shift an i1024 value by an
7839 // i8, which is easy to fall into in generic code that uses
7840 // TLI.getShiftAmount().
7843 "Invalid use of small shift amount with oversized value!");
7844
7845 // Always fold shifts of i1 values so the code generator doesn't need to
7846 // handle them. Since we know the size of the shift has to be less than the
7847 // size of the value, the shift/rotate count is guaranteed to be zero.
7848 if (VT == MVT::i1)
7849 return N1;
7850 if (N2CV && N2CV->isZero())
7851 return N1;
7852 break;
7853 case ISD::FP_ROUND:
7855 VT.bitsLE(N1.getValueType()) && N2C &&
7856 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
7857 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
7858 if (N1.getValueType() == VT) return N1; // noop conversion.
7859 break;
7860 case ISD::AssertNoFPClass: {
7862 "AssertNoFPClass is used for a non-floating type");
7863 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
7864 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
7865 assert(llvm::to_underlying(NoFPClass) <=
7867 "FPClassTest value too large");
7868 (void)NoFPClass;
7869 break;
7870 }
7871 case ISD::AssertSext:
7872 case ISD::AssertZext: {
7873 EVT EVT = cast<VTSDNode>(N2)->getVT();
7874 assert(VT == N1.getValueType() && "Not an inreg extend!");
7875 assert(VT.isInteger() && EVT.isInteger() &&
7876 "Cannot *_EXTEND_INREG FP types");
7877 assert(!EVT.isVector() &&
7878 "AssertSExt/AssertZExt type should be the vector element type "
7879 "rather than the vector type!");
7880 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
7881 if (VT.getScalarType() == EVT) return N1; // noop assertion.
7882 break;
7883 }
7885 EVT EVT = cast<VTSDNode>(N2)->getVT();
7886 assert(VT == N1.getValueType() && "Not an inreg extend!");
7887 assert(VT.isInteger() && EVT.isInteger() &&
7888 "Cannot *_EXTEND_INREG FP types");
7889 assert(EVT.isVector() == VT.isVector() &&
7890 "SIGN_EXTEND_INREG type should be vector iff the operand "
7891 "type is vector!");
7892 assert((!EVT.isVector() ||
7894 "Vector element counts must match in SIGN_EXTEND_INREG");
7895 assert(EVT.bitsLE(VT) && "Not extending!");
7896 if (EVT == VT) return N1; // Not actually extending
7897 break;
7898 }
7900 case ISD::FP_TO_UINT_SAT: {
7901 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
7902 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
7903 assert(N1.getValueType().isVector() == VT.isVector() &&
7904 "FP_TO_*INT_SAT type should be vector iff the operand type is "
7905 "vector!");
7906 assert((!VT.isVector() || VT.getVectorElementCount() ==
7908 "Vector element counts must match in FP_TO_*INT_SAT");
7909 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
7910 "Type to saturate to must be a scalar.");
7911 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
7912 "Not extending!");
7913 break;
7914 }
7917 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
7918 element type of the vector.");
7919
7920 // Extract from an undefined value or using an undefined index is undefined.
7921 if (N1.isUndef() || N2.isUndef())
7922 return getUNDEF(VT);
7923
7924 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
7925 // vectors. For scalable vectors we will provide appropriate support for
7926 // dealing with arbitrary indices.
7927 if (N2C && N1.getValueType().isFixedLengthVector() &&
7928 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
7929 return getUNDEF(VT);
7930
7931 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
7932 // expanding copies of large vectors from registers. This only works for
7933 // fixed length vectors, since we need to know the exact number of
7934 // elements.
7935 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
7937 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
7938 return getExtractVectorElt(DL, VT,
7939 N1.getOperand(N2C->getZExtValue() / Factor),
7940 N2C->getZExtValue() % Factor);
7941 }
7942
7943 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
7944 // lowering is expanding large vector constants.
7945 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
7946 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
7949 "BUILD_VECTOR used for scalable vectors");
7950 unsigned Index =
7951 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
7952 SDValue Elt = N1.getOperand(Index);
7953
7954 if (VT != Elt.getValueType())
7955 // If the vector element type is not legal, the BUILD_VECTOR operands
7956 // are promoted and implicitly truncated, and the result implicitly
7957 // extended. Make that explicit here.
7958 Elt = getAnyExtOrTrunc(Elt, DL, VT);
7959
7960 return Elt;
7961 }
7962
7963 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
7964 // operations are lowered to scalars.
7965 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
7966 // If the indices are the same, return the inserted element else
7967 // if the indices are known different, extract the element from
7968 // the original vector.
7969 SDValue N1Op2 = N1.getOperand(2);
7971
7972 if (N1Op2C && N2C) {
7973 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
7974 if (VT == N1.getOperand(1).getValueType())
7975 return N1.getOperand(1);
7976 if (VT.isFloatingPoint()) {
7978 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
7979 }
7980 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
7981 }
7982 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
7983 }
7984 }
7985
7986 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
7987 // when vector types are scalarized and v1iX is legal.
7988 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
7989 // Here we are completely ignoring the extract element index (N2),
7990 // which is fine for fixed width vectors, since any index other than 0
7991 // is undefined anyway. However, this cannot be ignored for scalable
7992 // vectors - in theory we could support this, but we don't want to do this
7993 // without a profitability check.
7994 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
7996 N1.getValueType().getVectorNumElements() == 1) {
7997 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
7998 N1.getOperand(1));
7999 }
8000 break;
8002 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8003 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8004 (N1.getValueType().isInteger() == VT.isInteger()) &&
8005 N1.getValueType() != VT &&
8006 "Wrong types for EXTRACT_ELEMENT!");
8007
8008 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8009 // 64-bit integers into 32-bit parts. Instead of building the extract of
8010 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8011 if (N1.getOpcode() == ISD::BUILD_PAIR)
8012 return N1.getOperand(N2C->getZExtValue());
8013
8014 // EXTRACT_ELEMENT of a constant int is also very common.
8015 if (N1C) {
8016 unsigned ElementSize = VT.getSizeInBits();
8017 unsigned Shift = ElementSize * N2C->getZExtValue();
8018 const APInt &Val = N1C->getAPIntValue();
8019 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8020 }
8021 break;
8023 EVT N1VT = N1.getValueType();
8024 assert(VT.isVector() && N1VT.isVector() &&
8025 "Extract subvector VTs must be vectors!");
8027 "Extract subvector VTs must have the same element type!");
8028 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8029 "Cannot extract a scalable vector from a fixed length vector!");
8030 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8032 "Extract subvector must be from larger vector to smaller vector!");
8033 assert(N2C && "Extract subvector index must be a constant");
8034 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8035 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8036 N1VT.getVectorMinNumElements()) &&
8037 "Extract subvector overflow!");
8038 assert(N2C->getAPIntValue().getBitWidth() ==
8039 TLI->getVectorIdxWidth(getDataLayout()) &&
8040 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8041 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8042 "Extract index is not a multiple of the output vector length");
8043
8044 // Trivial extraction.
8045 if (VT == N1VT)
8046 return N1;
8047
8048 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8049 if (N1.isUndef())
8050 return getUNDEF(VT);
8051
8052 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8053 // the concat have the same type as the extract.
8054 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8055 VT == N1.getOperand(0).getValueType()) {
8056 unsigned Factor = VT.getVectorMinNumElements();
8057 return N1.getOperand(N2C->getZExtValue() / Factor);
8058 }
8059
8060 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8061 // during shuffle legalization.
8062 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8063 VT == N1.getOperand(1).getValueType())
8064 return N1.getOperand(1);
8065 break;
8066 }
8067 }
8068
8069 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8070 switch (Opcode) {
8071 case ISD::XOR:
8072 case ISD::ADD:
8073 case ISD::PTRADD:
8074 case ISD::SUB:
8076 case ISD::UDIV:
8077 case ISD::SDIV:
8078 case ISD::UREM:
8079 case ISD::SREM:
8080 case ISD::MUL:
8081 case ISD::AND:
8082 case ISD::SSUBSAT:
8083 case ISD::USUBSAT:
8084 case ISD::UMIN:
8085 case ISD::OR:
8086 case ISD::SADDSAT:
8087 case ISD::UADDSAT:
8088 case ISD::UMAX:
8089 case ISD::SMAX:
8090 case ISD::SMIN:
8091 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8092 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8093 }
8094 }
8095
8096 // Canonicalize an UNDEF to the RHS, even over a constant.
8097 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8098 if (TLI->isCommutativeBinOp(Opcode)) {
8099 std::swap(N1, N2);
8100 } else {
8101 switch (Opcode) {
8102 case ISD::PTRADD:
8103 case ISD::SUB:
8104 // fold op(undef, non_undef_arg2) -> undef.
8105 return N1;
8107 case ISD::UDIV:
8108 case ISD::SDIV:
8109 case ISD::UREM:
8110 case ISD::SREM:
8111 case ISD::SSUBSAT:
8112 case ISD::USUBSAT:
8113 // fold op(undef, non_undef_arg2) -> 0.
8114 return getConstant(0, DL, VT);
8115 }
8116 }
8117 }
8118
8119 // Fold a bunch of operators when the RHS is undef.
8120 if (N2.getOpcode() == ISD::UNDEF) {
8121 switch (Opcode) {
8122 case ISD::XOR:
8123 if (N1.getOpcode() == ISD::UNDEF)
8124 // Handle undef ^ undef -> 0 special case. This is a common
8125 // idiom (misuse).
8126 return getConstant(0, DL, VT);
8127 [[fallthrough]];
8128 case ISD::ADD:
8129 case ISD::PTRADD:
8130 case ISD::SUB:
8131 // fold op(arg1, undef) -> undef.
8132 return N2;
8133 case ISD::UDIV:
8134 case ISD::SDIV:
8135 case ISD::UREM:
8136 case ISD::SREM:
8137 // fold op(arg1, undef) -> poison.
8138 return getPOISON(VT);
8139 case ISD::MUL:
8140 case ISD::AND:
8141 case ISD::SSUBSAT:
8142 case ISD::USUBSAT:
8143 case ISD::UMIN:
8144 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8145 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8146 case ISD::OR:
8147 case ISD::SADDSAT:
8148 case ISD::UADDSAT:
8149 case ISD::UMAX:
8150 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8151 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8152 case ISD::SMAX:
8153 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8154 return N1.getOpcode() == ISD::UNDEF
8155 ? N2
8156 : getConstant(
8158 VT);
8159 case ISD::SMIN:
8160 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8161 return N1.getOpcode() == ISD::UNDEF
8162 ? N2
8163 : getConstant(
8165 VT);
8166 }
8167 }
8168
8169 // Perform trivial constant folding.
8170 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
8171 return SV;
8172
8173 // Memoize this node if possible.
8174 SDNode *N;
8175 SDVTList VTs = getVTList(VT);
8176 SDValue Ops[] = {N1, N2};
8177 if (VT != MVT::Glue) {
8179 AddNodeIDNode(ID, Opcode, VTs, Ops);
8180 void *IP = nullptr;
8181 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8182 E->intersectFlagsWith(Flags);
8183 return SDValue(E, 0);
8184 }
8185
8186 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8187 N->setFlags(Flags);
8188 createOperands(N, Ops);
8189 CSEMap.InsertNode(N, IP);
8190 } else {
8191 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8192 createOperands(N, Ops);
8193 }
8194
8195 InsertNode(N);
8196 SDValue V = SDValue(N, 0);
8197 NewSDValueDbgMsg(V, "Creating new node: ", this);
8198 return V;
8199}
8200
8201SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8202 SDValue N1, SDValue N2, SDValue N3) {
8203 SDNodeFlags Flags;
8204 if (Inserter)
8205 Flags = Inserter->getFlags();
8206 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
8207}
8208
8209SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8210 SDValue N1, SDValue N2, SDValue N3,
8211 const SDNodeFlags Flags) {
8213 N2.getOpcode() != ISD::DELETED_NODE &&
8214 N3.getOpcode() != ISD::DELETED_NODE &&
8215 "Operand is DELETED_NODE!");
8216 // Perform various simplifications.
8217 switch (Opcode) {
8218 case ISD::BUILD_VECTOR: {
8219 // Attempt to simplify BUILD_VECTOR.
8220 SDValue Ops[] = {N1, N2, N3};
8221 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8222 return V;
8223 break;
8224 }
8225 case ISD::CONCAT_VECTORS: {
8226 SDValue Ops[] = {N1, N2, N3};
8227 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8228 return V;
8229 break;
8230 }
8231 case ISD::SETCC: {
8232 assert(VT.isInteger() && "SETCC result type must be an integer!");
8233 assert(N1.getValueType() == N2.getValueType() &&
8234 "SETCC operands must have the same type!");
8235 assert(VT.isVector() == N1.getValueType().isVector() &&
8236 "SETCC type should be vector iff the operand type is vector!");
8237 assert((!VT.isVector() || VT.getVectorElementCount() ==
8239 "SETCC vector element counts must match!");
8240 // Use FoldSetCC to simplify SETCC's.
8241 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
8242 return V;
8243 break;
8244 }
8245 case ISD::SELECT:
8246 case ISD::VSELECT:
8247 if (SDValue V = simplifySelect(N1, N2, N3))
8248 return V;
8249 break;
8251 llvm_unreachable("should use getVectorShuffle constructor!");
8252 case ISD::VECTOR_SPLICE: {
8253 if (cast<ConstantSDNode>(N3)->isZero())
8254 return N1;
8255 break;
8256 }
8258 assert(VT.isVector() && VT == N1.getValueType() &&
8259 "INSERT_VECTOR_ELT vector type mismatch");
8261 "INSERT_VECTOR_ELT scalar fp/int mismatch");
8262 assert((!VT.isFloatingPoint() ||
8263 VT.getVectorElementType() == N2.getValueType()) &&
8264 "INSERT_VECTOR_ELT fp scalar type mismatch");
8265 assert((!VT.isInteger() ||
8267 "INSERT_VECTOR_ELT int scalar size mismatch");
8268
8269 auto *N3C = dyn_cast<ConstantSDNode>(N3);
8270 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
8271 // for scalable vectors where we will generate appropriate code to
8272 // deal with out-of-bounds cases correctly.
8273 if (N3C && VT.isFixedLengthVector() &&
8274 N3C->getZExtValue() >= VT.getVectorNumElements())
8275 return getUNDEF(VT);
8276
8277 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
8278 if (N3.isUndef())
8279 return getUNDEF(VT);
8280
8281 // If inserting poison, just use the input vector.
8282 if (N2.getOpcode() == ISD::POISON)
8283 return N1;
8284
8285 // Inserting undef into undef/poison is still undef.
8286 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
8287 return getUNDEF(VT);
8288
8289 // If the inserted element is an UNDEF, just use the input vector.
8290 // But not if skipping the insert could make the result more poisonous.
8291 if (N2.isUndef()) {
8292 if (N3C && VT.isFixedLengthVector()) {
8293 APInt EltMask =
8294 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
8295 if (isGuaranteedNotToBePoison(N1, EltMask))
8296 return N1;
8297 } else if (isGuaranteedNotToBePoison(N1))
8298 return N1;
8299 }
8300 break;
8301 }
8302 case ISD::INSERT_SUBVECTOR: {
8303 // If inserting poison, just use the input vector,
8304 if (N2.getOpcode() == ISD::POISON)
8305 return N1;
8306
8307 // Inserting undef into undef/poison is still undef.
8308 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
8309 return getUNDEF(VT);
8310
8311 EVT N2VT = N2.getValueType();
8312 assert(VT == N1.getValueType() &&
8313 "Dest and insert subvector source types must match!");
8314 assert(VT.isVector() && N2VT.isVector() &&
8315 "Insert subvector VTs must be vectors!");
8317 "Insert subvector VTs must have the same element type!");
8318 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
8319 "Cannot insert a scalable vector into a fixed length vector!");
8320 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
8322 "Insert subvector must be from smaller vector to larger vector!");
8324 "Insert subvector index must be constant");
8325 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
8326 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
8328 "Insert subvector overflow!");
8330 TLI->getVectorIdxWidth(getDataLayout()) &&
8331 "Constant index for INSERT_SUBVECTOR has an invalid size");
8332
8333 // Trivial insertion.
8334 if (VT == N2VT)
8335 return N2;
8336
8337 // If this is an insert of an extracted vector into an undef/poison vector,
8338 // we can just use the input to the extract. But not if skipping the
8339 // extract+insert could make the result more poisonous.
8340 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8341 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
8342 if (N1.getOpcode() == ISD::POISON)
8343 return N2.getOperand(0);
8344 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
8345 unsigned LoBit = N3->getAsZExtVal();
8346 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
8347 APInt EltMask =
8348 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
8349 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
8350 return N2.getOperand(0);
8351 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
8352 return N2.getOperand(0);
8353 }
8354
8355 // If the inserted subvector is UNDEF, just use the input vector.
8356 // But not if skipping the insert could make the result more poisonous.
8357 if (N2.isUndef()) {
8358 if (VT.isFixedLengthVector()) {
8359 unsigned LoBit = N3->getAsZExtVal();
8360 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
8361 APInt EltMask =
8362 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
8363 if (isGuaranteedNotToBePoison(N1, EltMask))
8364 return N1;
8365 } else if (isGuaranteedNotToBePoison(N1))
8366 return N1;
8367 }
8368 break;
8369 }
8370 case ISD::BITCAST:
8371 // Fold bit_convert nodes from a type to themselves.
8372 if (N1.getValueType() == VT)
8373 return N1;
8374 break;
8375 case ISD::VP_TRUNCATE:
8376 case ISD::VP_SIGN_EXTEND:
8377 case ISD::VP_ZERO_EXTEND:
8378 // Don't create noop casts.
8379 if (N1.getValueType() == VT)
8380 return N1;
8381 break;
8382 case ISD::VECTOR_COMPRESS: {
8383 [[maybe_unused]] EVT VecVT = N1.getValueType();
8384 [[maybe_unused]] EVT MaskVT = N2.getValueType();
8385 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
8386 assert(VT == VecVT && "Vector and result type don't match.");
8387 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
8388 "All inputs must be vectors.");
8389 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
8391 "Vector and mask must have same number of elements.");
8392
8393 if (N1.isUndef() || N2.isUndef())
8394 return N3;
8395
8396 break;
8397 }
8402 [[maybe_unused]] EVT AccVT = N1.getValueType();
8403 [[maybe_unused]] EVT Input1VT = N2.getValueType();
8404 [[maybe_unused]] EVT Input2VT = N3.getValueType();
8405 assert(Input1VT.isVector() && Input1VT == Input2VT &&
8406 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
8407 "node to have the same type!");
8408 assert(VT.isVector() && VT == AccVT &&
8409 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
8410 "the same type as its result!");
8412 AccVT.getVectorElementCount()) &&
8413 "Expected the element count of the second and third operands of the "
8414 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
8415 "element count of the first operand and the result!");
8417 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
8418 "node to have an element type which is the same as or smaller than "
8419 "the element type of the first operand and result!");
8420 break;
8421 }
8422 }
8423
8424 // Perform trivial constant folding for arithmetic operators.
8425 switch (Opcode) {
8426 case ISD::FMA:
8427 case ISD::FMAD:
8428 case ISD::SETCC:
8429 case ISD::FSHL:
8430 case ISD::FSHR:
8431 if (SDValue SV =
8432 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
8433 return SV;
8434 break;
8435 }
8436
8437 // Memoize node if it doesn't produce a glue result.
8438 SDNode *N;
8439 SDVTList VTs = getVTList(VT);
8440 SDValue Ops[] = {N1, N2, N3};
8441 if (VT != MVT::Glue) {
8443 AddNodeIDNode(ID, Opcode, VTs, Ops);
8444 void *IP = nullptr;
8445 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8446 E->intersectFlagsWith(Flags);
8447 return SDValue(E, 0);
8448 }
8449
8450 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8451 N->setFlags(Flags);
8452 createOperands(N, Ops);
8453 CSEMap.InsertNode(N, IP);
8454 } else {
8455 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8456 createOperands(N, Ops);
8457 }
8458
8459 InsertNode(N);
8460 SDValue V = SDValue(N, 0);
8461 NewSDValueDbgMsg(V, "Creating new node: ", this);
8462 return V;
8463}
8464
8465SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8466 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8467 const SDNodeFlags Flags) {
8468 SDValue Ops[] = { N1, N2, N3, N4 };
8469 return getNode(Opcode, DL, VT, Ops, Flags);
8470}
8471
8472SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8473 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8474 SDNodeFlags Flags;
8475 if (Inserter)
8476 Flags = Inserter->getFlags();
8477 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
8478}
8479
8480SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8481 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8482 SDValue N5, const SDNodeFlags Flags) {
8483 SDValue Ops[] = { N1, N2, N3, N4, N5 };
8484 return getNode(Opcode, DL, VT, Ops, Flags);
8485}
8486
8487SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8488 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8489 SDValue N5) {
8490 SDNodeFlags Flags;
8491 if (Inserter)
8492 Flags = Inserter->getFlags();
8493 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
8494}
8495
8496/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
8497/// the incoming stack arguments to be loaded from the stack.
8499 SmallVector<SDValue, 8> ArgChains;
8500
8501 // Include the original chain at the beginning of the list. When this is
8502 // used by target LowerCall hooks, this helps legalize find the
8503 // CALLSEQ_BEGIN node.
8504 ArgChains.push_back(Chain);
8505
8506 // Add a chain value for each stack argument.
8507 for (SDNode *U : getEntryNode().getNode()->users())
8508 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
8509 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
8510 if (FI->getIndex() < 0)
8511 ArgChains.push_back(SDValue(L, 1));
8512
8513 // Build a tokenfactor for all the chains.
8514 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
8515}
8516
8517/// getMemsetValue - Vectorized representation of the memset value
8518/// operand.
8520 const SDLoc &dl) {
8521 assert(!Value.isUndef());
8522
8523 unsigned NumBits = VT.getScalarSizeInBits();
8525 assert(C->getAPIntValue().getBitWidth() == 8);
8526 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
8527 if (VT.isInteger()) {
8528 bool IsOpaque = VT.getSizeInBits() > 64 ||
8529 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
8530 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
8531 }
8532 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
8533 }
8534
8535 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
8536 EVT IntVT = VT.getScalarType();
8537 if (!IntVT.isInteger())
8538 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
8539
8540 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
8541 if (NumBits > 8) {
8542 // Use a multiplication with 0x010101... to extend the input to the
8543 // required length.
8544 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
8545 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
8546 DAG.getConstant(Magic, dl, IntVT));
8547 }
8548
8549 if (VT != Value.getValueType() && !VT.isInteger())
8550 Value = DAG.getBitcast(VT.getScalarType(), Value);
8551 if (VT != Value.getValueType())
8552 Value = DAG.getSplatBuildVector(VT, dl, Value);
8553
8554 return Value;
8555}
8556
8557/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
8558/// used when a memcpy is turned into a memset when the source is a constant
8559/// string ptr.
8561 const TargetLowering &TLI,
8562 const ConstantDataArraySlice &Slice) {
8563 // Handle vector with all elements zero.
8564 if (Slice.Array == nullptr) {
8565 if (VT.isInteger())
8566 return DAG.getConstant(0, dl, VT);
8567 return DAG.getNode(ISD::BITCAST, dl, VT,
8568 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
8569 }
8570
8571 assert(!VT.isVector() && "Can't handle vector type here!");
8572 unsigned NumVTBits = VT.getSizeInBits();
8573 unsigned NumVTBytes = NumVTBits / 8;
8574 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
8575
8576 APInt Val(NumVTBits, 0);
8577 if (DAG.getDataLayout().isLittleEndian()) {
8578 for (unsigned i = 0; i != NumBytes; ++i)
8579 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
8580 } else {
8581 for (unsigned i = 0; i != NumBytes; ++i)
8582 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
8583 }
8584
8585 // If the "cost" of materializing the integer immediate is less than the cost
8586 // of a load, then it is cost effective to turn the load into the immediate.
8587 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
8588 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
8589 return DAG.getConstant(Val, dl, VT);
8590 return SDValue();
8591}
8592
8594 const SDLoc &DL,
8595 const SDNodeFlags Flags) {
8596 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
8597 return getMemBasePlusOffset(Base, Index, DL, Flags);
8598}
8599
8601 const SDLoc &DL,
8602 const SDNodeFlags Flags) {
8603 assert(Offset.getValueType().isInteger());
8604 EVT BasePtrVT = Ptr.getValueType();
8605 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
8606 BasePtrVT))
8607 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
8608 // InBounds only applies to PTRADD, don't set it if we generate ADD.
8609 SDNodeFlags AddFlags = Flags;
8610 AddFlags.setInBounds(false);
8611 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
8612}
8613
8614/// Returns true if memcpy source is constant data.
8616 uint64_t SrcDelta = 0;
8617 GlobalAddressSDNode *G = nullptr;
8618 if (Src.getOpcode() == ISD::GlobalAddress)
8620 else if (Src->isAnyAdd() &&
8621 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
8622 Src.getOperand(1).getOpcode() == ISD::Constant) {
8623 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
8624 SrcDelta = Src.getConstantOperandVal(1);
8625 }
8626 if (!G)
8627 return false;
8628
8629 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
8630 SrcDelta + G->getOffset());
8631}
8632
8634 SelectionDAG &DAG) {
8635 // On Darwin, -Os means optimize for size without hurting performance, so
8636 // only really optimize for size when -Oz (MinSize) is used.
8638 return MF.getFunction().hasMinSize();
8639 return DAG.shouldOptForSize();
8640}
8641
8643 SmallVector<SDValue, 32> &OutChains, unsigned From,
8644 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
8645 SmallVector<SDValue, 16> &OutStoreChains) {
8646 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
8647 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
8648 SmallVector<SDValue, 16> GluedLoadChains;
8649 for (unsigned i = From; i < To; ++i) {
8650 OutChains.push_back(OutLoadChains[i]);
8651 GluedLoadChains.push_back(OutLoadChains[i]);
8652 }
8653
8654 // Chain for all loads.
8655 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8656 GluedLoadChains);
8657
8658 for (unsigned i = From; i < To; ++i) {
8659 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
8660 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
8661 ST->getBasePtr(), ST->getMemoryVT(),
8662 ST->getMemOperand());
8663 OutChains.push_back(NewStore);
8664 }
8665}
8666
8668 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
8669 uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline,
8670 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
8671 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
8672 // Turn a memcpy of undef to nop.
8673 // FIXME: We need to honor volatile even is Src is undef.
8674 if (Src.isUndef())
8675 return Chain;
8676
8677 // Expand memcpy to a series of load and store ops if the size operand falls
8678 // below a certain threshold.
8679 // TODO: In the AlwaysInline case, if the size is big then generate a loop
8680 // rather than maybe a humongous number of loads and stores.
8681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8682 const DataLayout &DL = DAG.getDataLayout();
8683 LLVMContext &C = *DAG.getContext();
8684 std::vector<EVT> MemOps;
8685 bool DstAlignCanChange = false;
8687 MachineFrameInfo &MFI = MF.getFrameInfo();
8688 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
8690 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
8691 DstAlignCanChange = true;
8692 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
8693 if (!SrcAlign || Alignment > *SrcAlign)
8694 SrcAlign = Alignment;
8695 assert(SrcAlign && "SrcAlign must be set");
8697 // If marked as volatile, perform a copy even when marked as constant.
8698 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
8699 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
8700 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
8701 const MemOp Op = isZeroConstant
8702 ? MemOp::Set(Size, DstAlignCanChange, Alignment,
8703 /*IsZeroMemset*/ true, isVol)
8704 : MemOp::Copy(Size, DstAlignCanChange, Alignment,
8705 *SrcAlign, isVol, CopyFromConstant);
8706 if (!TLI.findOptimalMemOpLowering(
8707 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
8708 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
8709 return SDValue();
8710
8711 if (DstAlignCanChange) {
8712 Type *Ty = MemOps[0].getTypeForEVT(C);
8713 Align NewAlign = DL.getABITypeAlign(Ty);
8714
8715 // Don't promote to an alignment that would require dynamic stack
8716 // realignment which may conflict with optimizations such as tail call
8717 // optimization.
8719 if (!TRI->hasStackRealignment(MF))
8720 if (MaybeAlign StackAlign = DL.getStackAlignment())
8721 NewAlign = std::min(NewAlign, *StackAlign);
8722
8723 if (NewAlign > Alignment) {
8724 // Give the stack frame object a larger alignment if needed.
8725 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
8726 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
8727 Alignment = NewAlign;
8728 }
8729 }
8730
8731 // Prepare AAInfo for loads/stores after lowering this memcpy.
8732 AAMDNodes NewAAInfo = AAInfo;
8733 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
8734
8735 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
8736 bool isConstant =
8737 BatchAA && SrcVal &&
8738 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
8739
8740 MachineMemOperand::Flags MMOFlags =
8742 SmallVector<SDValue, 16> OutLoadChains;
8743 SmallVector<SDValue, 16> OutStoreChains;
8744 SmallVector<SDValue, 32> OutChains;
8745 unsigned NumMemOps = MemOps.size();
8746 uint64_t SrcOff = 0, DstOff = 0;
8747 for (unsigned i = 0; i != NumMemOps; ++i) {
8748 EVT VT = MemOps[i];
8749 unsigned VTSize = VT.getSizeInBits() / 8;
8750 SDValue Value, Store;
8751
8752 if (VTSize > Size) {
8753 // Issuing an unaligned load / store pair that overlaps with the previous
8754 // pair. Adjust the offset accordingly.
8755 assert(i == NumMemOps-1 && i != 0);
8756 SrcOff -= VTSize - Size;
8757 DstOff -= VTSize - Size;
8758 }
8759
8760 if (CopyFromConstant &&
8761 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
8762 // It's unlikely a store of a vector immediate can be done in a single
8763 // instruction. It would require a load from a constantpool first.
8764 // We only handle zero vectors here.
8765 // FIXME: Handle other cases where store of vector immediate is done in
8766 // a single instruction.
8767 ConstantDataArraySlice SubSlice;
8768 if (SrcOff < Slice.Length) {
8769 SubSlice = Slice;
8770 SubSlice.move(SrcOff);
8771 } else {
8772 // This is an out-of-bounds access and hence UB. Pretend we read zero.
8773 SubSlice.Array = nullptr;
8774 SubSlice.Offset = 0;
8775 SubSlice.Length = VTSize;
8776 }
8777 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
8778 if (Value.getNode()) {
8779 Store = DAG.getStore(
8780 Chain, dl, Value,
8781 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
8782 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
8783 OutChains.push_back(Store);
8784 }
8785 }
8786
8787 if (!Store.getNode()) {
8788 // The type might not be legal for the target. This should only happen
8789 // if the type is smaller than a legal type, as on PPC, so the right
8790 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
8791 // to Load/Store if NVT==VT.
8792 // FIXME does the case above also need this?
8793 EVT NVT = TLI.getTypeToTransformTo(C, VT);
8794 assert(NVT.bitsGE(VT));
8795
8796 bool isDereferenceable =
8797 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
8798 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
8799 if (isDereferenceable)
8801 if (isConstant)
8802 SrcMMOFlags |= MachineMemOperand::MOInvariant;
8803
8804 Value = DAG.getExtLoad(
8805 ISD::EXTLOAD, dl, NVT, Chain,
8806 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
8807 SrcPtrInfo.getWithOffset(SrcOff), VT,
8808 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
8809 OutLoadChains.push_back(Value.getValue(1));
8810
8811 Store = DAG.getTruncStore(
8812 Chain, dl, Value,
8813 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
8814 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
8815 OutStoreChains.push_back(Store);
8816 }
8817 SrcOff += VTSize;
8818 DstOff += VTSize;
8819 Size -= VTSize;
8820 }
8821
8822 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
8824 unsigned NumLdStInMemcpy = OutStoreChains.size();
8825
8826 if (NumLdStInMemcpy) {
8827 // It may be that memcpy might be converted to memset if it's memcpy
8828 // of constants. In such a case, we won't have loads and stores, but
8829 // just stores. In the absence of loads, there is nothing to gang up.
8830 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
8831 // If target does not care, just leave as it.
8832 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
8833 OutChains.push_back(OutLoadChains[i]);
8834 OutChains.push_back(OutStoreChains[i]);
8835 }
8836 } else {
8837 // Ld/St less than/equal limit set by target.
8838 if (NumLdStInMemcpy <= GluedLdStLimit) {
8839 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
8840 NumLdStInMemcpy, OutLoadChains,
8841 OutStoreChains);
8842 } else {
8843 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
8844 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
8845 unsigned GlueIter = 0;
8846
8847 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
8848 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
8849 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
8850
8851 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
8852 OutLoadChains, OutStoreChains);
8853 GlueIter += GluedLdStLimit;
8854 }
8855
8856 // Residual ld/st.
8857 if (RemainingLdStInMemcpy) {
8858 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
8859 RemainingLdStInMemcpy, OutLoadChains,
8860 OutStoreChains);
8861 }
8862 }
8863 }
8864 }
8865 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
8866}
8867
8869 SDValue Chain, SDValue Dst, SDValue Src,
8870 uint64_t Size, Align Alignment,
8871 bool isVol, bool AlwaysInline,
8872 MachinePointerInfo DstPtrInfo,
8873 MachinePointerInfo SrcPtrInfo,
8874 const AAMDNodes &AAInfo) {
8875 // Turn a memmove of undef to nop.
8876 // FIXME: We need to honor volatile even is Src is undef.
8877 if (Src.isUndef())
8878 return Chain;
8879
8880 // Expand memmove to a series of load and store ops if the size operand falls
8881 // below a certain threshold.
8882 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8883 const DataLayout &DL = DAG.getDataLayout();
8884 LLVMContext &C = *DAG.getContext();
8885 std::vector<EVT> MemOps;
8886 bool DstAlignCanChange = false;
8888 MachineFrameInfo &MFI = MF.getFrameInfo();
8889 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
8891 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
8892 DstAlignCanChange = true;
8893 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
8894 if (!SrcAlign || Alignment > *SrcAlign)
8895 SrcAlign = Alignment;
8896 assert(SrcAlign && "SrcAlign must be set");
8897 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
8898 if (!TLI.findOptimalMemOpLowering(
8899 C, MemOps, Limit,
8900 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
8901 /*IsVolatile*/ true),
8902 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
8903 MF.getFunction().getAttributes()))
8904 return SDValue();
8905
8906 if (DstAlignCanChange) {
8907 Type *Ty = MemOps[0].getTypeForEVT(C);
8908 Align NewAlign = DL.getABITypeAlign(Ty);
8909
8910 // Don't promote to an alignment that would require dynamic stack
8911 // realignment which may conflict with optimizations such as tail call
8912 // optimization.
8914 if (!TRI->hasStackRealignment(MF))
8915 if (MaybeAlign StackAlign = DL.getStackAlignment())
8916 NewAlign = std::min(NewAlign, *StackAlign);
8917
8918 if (NewAlign > Alignment) {
8919 // Give the stack frame object a larger alignment if needed.
8920 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
8921 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
8922 Alignment = NewAlign;
8923 }
8924 }
8925
8926 // Prepare AAInfo for loads/stores after lowering this memmove.
8927 AAMDNodes NewAAInfo = AAInfo;
8928 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
8929
8930 MachineMemOperand::Flags MMOFlags =
8932 uint64_t SrcOff = 0, DstOff = 0;
8933 SmallVector<SDValue, 8> LoadValues;
8934 SmallVector<SDValue, 8> LoadChains;
8935 SmallVector<SDValue, 8> OutChains;
8936 unsigned NumMemOps = MemOps.size();
8937 for (unsigned i = 0; i < NumMemOps; i++) {
8938 EVT VT = MemOps[i];
8939 unsigned VTSize = VT.getSizeInBits() / 8;
8940 SDValue Value;
8941
8942 bool isDereferenceable =
8943 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
8944 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
8945 if (isDereferenceable)
8947
8948 Value = DAG.getLoad(
8949 VT, dl, Chain,
8950 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
8951 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
8952 LoadValues.push_back(Value);
8953 LoadChains.push_back(Value.getValue(1));
8954 SrcOff += VTSize;
8955 }
8956 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8957 OutChains.clear();
8958 for (unsigned i = 0; i < NumMemOps; i++) {
8959 EVT VT = MemOps[i];
8960 unsigned VTSize = VT.getSizeInBits() / 8;
8961 SDValue Store;
8962
8963 Store = DAG.getStore(
8964 Chain, dl, LoadValues[i],
8965 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
8966 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
8967 OutChains.push_back(Store);
8968 DstOff += VTSize;
8969 }
8970
8971 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
8972}
8973
8974/// Lower the call to 'memset' intrinsic function into a series of store
8975/// operations.
8976///
8977/// \param DAG Selection DAG where lowered code is placed.
8978/// \param dl Link to corresponding IR location.
8979/// \param Chain Control flow dependency.
8980/// \param Dst Pointer to destination memory location.
8981/// \param Src Value of byte to write into the memory.
8982/// \param Size Number of bytes to write.
8983/// \param Alignment Alignment of the destination in bytes.
8984/// \param isVol True if destination is volatile.
8985/// \param AlwaysInline Makes sure no function call is generated.
8986/// \param DstPtrInfo IR information on the memory pointer.
8987/// \returns New head in the control flow, if lowering was successful, empty
8988/// SDValue otherwise.
8989///
8990/// The function tries to replace 'llvm.memset' intrinsic with several store
8991/// operations and value calculation code. This is usually profitable for small
8992/// memory size or when the semantic requires inlining.
8994 SDValue Chain, SDValue Dst, SDValue Src,
8995 uint64_t Size, Align Alignment, bool isVol,
8996 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
8997 const AAMDNodes &AAInfo) {
8998 // Turn a memset of undef to nop.
8999 // FIXME: We need to honor volatile even is Src is undef.
9000 if (Src.isUndef())
9001 return Chain;
9002
9003 // Expand memset to a series of load/store ops if the size operand
9004 // falls below a certain threshold.
9005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9006 std::vector<EVT> MemOps;
9007 bool DstAlignCanChange = false;
9008 LLVMContext &C = *DAG.getContext();
9010 MachineFrameInfo &MFI = MF.getFrameInfo();
9011 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9013 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9014 DstAlignCanChange = true;
9015 bool IsZeroVal = isNullConstant(Src);
9016 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9017
9018 if (!TLI.findOptimalMemOpLowering(
9019 C, MemOps, Limit,
9020 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9021 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
9022 return SDValue();
9023
9024 if (DstAlignCanChange) {
9025 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9026 const DataLayout &DL = DAG.getDataLayout();
9027 Align NewAlign = DL.getABITypeAlign(Ty);
9028
9029 // Don't promote to an alignment that would require dynamic stack
9030 // realignment which may conflict with optimizations such as tail call
9031 // optimization.
9033 if (!TRI->hasStackRealignment(MF))
9034 if (MaybeAlign StackAlign = DL.getStackAlignment())
9035 NewAlign = std::min(NewAlign, *StackAlign);
9036
9037 if (NewAlign > Alignment) {
9038 // Give the stack frame object a larger alignment if needed.
9039 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9040 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9041 Alignment = NewAlign;
9042 }
9043 }
9044
9045 SmallVector<SDValue, 8> OutChains;
9046 uint64_t DstOff = 0;
9047 unsigned NumMemOps = MemOps.size();
9048
9049 // Find the largest store and generate the bit pattern for it.
9050 EVT LargestVT = MemOps[0];
9051 for (unsigned i = 1; i < NumMemOps; i++)
9052 if (MemOps[i].bitsGT(LargestVT))
9053 LargestVT = MemOps[i];
9054 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9055
9056 // Prepare AAInfo for loads/stores after lowering this memset.
9057 AAMDNodes NewAAInfo = AAInfo;
9058 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9059
9060 for (unsigned i = 0; i < NumMemOps; i++) {
9061 EVT VT = MemOps[i];
9062 unsigned VTSize = VT.getSizeInBits() / 8;
9063 if (VTSize > Size) {
9064 // Issuing an unaligned load / store pair that overlaps with the previous
9065 // pair. Adjust the offset accordingly.
9066 assert(i == NumMemOps-1 && i != 0);
9067 DstOff -= VTSize - Size;
9068 }
9069
9070 // If this store is smaller than the largest store see whether we can get
9071 // the smaller value for free with a truncate or extract vector element and
9072 // then store.
9073 SDValue Value = MemSetValue;
9074 if (VT.bitsLT(LargestVT)) {
9075 unsigned Index;
9076 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9077 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9078 if (!LargestVT.isVector() && !VT.isVector() &&
9079 TLI.isTruncateFree(LargestVT, VT))
9080 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9081 else if (LargestVT.isVector() && !VT.isVector() &&
9083 LargestVT.getTypeForEVT(*DAG.getContext()),
9084 VT.getSizeInBits(), Index) &&
9085 TLI.isTypeLegal(SVT) &&
9086 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9087 // Target which can combine store(extractelement VectorTy, Idx) can get
9088 // the smaller value for free.
9089 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9090 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9091 } else
9092 Value = getMemsetValue(Src, VT, DAG, dl);
9093 }
9094 assert(Value.getValueType() == VT && "Value with wrong type.");
9095 SDValue Store = DAG.getStore(
9096 Chain, dl, Value,
9097 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9098 DstPtrInfo.getWithOffset(DstOff), Alignment,
9100 NewAAInfo);
9101 OutChains.push_back(Store);
9102 DstOff += VT.getSizeInBits() / 8;
9103 Size -= VTSize;
9104 }
9105
9106 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
9107}
9108
9110 unsigned AS) {
9111 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
9112 // pointer operands can be losslessly bitcasted to pointers of address space 0
9113 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
9114 report_fatal_error("cannot lower memory intrinsic in address space " +
9115 Twine(AS));
9116 }
9117}
9118
9120 const SelectionDAG *SelDAG,
9121 bool AllowReturnsFirstArg) {
9122 if (!CI || !CI->isTailCall())
9123 return false;
9124 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
9125 // helper symbol we lower to.
9126 return isInTailCallPosition(*CI, SelDAG->getTarget(),
9127 AllowReturnsFirstArg &&
9129}
9130
9131std::pair<SDValue, SDValue>
9133 SDValue Mem1, SDValue Size, const CallInst *CI) {
9134 RTLIB::LibcallImpl MemcmpImpl = TLI->getLibcallImpl(RTLIB::MEMCMP);
9135 if (MemcmpImpl == RTLIB::Unsupported)
9136 return {};
9137
9140 {Mem0, PT},
9141 {Mem1, PT},
9143
9145 bool IsTailCall =
9146 isInTailCallPositionWrapper(CI, this, /*AllowReturnsFirstArg*/ true);
9147
9148 CLI.setDebugLoc(dl)
9149 .setChain(Chain)
9150 .setLibCallee(
9151 TLI->getLibcallImplCallingConv(MemcmpImpl),
9153 getExternalSymbol(MemcmpImpl, TLI->getPointerTy(getDataLayout())),
9154 std::move(Args))
9155 .setTailCall(IsTailCall);
9156
9157 return TLI->LowerCallTo(CLI);
9158}
9159
9160std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
9161 const SDLoc &dl,
9162 SDValue Src,
9163 const CallInst *CI) {
9164 RTLIB::LibcallImpl StrlenImpl = TLI->getLibcallImpl(RTLIB::STRLEN);
9165 if (StrlenImpl == RTLIB::Unsupported)
9166 return {};
9167
9168 // Emit a library call.
9171
9173 bool IsTailCall =
9174 isInTailCallPositionWrapper(CI, this, /*AllowReturnsFirstArg*/ true);
9175
9176 CLI.setDebugLoc(dl)
9177 .setChain(Chain)
9178 .setLibCallee(TLI->getLibcallImplCallingConv(StrlenImpl), CI->getType(),
9180 StrlenImpl, TLI->getProgramPointerTy(getDataLayout())),
9181 std::move(Args))
9182 .setTailCall(IsTailCall);
9183
9184 return TLI->LowerCallTo(CLI);
9185}
9186
9188 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
9189 Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI,
9190 std::optional<bool> OverrideTailCall, MachinePointerInfo DstPtrInfo,
9191 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9192 BatchAAResults *BatchAA) {
9193 // Check to see if we should lower the memcpy to loads and stores first.
9194 // For cases within the target-specified limits, this is the best choice.
9196 if (ConstantSize) {
9197 // Memcpy with size zero? Just return the original chain.
9198 if (ConstantSize->isZero())
9199 return Chain;
9200
9202 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
9203 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA);
9204 if (Result.getNode())
9205 return Result;
9206 }
9207
9208 // Then check to see if we should lower the memcpy with target-specific
9209 // code. If the target chooses to do this, this is the next best.
9210 if (TSI) {
9211 SDValue Result = TSI->EmitTargetCodeForMemcpy(
9212 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
9213 DstPtrInfo, SrcPtrInfo);
9214 if (Result.getNode())
9215 return Result;
9216 }
9217
9218 // If we really need inline code and the target declined to provide it,
9219 // use a (potentially long) sequence of loads and stores.
9220 if (AlwaysInline) {
9221 assert(ConstantSize && "AlwaysInline requires a constant size!");
9223 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
9224 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA);
9225 }
9226
9229
9230 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
9231 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
9232 // respect volatile, so they may do things like read or write memory
9233 // beyond the given memory regions. But fixing this isn't easy, and most
9234 // people don't care.
9235
9236 // Emit a library call.
9239 Args.emplace_back(Dst, PtrTy);
9240 Args.emplace_back(Src, PtrTy);
9241 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
9242 // FIXME: pass in SDLoc
9244 bool IsTailCall = false;
9245 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
9246
9247 if (OverrideTailCall.has_value()) {
9248 IsTailCall = *OverrideTailCall;
9249 } else {
9250 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
9251 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
9252 }
9253
9254 CLI.setDebugLoc(dl)
9255 .setChain(Chain)
9256 .setLibCallee(
9257 TLI->getLibcallImplCallingConv(MemCpyImpl),
9258 Dst.getValueType().getTypeForEVT(*getContext()),
9259 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
9260 std::move(Args))
9262 .setTailCall(IsTailCall);
9263
9264 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
9265 return CallResult.second;
9266}
9267
9269 SDValue Dst, SDValue Src, SDValue Size,
9270 Type *SizeTy, unsigned ElemSz,
9271 bool isTailCall,
9272 MachinePointerInfo DstPtrInfo,
9273 MachinePointerInfo SrcPtrInfo) {
9274 // Emit a library call.
9277 Args.emplace_back(Dst, ArgTy);
9278 Args.emplace_back(Src, ArgTy);
9279 Args.emplace_back(Size, SizeTy);
9280
9281 RTLIB::Libcall LibraryCall =
9283 RTLIB::LibcallImpl LibcallImpl = TLI->getLibcallImpl(LibraryCall);
9284 if (LibcallImpl == RTLIB::Unsupported)
9285 report_fatal_error("Unsupported element size");
9286
9288 CLI.setDebugLoc(dl)
9289 .setChain(Chain)
9290 .setLibCallee(
9291 TLI->getLibcallImplCallingConv(LibcallImpl),
9293 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
9294 std::move(Args))
9296 .setTailCall(isTailCall);
9297
9298 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9299 return CallResult.second;
9300}
9301
9303 SDValue Src, SDValue Size, Align Alignment,
9304 bool isVol, const CallInst *CI,
9305 std::optional<bool> OverrideTailCall,
9306 MachinePointerInfo DstPtrInfo,
9307 MachinePointerInfo SrcPtrInfo,
9308 const AAMDNodes &AAInfo,
9309 BatchAAResults *BatchAA) {
9310 // Check to see if we should lower the memmove to loads and stores first.
9311 // For cases within the target-specified limits, this is the best choice.
9313 if (ConstantSize) {
9314 // Memmove with size zero? Just return the original chain.
9315 if (ConstantSize->isZero())
9316 return Chain;
9317
9319 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
9320 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
9321 if (Result.getNode())
9322 return Result;
9323 }
9324
9325 // Then check to see if we should lower the memmove with target-specific
9326 // code. If the target chooses to do this, this is the next best.
9327 if (TSI) {
9328 SDValue Result =
9329 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
9330 Alignment, isVol, DstPtrInfo, SrcPtrInfo);
9331 if (Result.getNode())
9332 return Result;
9333 }
9334
9337
9338 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
9339 // not be safe. See memcpy above for more details.
9340
9341 // Emit a library call.
9344 Args.emplace_back(Dst, PtrTy);
9345 Args.emplace_back(Src, PtrTy);
9346 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
9347 // FIXME: pass in SDLoc
9349
9350 RTLIB::LibcallImpl MemmoveImpl = TLI->getLibcallImpl(RTLIB::MEMMOVE);
9351
9352 bool IsTailCall = false;
9353 if (OverrideTailCall.has_value()) {
9354 IsTailCall = *OverrideTailCall;
9355 } else {
9356 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
9357 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
9358 }
9359
9360 CLI.setDebugLoc(dl)
9361 .setChain(Chain)
9362 .setLibCallee(
9363 TLI->getLibcallImplCallingConv(MemmoveImpl),
9364 Dst.getValueType().getTypeForEVT(*getContext()),
9365 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
9366 std::move(Args))
9368 .setTailCall(IsTailCall);
9369
9370 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
9371 return CallResult.second;
9372}
9373
9375 SDValue Dst, SDValue Src, SDValue Size,
9376 Type *SizeTy, unsigned ElemSz,
9377 bool isTailCall,
9378 MachinePointerInfo DstPtrInfo,
9379 MachinePointerInfo SrcPtrInfo) {
9380 // Emit a library call.
9382 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
9383 Args.emplace_back(Dst, IntPtrTy);
9384 Args.emplace_back(Src, IntPtrTy);
9385 Args.emplace_back(Size, SizeTy);
9386
9387 RTLIB::Libcall LibraryCall =
9389 RTLIB::LibcallImpl LibcallImpl = TLI->getLibcallImpl(LibraryCall);
9390 if (LibcallImpl == RTLIB::Unsupported)
9391 report_fatal_error("Unsupported element size");
9392
9394 CLI.setDebugLoc(dl)
9395 .setChain(Chain)
9396 .setLibCallee(
9397 TLI->getLibcallImplCallingConv(LibcallImpl),
9399 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
9400 std::move(Args))
9402 .setTailCall(isTailCall);
9403
9404 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9405 return CallResult.second;
9406}
9407
9409 SDValue Src, SDValue Size, Align Alignment,
9410 bool isVol, bool AlwaysInline,
9411 const CallInst *CI,
9412 MachinePointerInfo DstPtrInfo,
9413 const AAMDNodes &AAInfo) {
9414 // Check to see if we should lower the memset to stores first.
9415 // For cases within the target-specified limits, this is the best choice.
9417 if (ConstantSize) {
9418 // Memset with size zero? Just return the original chain.
9419 if (ConstantSize->isZero())
9420 return Chain;
9421
9422 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
9423 ConstantSize->getZExtValue(), Alignment,
9424 isVol, false, DstPtrInfo, AAInfo);
9425
9426 if (Result.getNode())
9427 return Result;
9428 }
9429
9430 // Then check to see if we should lower the memset with target-specific
9431 // code. If the target chooses to do this, this is the next best.
9432 if (TSI) {
9433 SDValue Result = TSI->EmitTargetCodeForMemset(
9434 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
9435 if (Result.getNode())
9436 return Result;
9437 }
9438
9439 // If we really need inline code and the target declined to provide it,
9440 // use a (potentially long) sequence of loads and stores.
9441 if (AlwaysInline) {
9442 assert(ConstantSize && "AlwaysInline requires a constant size!");
9443 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
9444 ConstantSize->getZExtValue(), Alignment,
9445 isVol, true, DstPtrInfo, AAInfo);
9446 assert(Result &&
9447 "getMemsetStores must return a valid sequence when AlwaysInline");
9448 return Result;
9449 }
9450
9452
9453 // Emit a library call.
9454 auto &Ctx = *getContext();
9455 const auto& DL = getDataLayout();
9456
9458 // FIXME: pass in SDLoc
9459 CLI.setDebugLoc(dl).setChain(Chain);
9460
9461 RTLIB::LibcallImpl BzeroImpl = TLI->getLibcallImpl(RTLIB::BZERO);
9462 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
9463
9464 // If zeroing out and bzero is present, use it.
9465 if (UseBZero) {
9467 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
9468 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
9469 CLI.setLibCallee(
9470 TLI->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
9471 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
9472 } else {
9473 RTLIB::LibcallImpl MemsetImpl = TLI->getLibcallImpl(RTLIB::MEMSET);
9474
9476 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
9477 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
9478 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
9479 CLI.setLibCallee(TLI->getLibcallImplCallingConv(MemsetImpl),
9480 Dst.getValueType().getTypeForEVT(Ctx),
9481 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
9482 std::move(Args));
9483 }
9484
9485 RTLIB::LibcallImpl MemsetImpl = TLI->getLibcallImpl(RTLIB::MEMSET);
9486 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
9487
9488 // If we're going to use bzero, make sure not to tail call unless the
9489 // subsequent return doesn't need a value, as bzero doesn't return the first
9490 // arg unlike memset.
9491 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
9492 bool IsTailCall =
9493 CI && CI->isTailCall() &&
9494 isInTailCallPosition(*CI, getTarget(), ReturnsFirstArg && LowersToMemset);
9495 CLI.setDiscardResult().setTailCall(IsTailCall);
9496
9497 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9498 return CallResult.second;
9499}
9500
9503 Type *SizeTy, unsigned ElemSz,
9504 bool isTailCall,
9505 MachinePointerInfo DstPtrInfo) {
9506 // Emit a library call.
9508 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
9509 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
9510 Args.emplace_back(Size, SizeTy);
9511
9512 RTLIB::Libcall LibraryCall =
9514 RTLIB::LibcallImpl LibcallImpl = TLI->getLibcallImpl(LibraryCall);
9515 if (LibcallImpl == RTLIB::Unsupported)
9516 report_fatal_error("Unsupported element size");
9517
9519 CLI.setDebugLoc(dl)
9520 .setChain(Chain)
9521 .setLibCallee(
9522 TLI->getLibcallImplCallingConv(LibcallImpl),
9524 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
9525 std::move(Args))
9527 .setTailCall(isTailCall);
9528
9529 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9530 return CallResult.second;
9531}
9532
9533SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
9535 MachineMemOperand *MMO,
9536 ISD::LoadExtType ExtType) {
9538 AddNodeIDNode(ID, Opcode, VTList, Ops);
9539 ID.AddInteger(MemVT.getRawBits());
9540 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
9541 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
9542 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9543 ID.AddInteger(MMO->getFlags());
9544 void* IP = nullptr;
9545 if (auto *E = cast_or_null<AtomicSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
9546 E->refineAlignment(MMO);
9547 E->refineRanges(MMO);
9548 return SDValue(E, 0);
9549 }
9550
9551 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
9552 VTList, MemVT, MMO, ExtType);
9553 createOperands(N, Ops);
9554
9555 CSEMap.InsertNode(N, IP);
9556 InsertNode(N);
9557 SDValue V(N, 0);
9558 NewSDValueDbgMsg(V, "Creating new node: ", this);
9559 return V;
9560}
9561
9563 EVT MemVT, SDVTList VTs, SDValue Chain,
9564 SDValue Ptr, SDValue Cmp, SDValue Swp,
9565 MachineMemOperand *MMO) {
9566 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
9568 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
9569
9570 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
9571 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
9572}
9573
9574SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
9575 SDValue Chain, SDValue Ptr, SDValue Val,
9576 MachineMemOperand *MMO) {
9577 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
9578 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
9579 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
9580 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
9581 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
9582 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
9583 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
9584 Opcode == ISD::ATOMIC_LOAD_FMIN ||
9585 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
9586 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
9587 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
9588 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
9589 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
9590 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
9591 Opcode == ISD::ATOMIC_STORE) &&
9592 "Invalid Atomic Op");
9593
9594 EVT VT = Val.getValueType();
9595
9596 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
9597 getVTList(VT, MVT::Other);
9598 SDValue Ops[] = {Chain, Ptr, Val};
9599 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
9600}
9601
9603 EVT MemVT, EVT VT, SDValue Chain,
9604 SDValue Ptr, MachineMemOperand *MMO) {
9605 SDVTList VTs = getVTList(VT, MVT::Other);
9606 SDValue Ops[] = {Chain, Ptr};
9607 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
9608}
9609
9610/// getMergeValues - Create a MERGE_VALUES node from the given operands.
9612 if (Ops.size() == 1)
9613 return Ops[0];
9614
9616 VTs.reserve(Ops.size());
9617 for (const SDValue &Op : Ops)
9618 VTs.push_back(Op.getValueType());
9619 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
9620}
9621
9623 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
9624 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
9626 const AAMDNodes &AAInfo) {
9627 if (Size.hasValue() && !Size.getValue())
9629
9631 MachineMemOperand *MMO =
9632 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
9633
9634 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
9635}
9636
9638 SDVTList VTList,
9639 ArrayRef<SDValue> Ops, EVT MemVT,
9640 MachineMemOperand *MMO) {
9641 assert(
9642 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
9643 Opcode == ISD::PREFETCH ||
9644 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
9645 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
9646 "Opcode is not a memory-accessing opcode!");
9647
9648 // Memoize the node unless it returns a glue result.
9650 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9652 AddNodeIDNode(ID, Opcode, VTList, Ops);
9653 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
9654 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
9655 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9656 ID.AddInteger(MMO->getFlags());
9657 ID.AddInteger(MemVT.getRawBits());
9658 void *IP = nullptr;
9659 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9660 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
9661 return SDValue(E, 0);
9662 }
9663
9664 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
9665 VTList, MemVT, MMO);
9666 createOperands(N, Ops);
9667
9668 CSEMap.InsertNode(N, IP);
9669 } else {
9670 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
9671 VTList, MemVT, MMO);
9672 createOperands(N, Ops);
9673 }
9674 InsertNode(N);
9675 SDValue V(N, 0);
9676 NewSDValueDbgMsg(V, "Creating new node: ", this);
9677 return V;
9678}
9679
9681 SDValue Chain, int FrameIndex) {
9682 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
9683 const auto VTs = getVTList(MVT::Other);
9684 SDValue Ops[2] = {
9685 Chain,
9686 getFrameIndex(FrameIndex,
9687 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
9688 true)};
9689
9691 AddNodeIDNode(ID, Opcode, VTs, Ops);
9692 ID.AddInteger(FrameIndex);
9693 void *IP = nullptr;
9694 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
9695 return SDValue(E, 0);
9696
9697 LifetimeSDNode *N =
9698 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
9699 createOperands(N, Ops);
9700 CSEMap.InsertNode(N, IP);
9701 InsertNode(N);
9702 SDValue V(N, 0);
9703 NewSDValueDbgMsg(V, "Creating new node: ", this);
9704 return V;
9705}
9706
9708 uint64_t Guid, uint64_t Index,
9709 uint32_t Attr) {
9710 const unsigned Opcode = ISD::PSEUDO_PROBE;
9711 const auto VTs = getVTList(MVT::Other);
9712 SDValue Ops[] = {Chain};
9714 AddNodeIDNode(ID, Opcode, VTs, Ops);
9715 ID.AddInteger(Guid);
9716 ID.AddInteger(Index);
9717 void *IP = nullptr;
9718 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
9719 return SDValue(E, 0);
9720
9721 auto *N = newSDNode<PseudoProbeSDNode>(
9722 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
9723 createOperands(N, Ops);
9724 CSEMap.InsertNode(N, IP);
9725 InsertNode(N);
9726 SDValue V(N, 0);
9727 NewSDValueDbgMsg(V, "Creating new node: ", this);
9728 return V;
9729}
9730
9731/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
9732/// MachinePointerInfo record from it. This is particularly useful because the
9733/// code generator has many cases where it doesn't bother passing in a
9734/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
9736 SelectionDAG &DAG, SDValue Ptr,
9737 int64_t Offset = 0) {
9738 // If this is FI+Offset, we can model it.
9739 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
9741 FI->getIndex(), Offset);
9742
9743 // If this is (FI+Offset1)+Offset2, we can model it.
9744 if (Ptr.getOpcode() != ISD::ADD ||
9747 return Info;
9748
9749 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9751 DAG.getMachineFunction(), FI,
9752 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
9753}
9754
9755/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
9756/// MachinePointerInfo record from it. This is particularly useful because the
9757/// code generator has many cases where it doesn't bother passing in a
9758/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
9760 SelectionDAG &DAG, SDValue Ptr,
9761 SDValue OffsetOp) {
9762 // If the 'Offset' value isn't a constant, we can't handle this.
9764 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
9765 if (OffsetOp.isUndef())
9766 return InferPointerInfo(Info, DAG, Ptr);
9767 return Info;
9768}
9769
9771 EVT VT, const SDLoc &dl, SDValue Chain,
9772 SDValue Ptr, SDValue Offset,
9773 MachinePointerInfo PtrInfo, EVT MemVT,
9774 Align Alignment,
9775 MachineMemOperand::Flags MMOFlags,
9776 const AAMDNodes &AAInfo, const MDNode *Ranges) {
9777 assert(Chain.getValueType() == MVT::Other &&
9778 "Invalid chain type");
9779
9780 MMOFlags |= MachineMemOperand::MOLoad;
9781 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
9782 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
9783 // clients.
9784 if (PtrInfo.V.isNull())
9785 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
9786
9787 TypeSize Size = MemVT.getStoreSize();
9789 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
9790 Alignment, AAInfo, Ranges);
9791 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
9792}
9793
9795 EVT VT, const SDLoc &dl, SDValue Chain,
9796 SDValue Ptr, SDValue Offset, EVT MemVT,
9797 MachineMemOperand *MMO) {
9798 if (VT == MemVT) {
9799 ExtType = ISD::NON_EXTLOAD;
9800 } else if (ExtType == ISD::NON_EXTLOAD) {
9801 assert(VT == MemVT && "Non-extending load from different memory type!");
9802 } else {
9803 // Extending load.
9804 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
9805 "Should only be an extending load, not truncating!");
9806 assert(VT.isInteger() == MemVT.isInteger() &&
9807 "Cannot convert from FP to Int or Int -> FP!");
9808 assert(VT.isVector() == MemVT.isVector() &&
9809 "Cannot use an ext load to convert to or from a vector!");
9810 assert((!VT.isVector() ||
9812 "Cannot use an ext load to change the number of vector elements!");
9813 }
9814
9815 assert((!MMO->getRanges() ||
9817 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
9818 MemVT.isInteger())) &&
9819 "Range metadata and load type must match!");
9820
9821 bool Indexed = AM != ISD::UNINDEXED;
9822 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
9823
9824 SDVTList VTs = Indexed ?
9825 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
9826 SDValue Ops[] = { Chain, Ptr, Offset };
9828 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
9829 ID.AddInteger(MemVT.getRawBits());
9830 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
9831 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
9832 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9833 ID.AddInteger(MMO->getFlags());
9834 void *IP = nullptr;
9835 if (auto *E = cast_or_null<LoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
9836 E->refineAlignment(MMO);
9837 E->refineRanges(MMO);
9838 return SDValue(E, 0);
9839 }
9840 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
9841 ExtType, MemVT, MMO);
9842 createOperands(N, Ops);
9843
9844 CSEMap.InsertNode(N, IP);
9845 InsertNode(N);
9846 SDValue V(N, 0);
9847 NewSDValueDbgMsg(V, "Creating new node: ", this);
9848 return V;
9849}
9850
9852 SDValue Ptr, MachinePointerInfo PtrInfo,
9853 MaybeAlign Alignment,
9854 MachineMemOperand::Flags MMOFlags,
9855 const AAMDNodes &AAInfo, const MDNode *Ranges) {
9856 SDValue Undef = getUNDEF(Ptr.getValueType());
9857 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
9858 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
9859}
9860
9862 SDValue Ptr, MachineMemOperand *MMO) {
9863 SDValue Undef = getUNDEF(Ptr.getValueType());
9864 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
9865 VT, MMO);
9866}
9867
9869 EVT VT, SDValue Chain, SDValue Ptr,
9870 MachinePointerInfo PtrInfo, EVT MemVT,
9871 MaybeAlign Alignment,
9872 MachineMemOperand::Flags MMOFlags,
9873 const AAMDNodes &AAInfo) {
9874 SDValue Undef = getUNDEF(Ptr.getValueType());
9875 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
9876 MemVT, Alignment, MMOFlags, AAInfo);
9877}
9878
9880 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
9881 MachineMemOperand *MMO) {
9882 SDValue Undef = getUNDEF(Ptr.getValueType());
9883 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
9884 MemVT, MMO);
9885}
9886
9890 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
9891 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
9892 // Don't propagate the invariant or dereferenceable flags.
9893 auto MMOFlags =
9894 LD->getMemOperand()->getFlags() &
9896 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
9897 LD->getChain(), Base, Offset, LD->getPointerInfo(),
9898 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
9899}
9900
9902 SDValue Ptr, MachinePointerInfo PtrInfo,
9903 Align Alignment,
9904 MachineMemOperand::Flags MMOFlags,
9905 const AAMDNodes &AAInfo) {
9906 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
9907
9908 MMOFlags |= MachineMemOperand::MOStore;
9909 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
9910
9911 if (PtrInfo.V.isNull())
9912 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
9913
9916 MachineMemOperand *MMO =
9917 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
9918 return getStore(Chain, dl, Val, Ptr, MMO);
9919}
9920
9922 SDValue Ptr, MachineMemOperand *MMO) {
9923 SDValue Undef = getUNDEF(Ptr.getValueType());
9924 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
9926}
9927
9929 SDValue Ptr, SDValue Offset, EVT SVT,
9931 bool IsTruncating) {
9932 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
9933 EVT VT = Val.getValueType();
9934 if (VT == SVT) {
9935 IsTruncating = false;
9936 } else if (!IsTruncating) {
9937 assert(VT == SVT && "No-truncating store from different memory type!");
9938 } else {
9940 "Should only be a truncating store, not extending!");
9941 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
9942 assert(VT.isVector() == SVT.isVector() &&
9943 "Cannot use trunc store to convert to or from a vector!");
9944 assert((!VT.isVector() ||
9946 "Cannot use trunc store to change the number of vector elements!");
9947 }
9948
9949 bool Indexed = AM != ISD::UNINDEXED;
9950 assert((Indexed || Offset.isUndef()) && "Unindexed store with an offset!");
9951 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
9952 : getVTList(MVT::Other);
9953 SDValue Ops[] = {Chain, Val, Ptr, Offset};
9956 ID.AddInteger(SVT.getRawBits());
9957 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
9958 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
9959 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9960 ID.AddInteger(MMO->getFlags());
9961 void *IP = nullptr;
9962 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9963 cast<StoreSDNode>(E)->refineAlignment(MMO);
9964 return SDValue(E, 0);
9965 }
9966 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
9967 IsTruncating, SVT, MMO);
9968 createOperands(N, Ops);
9969
9970 CSEMap.InsertNode(N, IP);
9971 InsertNode(N);
9972 SDValue V(N, 0);
9973 NewSDValueDbgMsg(V, "Creating new node: ", this);
9974 return V;
9975}
9976
9978 SDValue Ptr, MachinePointerInfo PtrInfo,
9979 EVT SVT, Align Alignment,
9980 MachineMemOperand::Flags MMOFlags,
9981 const AAMDNodes &AAInfo) {
9982 assert(Chain.getValueType() == MVT::Other &&
9983 "Invalid chain type");
9984
9985 MMOFlags |= MachineMemOperand::MOStore;
9986 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
9987
9988 if (PtrInfo.V.isNull())
9989 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
9990
9992 MachineMemOperand *MMO = MF.getMachineMemOperand(
9993 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
9994 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
9995}
9996
9998 SDValue Ptr, EVT SVT,
9999 MachineMemOperand *MMO) {
10000 SDValue Undef = getUNDEF(Ptr.getValueType());
10001 return getStore(Chain, dl, Val, Ptr, Undef, SVT, MMO, ISD::UNINDEXED, true);
10002}
10003
10007 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
10008 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
10009 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10010 ST->getMemoryVT(), ST->getMemOperand(), AM,
10011 ST->isTruncatingStore());
10012}
10013
10015 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
10016 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
10017 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
10018 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
10019 const MDNode *Ranges, bool IsExpanding) {
10020 MMOFlags |= MachineMemOperand::MOLoad;
10021 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10022 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10023 // clients.
10024 if (PtrInfo.V.isNull())
10025 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10026
10027 TypeSize Size = MemVT.getStoreSize();
10029 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
10030 Alignment, AAInfo, Ranges);
10031 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
10032 MMO, IsExpanding);
10033}
10034
10036 ISD::LoadExtType ExtType, EVT VT,
10037 const SDLoc &dl, SDValue Chain, SDValue Ptr,
10038 SDValue Offset, SDValue Mask, SDValue EVL,
10039 EVT MemVT, MachineMemOperand *MMO,
10040 bool IsExpanding) {
10041 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10042 assert(Mask.getValueType().getVectorElementCount() ==
10043 VT.getVectorElementCount() &&
10044 "Vector width mismatch between mask and data");
10045
10046 bool Indexed = AM != ISD::UNINDEXED;
10047 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
10048
10049 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
10050 : getVTList(VT, MVT::Other);
10051 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
10053 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
10054 ID.AddInteger(MemVT.getRawBits());
10055 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
10056 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
10057 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10058 ID.AddInteger(MMO->getFlags());
10059 void *IP = nullptr;
10060 if (auto *E = cast_or_null<VPLoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10061 E->refineAlignment(MMO);
10062 E->refineRanges(MMO);
10063 return SDValue(E, 0);
10064 }
10065 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10066 ExtType, IsExpanding, MemVT, MMO);
10067 createOperands(N, Ops);
10068
10069 CSEMap.InsertNode(N, IP);
10070 InsertNode(N);
10071 SDValue V(N, 0);
10072 NewSDValueDbgMsg(V, "Creating new node: ", this);
10073 return V;
10074}
10075
10077 SDValue Ptr, SDValue Mask, SDValue EVL,
10078 MachinePointerInfo PtrInfo,
10079 MaybeAlign Alignment,
10080 MachineMemOperand::Flags MMOFlags,
10081 const AAMDNodes &AAInfo, const MDNode *Ranges,
10082 bool IsExpanding) {
10083 SDValue Undef = getUNDEF(Ptr.getValueType());
10084 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10085 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
10086 IsExpanding);
10087}
10088
10090 SDValue Ptr, SDValue Mask, SDValue EVL,
10091 MachineMemOperand *MMO, bool IsExpanding) {
10092 SDValue Undef = getUNDEF(Ptr.getValueType());
10093 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10094 Mask, EVL, VT, MMO, IsExpanding);
10095}
10096
10098 EVT VT, SDValue Chain, SDValue Ptr,
10099 SDValue Mask, SDValue EVL,
10100 MachinePointerInfo PtrInfo, EVT MemVT,
10101 MaybeAlign Alignment,
10102 MachineMemOperand::Flags MMOFlags,
10103 const AAMDNodes &AAInfo, bool IsExpanding) {
10104 SDValue Undef = getUNDEF(Ptr.getValueType());
10105 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
10106 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
10107 IsExpanding);
10108}
10109
10111 EVT VT, SDValue Chain, SDValue Ptr,
10112 SDValue Mask, SDValue EVL, EVT MemVT,
10113 MachineMemOperand *MMO, bool IsExpanding) {
10114 SDValue Undef = getUNDEF(Ptr.getValueType());
10115 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
10116 EVL, MemVT, MMO, IsExpanding);
10117}
10118
10122 auto *LD = cast<VPLoadSDNode>(OrigLoad);
10123 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
10124 // Don't propagate the invariant or dereferenceable flags.
10125 auto MMOFlags =
10126 LD->getMemOperand()->getFlags() &
10128 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
10129 LD->getChain(), Base, Offset, LD->getMask(),
10130 LD->getVectorLength(), LD->getPointerInfo(),
10131 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
10132 nullptr, LD->isExpandingLoad());
10133}
10134
10136 SDValue Ptr, SDValue Offset, SDValue Mask,
10137 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
10138 ISD::MemIndexedMode AM, bool IsTruncating,
10139 bool IsCompressing) {
10140 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10141 assert(Mask.getValueType().getVectorElementCount() ==
10143 "Vector width mismatch between mask and data");
10144
10145 bool Indexed = AM != ISD::UNINDEXED;
10146 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
10147 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10148 : getVTList(MVT::Other);
10149 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
10151 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
10152 ID.AddInteger(MemVT.getRawBits());
10153 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
10154 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
10155 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10156 ID.AddInteger(MMO->getFlags());
10157 void *IP = nullptr;
10158 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10159 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
10160 return SDValue(E, 0);
10161 }
10162 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10163 IsTruncating, IsCompressing, MemVT, MMO);
10164 createOperands(N, Ops);
10165
10166 CSEMap.InsertNode(N, IP);
10167 InsertNode(N);
10168 SDValue V(N, 0);
10169 NewSDValueDbgMsg(V, "Creating new node: ", this);
10170 return V;
10171}
10172
10174 SDValue Val, SDValue Ptr, SDValue Mask,
10175 SDValue EVL, MachinePointerInfo PtrInfo,
10176 EVT SVT, Align Alignment,
10177 MachineMemOperand::Flags MMOFlags,
10178 const AAMDNodes &AAInfo,
10179 bool IsCompressing) {
10180 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10181
10182 MMOFlags |= MachineMemOperand::MOStore;
10183 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10184
10185 if (PtrInfo.V.isNull())
10186 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10187
10189 MachineMemOperand *MMO = MF.getMachineMemOperand(
10190 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
10191 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
10192 IsCompressing);
10193}
10194
10196 SDValue Val, SDValue Ptr, SDValue Mask,
10197 SDValue EVL, EVT SVT,
10198 MachineMemOperand *MMO,
10199 bool IsCompressing) {
10200 EVT VT = Val.getValueType();
10201
10202 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10203 if (VT == SVT)
10204 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
10205 EVL, VT, MMO, ISD::UNINDEXED,
10206 /*IsTruncating*/ false, IsCompressing);
10207
10209 "Should only be a truncating store, not extending!");
10210 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10211 assert(VT.isVector() == SVT.isVector() &&
10212 "Cannot use trunc store to convert to or from a vector!");
10213 assert((!VT.isVector() ||
10215 "Cannot use trunc store to change the number of vector elements!");
10216
10217 SDVTList VTs = getVTList(MVT::Other);
10218 SDValue Undef = getUNDEF(Ptr.getValueType());
10219 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
10221 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
10222 ID.AddInteger(SVT.getRawBits());
10223 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
10224 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
10225 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10226 ID.AddInteger(MMO->getFlags());
10227 void *IP = nullptr;
10228 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10229 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
10230 return SDValue(E, 0);
10231 }
10232 auto *N =
10233 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10234 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
10235 createOperands(N, Ops);
10236
10237 CSEMap.InsertNode(N, IP);
10238 InsertNode(N);
10239 SDValue V(N, 0);
10240 NewSDValueDbgMsg(V, "Creating new node: ", this);
10241 return V;
10242}
10243
10247 auto *ST = cast<VPStoreSDNode>(OrigStore);
10248 assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
10249 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
10250 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
10251 Offset, ST->getMask(), ST->getVectorLength()};
10253 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
10254 ID.AddInteger(ST->getMemoryVT().getRawBits());
10255 ID.AddInteger(ST->getRawSubclassData());
10256 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
10257 ID.AddInteger(ST->getMemOperand()->getFlags());
10258 void *IP = nullptr;
10259 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10260 return SDValue(E, 0);
10261
10262 auto *N = newSDNode<VPStoreSDNode>(
10263 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
10264 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
10265 createOperands(N, Ops);
10266
10267 CSEMap.InsertNode(N, IP);
10268 InsertNode(N);
10269 SDValue V(N, 0);
10270 NewSDValueDbgMsg(V, "Creating new node: ", this);
10271 return V;
10272}
10273
10275 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
10276 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
10277 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
10278 bool Indexed = AM != ISD::UNINDEXED;
10279 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
10280
10281 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
10282 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
10283 : getVTList(VT, MVT::Other);
10285 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
10286 ID.AddInteger(VT.getRawBits());
10287 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
10288 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
10289 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10290
10291 void *IP = nullptr;
10292 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10293 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
10294 return SDValue(E, 0);
10295 }
10296
10297 auto *N =
10298 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
10299 ExtType, IsExpanding, MemVT, MMO);
10300 createOperands(N, Ops);
10301 CSEMap.InsertNode(N, IP);
10302 InsertNode(N);
10303 SDValue V(N, 0);
10304 NewSDValueDbgMsg(V, "Creating new node: ", this);
10305 return V;
10306}
10307
10309 SDValue Ptr, SDValue Stride,
10310 SDValue Mask, SDValue EVL,
10311 MachineMemOperand *MMO,
10312 bool IsExpanding) {
10313 SDValue Undef = getUNDEF(Ptr.getValueType());
10314 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
10315 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
10316}
10317
10319 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
10320 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
10321 MachineMemOperand *MMO, bool IsExpanding) {
10322 SDValue Undef = getUNDEF(Ptr.getValueType());
10323 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
10324 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
10325}
10326
10328 SDValue Val, SDValue Ptr,
10329 SDValue Offset, SDValue Stride,
10330 SDValue Mask, SDValue EVL, EVT MemVT,
10331 MachineMemOperand *MMO,
10333 bool IsTruncating, bool IsCompressing) {
10334 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10335 bool Indexed = AM != ISD::UNINDEXED;
10336 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
10337 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10338 : getVTList(MVT::Other);
10339 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
10341 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
10342 ID.AddInteger(MemVT.getRawBits());
10343 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
10344 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
10345 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10346 void *IP = nullptr;
10347 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10348 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
10349 return SDValue(E, 0);
10350 }
10351 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
10352 VTs, AM, IsTruncating,
10353 IsCompressing, MemVT, MMO);
10354 createOperands(N, Ops);
10355
10356 CSEMap.InsertNode(N, IP);
10357 InsertNode(N);
10358 SDValue V(N, 0);
10359 NewSDValueDbgMsg(V, "Creating new node: ", this);
10360 return V;
10361}
10362
10364 SDValue Val, SDValue Ptr,
10365 SDValue Stride, SDValue Mask,
10366 SDValue EVL, EVT SVT,
10367 MachineMemOperand *MMO,
10368 bool IsCompressing) {
10369 EVT VT = Val.getValueType();
10370
10371 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10372 if (VT == SVT)
10373 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
10374 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
10375 /*IsTruncating*/ false, IsCompressing);
10376
10378 "Should only be a truncating store, not extending!");
10379 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10380 assert(VT.isVector() == SVT.isVector() &&
10381 "Cannot use trunc store to convert to or from a vector!");
10382 assert((!VT.isVector() ||
10384 "Cannot use trunc store to change the number of vector elements!");
10385
10386 SDVTList VTs = getVTList(MVT::Other);
10387 SDValue Undef = getUNDEF(Ptr.getValueType());
10388 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
10390 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
10391 ID.AddInteger(SVT.getRawBits());
10392 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
10393 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
10394 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10395 void *IP = nullptr;
10396 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10397 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
10398 return SDValue(E, 0);
10399 }
10400 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
10401 VTs, ISD::UNINDEXED, true,
10402 IsCompressing, SVT, MMO);
10403 createOperands(N, Ops);
10404
10405 CSEMap.InsertNode(N, IP);
10406 InsertNode(N);
10407 SDValue V(N, 0);
10408 NewSDValueDbgMsg(V, "Creating new node: ", this);
10409 return V;
10410}
10411
10414 ISD::MemIndexType IndexType) {
10415 assert(Ops.size() == 6 && "Incompatible number of operands");
10416
10418 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
10419 ID.AddInteger(VT.getRawBits());
10420 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
10421 dl.getIROrder(), VTs, VT, MMO, IndexType));
10422 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10423 ID.AddInteger(MMO->getFlags());
10424 void *IP = nullptr;
10425 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10426 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
10427 return SDValue(E, 0);
10428 }
10429
10430 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10431 VT, MMO, IndexType);
10432 createOperands(N, Ops);
10433
10434 assert(N->getMask().getValueType().getVectorElementCount() ==
10435 N->getValueType(0).getVectorElementCount() &&
10436 "Vector width mismatch between mask and data");
10437 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10438 N->getValueType(0).getVectorElementCount().isScalable() &&
10439 "Scalable flags of index and data do not match");
10441 N->getIndex().getValueType().getVectorElementCount(),
10442 N->getValueType(0).getVectorElementCount()) &&
10443 "Vector width mismatch between index and data");
10444 assert(isa<ConstantSDNode>(N->getScale()) &&
10445 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10446 "Scale should be a constant power of 2");
10447
10448 CSEMap.InsertNode(N, IP);
10449 InsertNode(N);
10450 SDValue V(N, 0);
10451 NewSDValueDbgMsg(V, "Creating new node: ", this);
10452 return V;
10453}
10454
10457 MachineMemOperand *MMO,
10458 ISD::MemIndexType IndexType) {
10459 assert(Ops.size() == 7 && "Incompatible number of operands");
10460
10462 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
10463 ID.AddInteger(VT.getRawBits());
10464 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
10465 dl.getIROrder(), VTs, VT, MMO, IndexType));
10466 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10467 ID.AddInteger(MMO->getFlags());
10468 void *IP = nullptr;
10469 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10470 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
10471 return SDValue(E, 0);
10472 }
10473 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10474 VT, MMO, IndexType);
10475 createOperands(N, Ops);
10476
10477 assert(N->getMask().getValueType().getVectorElementCount() ==
10478 N->getValue().getValueType().getVectorElementCount() &&
10479 "Vector width mismatch between mask and data");
10480 assert(
10481 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10482 N->getValue().getValueType().getVectorElementCount().isScalable() &&
10483 "Scalable flags of index and data do not match");
10485 N->getIndex().getValueType().getVectorElementCount(),
10486 N->getValue().getValueType().getVectorElementCount()) &&
10487 "Vector width mismatch between index and data");
10488 assert(isa<ConstantSDNode>(N->getScale()) &&
10489 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10490 "Scale should be a constant power of 2");
10491
10492 CSEMap.InsertNode(N, IP);
10493 InsertNode(N);
10494 SDValue V(N, 0);
10495 NewSDValueDbgMsg(V, "Creating new node: ", this);
10496 return V;
10497}
10498
10501 SDValue PassThru, EVT MemVT,
10502 MachineMemOperand *MMO,
10504 ISD::LoadExtType ExtTy, bool isExpanding) {
10505 bool Indexed = AM != ISD::UNINDEXED;
10506 assert((Indexed || Offset.isUndef()) &&
10507 "Unindexed masked load with an offset!");
10508 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
10509 : getVTList(VT, MVT::Other);
10510 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
10513 ID.AddInteger(MemVT.getRawBits());
10514 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
10515 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
10516 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10517 ID.AddInteger(MMO->getFlags());
10518 void *IP = nullptr;
10519 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10520 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
10521 return SDValue(E, 0);
10522 }
10523 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10524 AM, ExtTy, isExpanding, MemVT, MMO);
10525 createOperands(N, Ops);
10526
10527 CSEMap.InsertNode(N, IP);
10528 InsertNode(N);
10529 SDValue V(N, 0);
10530 NewSDValueDbgMsg(V, "Creating new node: ", this);
10531 return V;
10532}
10533
10538 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
10539 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
10540 Offset, LD->getMask(), LD->getPassThru(),
10541 LD->getMemoryVT(), LD->getMemOperand(), AM,
10542 LD->getExtensionType(), LD->isExpandingLoad());
10543}
10544
10547 SDValue Mask, EVT MemVT,
10548 MachineMemOperand *MMO,
10549 ISD::MemIndexedMode AM, bool IsTruncating,
10550 bool IsCompressing) {
10551 assert(Chain.getValueType() == MVT::Other &&
10552 "Invalid chain type");
10553 bool Indexed = AM != ISD::UNINDEXED;
10554 assert((Indexed || Offset.isUndef()) &&
10555 "Unindexed masked store with an offset!");
10556 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
10557 : getVTList(MVT::Other);
10558 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
10561 ID.AddInteger(MemVT.getRawBits());
10562 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
10563 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
10564 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10565 ID.AddInteger(MMO->getFlags());
10566 void *IP = nullptr;
10567 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10568 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
10569 return SDValue(E, 0);
10570 }
10571 auto *N =
10572 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10573 IsTruncating, IsCompressing, MemVT, MMO);
10574 createOperands(N, Ops);
10575
10576 CSEMap.InsertNode(N, IP);
10577 InsertNode(N);
10578 SDValue V(N, 0);
10579 NewSDValueDbgMsg(V, "Creating new node: ", this);
10580 return V;
10581}
10582
10587 assert(ST->getOffset().isUndef() &&
10588 "Masked store is already a indexed store!");
10589 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10590 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
10591 AM, ST->isTruncatingStore(), ST->isCompressingStore());
10592}
10593
10596 MachineMemOperand *MMO,
10597 ISD::MemIndexType IndexType,
10598 ISD::LoadExtType ExtTy) {
10599 assert(Ops.size() == 6 && "Incompatible number of operands");
10600
10603 ID.AddInteger(MemVT.getRawBits());
10604 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
10605 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
10606 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10607 ID.AddInteger(MMO->getFlags());
10608 void *IP = nullptr;
10609 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10610 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
10611 return SDValue(E, 0);
10612 }
10613
10614 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
10615 VTs, MemVT, MMO, IndexType, ExtTy);
10616 createOperands(N, Ops);
10617
10618 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
10619 "Incompatible type of the PassThru value in MaskedGatherSDNode");
10620 assert(N->getMask().getValueType().getVectorElementCount() ==
10621 N->getValueType(0).getVectorElementCount() &&
10622 "Vector width mismatch between mask and data");
10623 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10624 N->getValueType(0).getVectorElementCount().isScalable() &&
10625 "Scalable flags of index and data do not match");
10627 N->getIndex().getValueType().getVectorElementCount(),
10628 N->getValueType(0).getVectorElementCount()) &&
10629 "Vector width mismatch between index and data");
10630 assert(isa<ConstantSDNode>(N->getScale()) &&
10631 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10632 "Scale should be a constant power of 2");
10633
10634 CSEMap.InsertNode(N, IP);
10635 InsertNode(N);
10636 SDValue V(N, 0);
10637 NewSDValueDbgMsg(V, "Creating new node: ", this);
10638 return V;
10639}
10640
10643 MachineMemOperand *MMO,
10644 ISD::MemIndexType IndexType,
10645 bool IsTrunc) {
10646 assert(Ops.size() == 6 && "Incompatible number of operands");
10647
10650 ID.AddInteger(MemVT.getRawBits());
10651 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
10652 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
10653 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10654 ID.AddInteger(MMO->getFlags());
10655 void *IP = nullptr;
10656 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10657 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
10658 return SDValue(E, 0);
10659 }
10660
10661 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
10662 VTs, MemVT, MMO, IndexType, IsTrunc);
10663 createOperands(N, Ops);
10664
10665 assert(N->getMask().getValueType().getVectorElementCount() ==
10666 N->getValue().getValueType().getVectorElementCount() &&
10667 "Vector width mismatch between mask and data");
10668 assert(
10669 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10670 N->getValue().getValueType().getVectorElementCount().isScalable() &&
10671 "Scalable flags of index and data do not match");
10673 N->getIndex().getValueType().getVectorElementCount(),
10674 N->getValue().getValueType().getVectorElementCount()) &&
10675 "Vector width mismatch between index and data");
10676 assert(isa<ConstantSDNode>(N->getScale()) &&
10677 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10678 "Scale should be a constant power of 2");
10679
10680 CSEMap.InsertNode(N, IP);
10681 InsertNode(N);
10682 SDValue V(N, 0);
10683 NewSDValueDbgMsg(V, "Creating new node: ", this);
10684 return V;
10685}
10686
10688 const SDLoc &dl, ArrayRef<SDValue> Ops,
10689 MachineMemOperand *MMO,
10690 ISD::MemIndexType IndexType) {
10691 assert(Ops.size() == 7 && "Incompatible number of operands");
10692
10695 ID.AddInteger(MemVT.getRawBits());
10696 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
10697 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
10698 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10699 ID.AddInteger(MMO->getFlags());
10700 void *IP = nullptr;
10701 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10702 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
10703 return SDValue(E, 0);
10704 }
10705
10706 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
10707 VTs, MemVT, MMO, IndexType);
10708 createOperands(N, Ops);
10709
10710 assert(N->getMask().getValueType().getVectorElementCount() ==
10711 N->getIndex().getValueType().getVectorElementCount() &&
10712 "Vector width mismatch between mask and data");
10713 assert(isa<ConstantSDNode>(N->getScale()) &&
10714 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10715 "Scale should be a constant power of 2");
10716 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
10717
10718 CSEMap.InsertNode(N, IP);
10719 InsertNode(N);
10720 SDValue V(N, 0);
10721 NewSDValueDbgMsg(V, "Creating new node: ", this);
10722 return V;
10723}
10724
10726 SDValue Ptr, SDValue Mask, SDValue EVL,
10727 MachineMemOperand *MMO) {
10728 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
10729 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
10731 AddNodeIDNode(ID, ISD::VP_LOAD_FF, VTs, Ops);
10732 ID.AddInteger(VT.getRawBits());
10733 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
10734 VTs, VT, MMO));
10735 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10736 ID.AddInteger(MMO->getFlags());
10737 void *IP = nullptr;
10738 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10739 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
10740 return SDValue(E, 0);
10741 }
10742 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
10743 VT, MMO);
10744 createOperands(N, Ops);
10745
10746 CSEMap.InsertNode(N, IP);
10747 InsertNode(N);
10748 SDValue V(N, 0);
10749 NewSDValueDbgMsg(V, "Creating new node: ", this);
10750 return V;
10751}
10752
10754 EVT MemVT, MachineMemOperand *MMO) {
10755 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10756 SDVTList VTs = getVTList(MVT::Other);
10757 SDValue Ops[] = {Chain, Ptr};
10760 ID.AddInteger(MemVT.getRawBits());
10761 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
10762 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
10763 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10764 ID.AddInteger(MMO->getFlags());
10765 void *IP = nullptr;
10766 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10767 return SDValue(E, 0);
10768
10769 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
10770 dl.getDebugLoc(), VTs, MemVT, MMO);
10771 createOperands(N, Ops);
10772
10773 CSEMap.InsertNode(N, IP);
10774 InsertNode(N);
10775 SDValue V(N, 0);
10776 NewSDValueDbgMsg(V, "Creating new node: ", this);
10777 return V;
10778}
10779
10781 EVT MemVT, MachineMemOperand *MMO) {
10782 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10783 SDVTList VTs = getVTList(MVT::Other);
10784 SDValue Ops[] = {Chain, Ptr};
10787 ID.AddInteger(MemVT.getRawBits());
10788 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
10789 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
10790 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10791 ID.AddInteger(MMO->getFlags());
10792 void *IP = nullptr;
10793 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10794 return SDValue(E, 0);
10795
10796 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
10797 dl.getDebugLoc(), VTs, MemVT, MMO);
10798 createOperands(N, Ops);
10799
10800 CSEMap.InsertNode(N, IP);
10801 InsertNode(N);
10802 SDValue V(N, 0);
10803 NewSDValueDbgMsg(V, "Creating new node: ", this);
10804 return V;
10805}
10806
10808 // select undef, T, F --> T (if T is a constant), otherwise F
10809 // select, ?, undef, F --> F
10810 // select, ?, T, undef --> T
10811 if (Cond.isUndef())
10812 return isConstantValueOfAnyType(T) ? T : F;
10813 if (T.isUndef())
10814 return F;
10815 if (F.isUndef())
10816 return T;
10817
10818 // select true, T, F --> T
10819 // select false, T, F --> F
10820 if (auto C = isBoolConstant(Cond))
10821 return *C ? T : F;
10822
10823 // select ?, T, T --> T
10824 if (T == F)
10825 return T;
10826
10827 return SDValue();
10828}
10829
10831 // shift undef, Y --> 0 (can always assume that the undef value is 0)
10832 if (X.isUndef())
10833 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
10834 // shift X, undef --> undef (because it may shift by the bitwidth)
10835 if (Y.isUndef())
10836 return getUNDEF(X.getValueType());
10837
10838 // shift 0, Y --> 0
10839 // shift X, 0 --> X
10841 return X;
10842
10843 // shift X, C >= bitwidth(X) --> undef
10844 // All vector elements must be too big (or undef) to avoid partial undefs.
10845 auto isShiftTooBig = [X](ConstantSDNode *Val) {
10846 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
10847 };
10848 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
10849 return getUNDEF(X.getValueType());
10850
10851 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
10852 if (X.getValueType().getScalarType() == MVT::i1)
10853 return X;
10854
10855 return SDValue();
10856}
10857
10859 SDNodeFlags Flags) {
10860 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
10861 // (an undef operand can be chosen to be Nan/Inf), then the result of this
10862 // operation is poison. That result can be relaxed to undef.
10863 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
10864 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
10865 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
10866 (YC && YC->getValueAPF().isNaN());
10867 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
10868 (YC && YC->getValueAPF().isInfinity());
10869
10870 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
10871 return getUNDEF(X.getValueType());
10872
10873 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
10874 return getUNDEF(X.getValueType());
10875
10876 if (!YC)
10877 return SDValue();
10878
10879 // X + -0.0 --> X
10880 if (Opcode == ISD::FADD)
10881 if (YC->getValueAPF().isNegZero())
10882 return X;
10883
10884 // X - +0.0 --> X
10885 if (Opcode == ISD::FSUB)
10886 if (YC->getValueAPF().isPosZero())
10887 return X;
10888
10889 // X * 1.0 --> X
10890 // X / 1.0 --> X
10891 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
10892 if (YC->getValueAPF().isExactlyValue(1.0))
10893 return X;
10894
10895 // X * 0.0 --> 0.0
10896 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
10897 if (YC->getValueAPF().isZero())
10898 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
10899
10900 return SDValue();
10901}
10902
10904 SDValue Ptr, SDValue SV, unsigned Align) {
10905 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
10906 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
10907}
10908
10909SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
10911 switch (Ops.size()) {
10912 case 0: return getNode(Opcode, DL, VT);
10913 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
10914 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
10915 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
10916 default: break;
10917 }
10918
10919 // Copy from an SDUse array into an SDValue array for use with
10920 // the regular getNode logic.
10922 return getNode(Opcode, DL, VT, NewOps);
10923}
10924
10925SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
10927 SDNodeFlags Flags;
10928 if (Inserter)
10929 Flags = Inserter->getFlags();
10930 return getNode(Opcode, DL, VT, Ops, Flags);
10931}
10932
10933SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
10934 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
10935 unsigned NumOps = Ops.size();
10936 switch (NumOps) {
10937 case 0: return getNode(Opcode, DL, VT);
10938 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
10939 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
10940 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
10941 default: break;
10942 }
10943
10944#ifndef NDEBUG
10945 for (const auto &Op : Ops)
10946 assert(Op.getOpcode() != ISD::DELETED_NODE &&
10947 "Operand is DELETED_NODE!");
10948#endif
10949
10950 switch (Opcode) {
10951 default: break;
10952 case ISD::BUILD_VECTOR:
10953 // Attempt to simplify BUILD_VECTOR.
10954 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
10955 return V;
10956 break;
10958 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
10959 return V;
10960 break;
10961 case ISD::SELECT_CC:
10962 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
10963 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
10964 "LHS and RHS of condition must have same type!");
10965 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
10966 "True and False arms of SelectCC must have same type!");
10967 assert(Ops[2].getValueType() == VT &&
10968 "select_cc node must be of same type as true and false value!");
10969 assert((!Ops[0].getValueType().isVector() ||
10970 Ops[0].getValueType().getVectorElementCount() ==
10971 VT.getVectorElementCount()) &&
10972 "Expected select_cc with vector result to have the same sized "
10973 "comparison type!");
10974 break;
10975 case ISD::BR_CC:
10976 assert(NumOps == 5 && "BR_CC takes 5 operands!");
10977 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
10978 "LHS/RHS of comparison should match types!");
10979 break;
10980 case ISD::VP_ADD:
10981 case ISD::VP_SUB:
10982 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
10983 if (VT.getScalarType() == MVT::i1)
10984 Opcode = ISD::VP_XOR;
10985 break;
10986 case ISD::VP_MUL:
10987 // If it is VP_MUL mask operation then turn it to VP_AND
10988 if (VT.getScalarType() == MVT::i1)
10989 Opcode = ISD::VP_AND;
10990 break;
10991 case ISD::VP_REDUCE_MUL:
10992 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
10993 if (VT == MVT::i1)
10994 Opcode = ISD::VP_REDUCE_AND;
10995 break;
10996 case ISD::VP_REDUCE_ADD:
10997 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
10998 if (VT == MVT::i1)
10999 Opcode = ISD::VP_REDUCE_XOR;
11000 break;
11001 case ISD::VP_REDUCE_SMAX:
11002 case ISD::VP_REDUCE_UMIN:
11003 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
11004 // VP_REDUCE_AND.
11005 if (VT == MVT::i1)
11006 Opcode = ISD::VP_REDUCE_AND;
11007 break;
11008 case ISD::VP_REDUCE_SMIN:
11009 case ISD::VP_REDUCE_UMAX:
11010 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
11011 // VP_REDUCE_OR.
11012 if (VT == MVT::i1)
11013 Opcode = ISD::VP_REDUCE_OR;
11014 break;
11015 }
11016
11017 // Memoize nodes.
11018 SDNode *N;
11019 SDVTList VTs = getVTList(VT);
11020
11021 if (VT != MVT::Glue) {
11023 AddNodeIDNode(ID, Opcode, VTs, Ops);
11024 void *IP = nullptr;
11025
11026 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11027 E->intersectFlagsWith(Flags);
11028 return SDValue(E, 0);
11029 }
11030
11031 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11032 createOperands(N, Ops);
11033
11034 CSEMap.InsertNode(N, IP);
11035 } else {
11036 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11037 createOperands(N, Ops);
11038 }
11039
11040 N->setFlags(Flags);
11041 InsertNode(N);
11042 SDValue V(N, 0);
11043 NewSDValueDbgMsg(V, "Creating new node: ", this);
11044 return V;
11045}
11046
11047SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11048 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
11049 SDNodeFlags Flags;
11050 if (Inserter)
11051 Flags = Inserter->getFlags();
11052 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11053}
11054
11055SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11057 const SDNodeFlags Flags) {
11058 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11059}
11060
11061SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11063 SDNodeFlags Flags;
11064 if (Inserter)
11065 Flags = Inserter->getFlags();
11066 return getNode(Opcode, DL, VTList, Ops, Flags);
11067}
11068
11069SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11070 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11071 if (VTList.NumVTs == 1)
11072 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
11073
11074#ifndef NDEBUG
11075 for (const auto &Op : Ops)
11076 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11077 "Operand is DELETED_NODE!");
11078#endif
11079
11080 switch (Opcode) {
11081 case ISD::SADDO:
11082 case ISD::UADDO:
11083 case ISD::SSUBO:
11084 case ISD::USUBO: {
11085 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
11086 "Invalid add/sub overflow op!");
11087 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
11088 Ops[0].getValueType() == Ops[1].getValueType() &&
11089 Ops[0].getValueType() == VTList.VTs[0] &&
11090 "Binary operator types must match!");
11091 SDValue N1 = Ops[0], N2 = Ops[1];
11092 canonicalizeCommutativeBinop(Opcode, N1, N2);
11093
11094 // (X +- 0) -> X with zero-overflow.
11095 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
11096 /*AllowTruncation*/ true);
11097 if (N2CV && N2CV->isZero()) {
11098 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
11099 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
11100 }
11101
11102 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
11103 VTList.VTs[1].getScalarType() == MVT::i1) {
11104 SDValue F1 = getFreeze(N1);
11105 SDValue F2 = getFreeze(N2);
11106 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
11107 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
11108 return getNode(ISD::MERGE_VALUES, DL, VTList,
11109 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
11110 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
11111 Flags);
11112 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
11113 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
11114 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
11115 return getNode(ISD::MERGE_VALUES, DL, VTList,
11116 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
11117 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
11118 Flags);
11119 }
11120 }
11121 break;
11122 }
11123 case ISD::SADDO_CARRY:
11124 case ISD::UADDO_CARRY:
11125 case ISD::SSUBO_CARRY:
11126 case ISD::USUBO_CARRY:
11127 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
11128 "Invalid add/sub overflow op!");
11129 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
11130 Ops[0].getValueType() == Ops[1].getValueType() &&
11131 Ops[0].getValueType() == VTList.VTs[0] &&
11132 Ops[2].getValueType() == VTList.VTs[1] &&
11133 "Binary operator types must match!");
11134 break;
11135 case ISD::SMUL_LOHI:
11136 case ISD::UMUL_LOHI: {
11137 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
11138 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
11139 VTList.VTs[0] == Ops[0].getValueType() &&
11140 VTList.VTs[0] == Ops[1].getValueType() &&
11141 "Binary operator types must match!");
11142 // Constant fold.
11145 if (LHS && RHS) {
11146 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
11147 unsigned OutWidth = Width * 2;
11148 APInt Val = LHS->getAPIntValue();
11149 APInt Mul = RHS->getAPIntValue();
11150 if (Opcode == ISD::SMUL_LOHI) {
11151 Val = Val.sext(OutWidth);
11152 Mul = Mul.sext(OutWidth);
11153 } else {
11154 Val = Val.zext(OutWidth);
11155 Mul = Mul.zext(OutWidth);
11156 }
11157 Val *= Mul;
11158
11159 SDValue Hi =
11160 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
11161 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
11162 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
11163 }
11164 break;
11165 }
11166 case ISD::FFREXP: {
11167 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
11168 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
11169 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
11170
11172 int FrexpExp;
11173 APFloat FrexpMant =
11174 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
11175 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
11176 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
11177 DL, VTList.VTs[1]);
11178 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
11179 }
11180
11181 break;
11182 }
11184 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
11185 "Invalid STRICT_FP_EXTEND!");
11186 assert(VTList.VTs[0].isFloatingPoint() &&
11187 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
11188 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
11189 "STRICT_FP_EXTEND result type should be vector iff the operand "
11190 "type is vector!");
11191 assert((!VTList.VTs[0].isVector() ||
11192 VTList.VTs[0].getVectorElementCount() ==
11193 Ops[1].getValueType().getVectorElementCount()) &&
11194 "Vector element count mismatch!");
11195 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
11196 "Invalid fpext node, dst <= src!");
11197 break;
11199 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
11200 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
11201 "STRICT_FP_ROUND result type should be vector iff the operand "
11202 "type is vector!");
11203 assert((!VTList.VTs[0].isVector() ||
11204 VTList.VTs[0].getVectorElementCount() ==
11205 Ops[1].getValueType().getVectorElementCount()) &&
11206 "Vector element count mismatch!");
11207 assert(VTList.VTs[0].isFloatingPoint() &&
11208 Ops[1].getValueType().isFloatingPoint() &&
11209 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
11210 Ops[2].getOpcode() == ISD::TargetConstant &&
11211 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
11212 "Invalid STRICT_FP_ROUND!");
11213 break;
11214 }
11215
11216 // Memoize the node unless it returns a glue result.
11217 SDNode *N;
11218 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
11220 AddNodeIDNode(ID, Opcode, VTList, Ops);
11221 void *IP = nullptr;
11222 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11223 E->intersectFlagsWith(Flags);
11224 return SDValue(E, 0);
11225 }
11226
11227 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
11228 createOperands(N, Ops);
11229 CSEMap.InsertNode(N, IP);
11230 } else {
11231 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
11232 createOperands(N, Ops);
11233 }
11234
11235 N->setFlags(Flags);
11236 InsertNode(N);
11237 SDValue V(N, 0);
11238 NewSDValueDbgMsg(V, "Creating new node: ", this);
11239 return V;
11240}
11241
11242SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11243 SDVTList VTList) {
11244 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
11245}
11246
11247SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11248 SDValue N1) {
11249 SDValue Ops[] = { N1 };
11250 return getNode(Opcode, DL, VTList, Ops);
11251}
11252
11253SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11254 SDValue N1, SDValue N2) {
11255 SDValue Ops[] = { N1, N2 };
11256 return getNode(Opcode, DL, VTList, Ops);
11257}
11258
11259SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11260 SDValue N1, SDValue N2, SDValue N3) {
11261 SDValue Ops[] = { N1, N2, N3 };
11262 return getNode(Opcode, DL, VTList, Ops);
11263}
11264
11265SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11266 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
11267 SDValue Ops[] = { N1, N2, N3, N4 };
11268 return getNode(Opcode, DL, VTList, Ops);
11269}
11270
11271SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11272 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
11273 SDValue N5) {
11274 SDValue Ops[] = { N1, N2, N3, N4, N5 };
11275 return getNode(Opcode, DL, VTList, Ops);
11276}
11277
11279 if (!VT.isExtended())
11280 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
11281
11282 return makeVTList(&(*EVTs.insert(VT).first), 1);
11283}
11284
11287 ID.AddInteger(2U);
11288 ID.AddInteger(VT1.getRawBits());
11289 ID.AddInteger(VT2.getRawBits());
11290
11291 void *IP = nullptr;
11292 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11293 if (!Result) {
11294 EVT *Array = Allocator.Allocate<EVT>(2);
11295 Array[0] = VT1;
11296 Array[1] = VT2;
11297 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
11298 VTListMap.InsertNode(Result, IP);
11299 }
11300 return Result->getSDVTList();
11301}
11302
11305 ID.AddInteger(3U);
11306 ID.AddInteger(VT1.getRawBits());
11307 ID.AddInteger(VT2.getRawBits());
11308 ID.AddInteger(VT3.getRawBits());
11309
11310 void *IP = nullptr;
11311 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11312 if (!Result) {
11313 EVT *Array = Allocator.Allocate<EVT>(3);
11314 Array[0] = VT1;
11315 Array[1] = VT2;
11316 Array[2] = VT3;
11317 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
11318 VTListMap.InsertNode(Result, IP);
11319 }
11320 return Result->getSDVTList();
11321}
11322
11325 ID.AddInteger(4U);
11326 ID.AddInteger(VT1.getRawBits());
11327 ID.AddInteger(VT2.getRawBits());
11328 ID.AddInteger(VT3.getRawBits());
11329 ID.AddInteger(VT4.getRawBits());
11330
11331 void *IP = nullptr;
11332 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11333 if (!Result) {
11334 EVT *Array = Allocator.Allocate<EVT>(4);
11335 Array[0] = VT1;
11336 Array[1] = VT2;
11337 Array[2] = VT3;
11338 Array[3] = VT4;
11339 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
11340 VTListMap.InsertNode(Result, IP);
11341 }
11342 return Result->getSDVTList();
11343}
11344
11346 unsigned NumVTs = VTs.size();
11348 ID.AddInteger(NumVTs);
11349 for (unsigned index = 0; index < NumVTs; index++) {
11350 ID.AddInteger(VTs[index].getRawBits());
11351 }
11352
11353 void *IP = nullptr;
11354 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11355 if (!Result) {
11356 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
11357 llvm::copy(VTs, Array);
11358 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
11359 VTListMap.InsertNode(Result, IP);
11360 }
11361 return Result->getSDVTList();
11362}
11363
11364
11365/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
11366/// specified operands. If the resultant node already exists in the DAG,
11367/// this does not modify the specified node, instead it returns the node that
11368/// already exists. If the resultant node does not exist in the DAG, the
11369/// input node is returned. As a degenerate case, if you specify the same
11370/// input operands as the node already has, the input node is returned.
11372 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
11373
11374 // Check to see if there is no change.
11375 if (Op == N->getOperand(0)) return N;
11376
11377 // See if the modified node already exists.
11378 void *InsertPos = nullptr;
11379 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
11380 return Existing;
11381
11382 // Nope it doesn't. Remove the node from its current place in the maps.
11383 if (InsertPos)
11384 if (!RemoveNodeFromCSEMaps(N))
11385 InsertPos = nullptr;
11386
11387 // Now we update the operands.
11388 N->OperandList[0].set(Op);
11389
11391 // If this gets put into a CSE map, add it.
11392 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
11393 return N;
11394}
11395
11397 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
11398
11399 // Check to see if there is no change.
11400 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
11401 return N; // No operands changed, just return the input node.
11402
11403 // See if the modified node already exists.
11404 void *InsertPos = nullptr;
11405 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
11406 return Existing;
11407
11408 // Nope it doesn't. Remove the node from its current place in the maps.
11409 if (InsertPos)
11410 if (!RemoveNodeFromCSEMaps(N))
11411 InsertPos = nullptr;
11412
11413 // Now we update the operands.
11414 if (N->OperandList[0] != Op1)
11415 N->OperandList[0].set(Op1);
11416 if (N->OperandList[1] != Op2)
11417 N->OperandList[1].set(Op2);
11418
11420 // If this gets put into a CSE map, add it.
11421 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
11422 return N;
11423}
11424
11427 SDValue Ops[] = { Op1, Op2, Op3 };
11428 return UpdateNodeOperands(N, Ops);
11429}
11430
11433 SDValue Op3, SDValue Op4) {
11434 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
11435 return UpdateNodeOperands(N, Ops);
11436}
11437
11440 SDValue Op3, SDValue Op4, SDValue Op5) {
11441 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
11442 return UpdateNodeOperands(N, Ops);
11443}
11444
11447 unsigned NumOps = Ops.size();
11448 assert(N->getNumOperands() == NumOps &&
11449 "Update with wrong number of operands");
11450
11451 // If no operands changed just return the input node.
11452 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
11453 return N;
11454
11455 // See if the modified node already exists.
11456 void *InsertPos = nullptr;
11457 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
11458 return Existing;
11459
11460 // Nope it doesn't. Remove the node from its current place in the maps.
11461 if (InsertPos)
11462 if (!RemoveNodeFromCSEMaps(N))
11463 InsertPos = nullptr;
11464
11465 // Now we update the operands.
11466 for (unsigned i = 0; i != NumOps; ++i)
11467 if (N->OperandList[i] != Ops[i])
11468 N->OperandList[i].set(Ops[i]);
11469
11471 // If this gets put into a CSE map, add it.
11472 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
11473 return N;
11474}
11475
11476/// DropOperands - Release the operands and set this node to have
11477/// zero operands.
11479 // Unlike the code in MorphNodeTo that does this, we don't need to
11480 // watch for dead nodes here.
11481 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
11482 SDUse &Use = *I++;
11483 Use.set(SDValue());
11484 }
11485}
11486
11488 ArrayRef<MachineMemOperand *> NewMemRefs) {
11489 if (NewMemRefs.empty()) {
11490 N->clearMemRefs();
11491 return;
11492 }
11493
11494 // Check if we can avoid allocating by storing a single reference directly.
11495 if (NewMemRefs.size() == 1) {
11496 N->MemRefs = NewMemRefs[0];
11497 N->NumMemRefs = 1;
11498 return;
11499 }
11500
11501 MachineMemOperand **MemRefsBuffer =
11502 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
11503 llvm::copy(NewMemRefs, MemRefsBuffer);
11504 N->MemRefs = MemRefsBuffer;
11505 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
11506}
11507
11508/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
11509/// machine opcode.
11510///
11512 EVT VT) {
11513 SDVTList VTs = getVTList(VT);
11514 return SelectNodeTo(N, MachineOpc, VTs, {});
11515}
11516
11518 EVT VT, SDValue Op1) {
11519 SDVTList VTs = getVTList(VT);
11520 SDValue Ops[] = { Op1 };
11521 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11522}
11523
11525 EVT VT, SDValue Op1,
11526 SDValue Op2) {
11527 SDVTList VTs = getVTList(VT);
11528 SDValue Ops[] = { Op1, Op2 };
11529 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11530}
11531
11533 EVT VT, SDValue Op1,
11534 SDValue Op2, SDValue Op3) {
11535 SDVTList VTs = getVTList(VT);
11536 SDValue Ops[] = { Op1, Op2, Op3 };
11537 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11538}
11539
11542 SDVTList VTs = getVTList(VT);
11543 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11544}
11545
11547 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
11548 SDVTList VTs = getVTList(VT1, VT2);
11549 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11550}
11551
11553 EVT VT1, EVT VT2) {
11554 SDVTList VTs = getVTList(VT1, VT2);
11555 return SelectNodeTo(N, MachineOpc, VTs, {});
11556}
11557
11559 EVT VT1, EVT VT2, EVT VT3,
11561 SDVTList VTs = getVTList(VT1, VT2, VT3);
11562 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11563}
11564
11566 EVT VT1, EVT VT2,
11567 SDValue Op1, SDValue Op2) {
11568 SDVTList VTs = getVTList(VT1, VT2);
11569 SDValue Ops[] = { Op1, Op2 };
11570 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11571}
11572
11575 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
11576 // Reset the NodeID to -1.
11577 New->setNodeId(-1);
11578 if (New != N) {
11579 ReplaceAllUsesWith(N, New);
11581 }
11582 return New;
11583}
11584
11585/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
11586/// the line number information on the merged node since it is not possible to
11587/// preserve the information that operation is associated with multiple lines.
11588/// This will make the debugger working better at -O0, were there is a higher
11589/// probability having other instructions associated with that line.
11590///
11591/// For IROrder, we keep the smaller of the two
11592SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
11593 DebugLoc NLoc = N->getDebugLoc();
11594 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
11595 N->setDebugLoc(DebugLoc());
11596 }
11597 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
11598 N->setIROrder(Order);
11599 return N;
11600}
11601
11602/// MorphNodeTo - This *mutates* the specified node to have the specified
11603/// return type, opcode, and operands.
11604///
11605/// Note that MorphNodeTo returns the resultant node. If there is already a
11606/// node of the specified opcode and operands, it returns that node instead of
11607/// the current one. Note that the SDLoc need not be the same.
11608///
11609/// Using MorphNodeTo is faster than creating a new node and swapping it in
11610/// with ReplaceAllUsesWith both because it often avoids allocating a new
11611/// node, and because it doesn't require CSE recalculation for any of
11612/// the node's users.
11613///
11614/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
11615/// As a consequence it isn't appropriate to use from within the DAG combiner or
11616/// the legalizer which maintain worklists that would need to be updated when
11617/// deleting things.
11620 // If an identical node already exists, use it.
11621 void *IP = nullptr;
11622 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
11624 AddNodeIDNode(ID, Opc, VTs, Ops);
11625 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
11626 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
11627 }
11628
11629 if (!RemoveNodeFromCSEMaps(N))
11630 IP = nullptr;
11631
11632 // Start the morphing.
11633 N->NodeType = Opc;
11634 N->ValueList = VTs.VTs;
11635 N->NumValues = VTs.NumVTs;
11636
11637 // Clear the operands list, updating used nodes to remove this from their
11638 // use list. Keep track of any operands that become dead as a result.
11639 SmallPtrSet<SDNode*, 16> DeadNodeSet;
11640 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
11641 SDUse &Use = *I++;
11642 SDNode *Used = Use.getNode();
11643 Use.set(SDValue());
11644 if (Used->use_empty())
11645 DeadNodeSet.insert(Used);
11646 }
11647
11648 // For MachineNode, initialize the memory references information.
11650 MN->clearMemRefs();
11651
11652 // Swap for an appropriately sized array from the recycler.
11653 removeOperands(N);
11654 createOperands(N, Ops);
11655
11656 // Delete any nodes that are still dead after adding the uses for the
11657 // new operands.
11658 if (!DeadNodeSet.empty()) {
11659 SmallVector<SDNode *, 16> DeadNodes;
11660 for (SDNode *N : DeadNodeSet)
11661 if (N->use_empty())
11662 DeadNodes.push_back(N);
11663 RemoveDeadNodes(DeadNodes);
11664 }
11665
11666 if (IP)
11667 CSEMap.InsertNode(N, IP); // Memoize the new node.
11668 return N;
11669}
11670
11672 unsigned OrigOpc = Node->getOpcode();
11673 unsigned NewOpc;
11674 switch (OrigOpc) {
11675 default:
11676 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
11677#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
11678 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
11679#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
11680 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
11681#include "llvm/IR/ConstrainedOps.def"
11682 }
11683
11684 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
11685
11686 // We're taking this node out of the chain, so we need to re-link things.
11687 SDValue InputChain = Node->getOperand(0);
11688 SDValue OutputChain = SDValue(Node, 1);
11689 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
11690
11692 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
11693 Ops.push_back(Node->getOperand(i));
11694
11695 SDVTList VTs = getVTList(Node->getValueType(0));
11696 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
11697
11698 // MorphNodeTo can operate in two ways: if an existing node with the
11699 // specified operands exists, it can just return it. Otherwise, it
11700 // updates the node in place to have the requested operands.
11701 if (Res == Node) {
11702 // If we updated the node in place, reset the node ID. To the isel,
11703 // this should be just like a newly allocated machine node.
11704 Res->setNodeId(-1);
11705 } else {
11708 }
11709
11710 return Res;
11711}
11712
11713/// getMachineNode - These are used for target selectors to create a new node
11714/// with specified return type(s), MachineInstr opcode, and operands.
11715///
11716/// Note that getMachineNode returns the resultant node. If there is already a
11717/// node of the specified opcode and operands, it returns that node instead of
11718/// the current one.
11720 EVT VT) {
11721 SDVTList VTs = getVTList(VT);
11722 return getMachineNode(Opcode, dl, VTs, {});
11723}
11724
11726 EVT VT, SDValue Op1) {
11727 SDVTList VTs = getVTList(VT);
11728 SDValue Ops[] = { Op1 };
11729 return getMachineNode(Opcode, dl, VTs, Ops);
11730}
11731
11733 EVT VT, SDValue Op1, SDValue Op2) {
11734 SDVTList VTs = getVTList(VT);
11735 SDValue Ops[] = { Op1, Op2 };
11736 return getMachineNode(Opcode, dl, VTs, Ops);
11737}
11738
11740 EVT VT, SDValue Op1, SDValue Op2,
11741 SDValue Op3) {
11742 SDVTList VTs = getVTList(VT);
11743 SDValue Ops[] = { Op1, Op2, Op3 };
11744 return getMachineNode(Opcode, dl, VTs, Ops);
11745}
11746
11749 SDVTList VTs = getVTList(VT);
11750 return getMachineNode(Opcode, dl, VTs, Ops);
11751}
11752
11754 EVT VT1, EVT VT2, SDValue Op1,
11755 SDValue Op2) {
11756 SDVTList VTs = getVTList(VT1, VT2);
11757 SDValue Ops[] = { Op1, Op2 };
11758 return getMachineNode(Opcode, dl, VTs, Ops);
11759}
11760
11762 EVT VT1, EVT VT2, SDValue Op1,
11763 SDValue Op2, SDValue Op3) {
11764 SDVTList VTs = getVTList(VT1, VT2);
11765 SDValue Ops[] = { Op1, Op2, Op3 };
11766 return getMachineNode(Opcode, dl, VTs, Ops);
11767}
11768
11770 EVT VT1, EVT VT2,
11772 SDVTList VTs = getVTList(VT1, VT2);
11773 return getMachineNode(Opcode, dl, VTs, Ops);
11774}
11775
11777 EVT VT1, EVT VT2, EVT VT3,
11778 SDValue Op1, SDValue Op2) {
11779 SDVTList VTs = getVTList(VT1, VT2, VT3);
11780 SDValue Ops[] = { Op1, Op2 };
11781 return getMachineNode(Opcode, dl, VTs, Ops);
11782}
11783
11785 EVT VT1, EVT VT2, EVT VT3,
11786 SDValue Op1, SDValue Op2,
11787 SDValue Op3) {
11788 SDVTList VTs = getVTList(VT1, VT2, VT3);
11789 SDValue Ops[] = { Op1, Op2, Op3 };
11790 return getMachineNode(Opcode, dl, VTs, Ops);
11791}
11792
11794 EVT VT1, EVT VT2, EVT VT3,
11796 SDVTList VTs = getVTList(VT1, VT2, VT3);
11797 return getMachineNode(Opcode, dl, VTs, Ops);
11798}
11799
11801 ArrayRef<EVT> ResultTys,
11803 SDVTList VTs = getVTList(ResultTys);
11804 return getMachineNode(Opcode, dl, VTs, Ops);
11805}
11806
11808 SDVTList VTs,
11810 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
11812 void *IP = nullptr;
11813
11814 if (DoCSE) {
11816 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
11817 IP = nullptr;
11818 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11819 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
11820 }
11821 }
11822
11823 // Allocate a new MachineSDNode.
11824 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11825 createOperands(N, Ops);
11826
11827 if (DoCSE)
11828 CSEMap.InsertNode(N, IP);
11829
11830 InsertNode(N);
11831 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
11832 return N;
11833}
11834
11835/// getTargetExtractSubreg - A convenience function for creating
11836/// TargetOpcode::EXTRACT_SUBREG nodes.
11838 SDValue Operand) {
11839 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
11840 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
11841 VT, Operand, SRIdxVal);
11842 return SDValue(Subreg, 0);
11843}
11844
11845/// getTargetInsertSubreg - A convenience function for creating
11846/// TargetOpcode::INSERT_SUBREG nodes.
11848 SDValue Operand, SDValue Subreg) {
11849 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
11850 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
11851 VT, Operand, Subreg, SRIdxVal);
11852 return SDValue(Result, 0);
11853}
11854
11855/// getNodeIfExists - Get the specified node if it's already available, or
11856/// else return NULL.
11859 bool AllowCommute) {
11860 SDNodeFlags Flags;
11861 if (Inserter)
11862 Flags = Inserter->getFlags();
11863 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
11864}
11865
11868 const SDNodeFlags Flags,
11869 bool AllowCommute) {
11870 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
11871 return nullptr;
11872
11873 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
11875 AddNodeIDNode(ID, Opcode, VTList, LookupOps);
11876 void *IP = nullptr;
11877 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) {
11878 E->intersectFlagsWith(Flags);
11879 return E;
11880 }
11881 return nullptr;
11882 };
11883
11884 if (SDNode *Existing = Lookup(Ops))
11885 return Existing;
11886
11887 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
11888 return Lookup({Ops[1], Ops[0]});
11889
11890 return nullptr;
11891}
11892
11893/// doesNodeExist - Check if a node exists without modifying its flags.
11894bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
11896 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
11898 AddNodeIDNode(ID, Opcode, VTList, Ops);
11899 void *IP = nullptr;
11900 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
11901 return true;
11902 }
11903 return false;
11904}
11905
11906/// getDbgValue - Creates a SDDbgValue node.
11907///
11908/// SDNode
11910 SDNode *N, unsigned R, bool IsIndirect,
11911 const DebugLoc &DL, unsigned O) {
11912 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11913 "Expected inlined-at fields to agree");
11914 return new (DbgInfo->getAlloc())
11915 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
11916 {}, IsIndirect, DL, O,
11917 /*IsVariadic=*/false);
11918}
11919
11920/// Constant
11922 DIExpression *Expr,
11923 const Value *C,
11924 const DebugLoc &DL, unsigned O) {
11925 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11926 "Expected inlined-at fields to agree");
11927 return new (DbgInfo->getAlloc())
11928 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
11929 /*IsIndirect=*/false, DL, O,
11930 /*IsVariadic=*/false);
11931}
11932
11933/// FrameIndex
11935 DIExpression *Expr, unsigned FI,
11936 bool IsIndirect,
11937 const DebugLoc &DL,
11938 unsigned O) {
11939 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11940 "Expected inlined-at fields to agree");
11941 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
11942}
11943
11944/// FrameIndex with dependencies
11946 DIExpression *Expr, unsigned FI,
11947 ArrayRef<SDNode *> Dependencies,
11948 bool IsIndirect,
11949 const DebugLoc &DL,
11950 unsigned O) {
11951 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11952 "Expected inlined-at fields to agree");
11953 return new (DbgInfo->getAlloc())
11954 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
11955 Dependencies, IsIndirect, DL, O,
11956 /*IsVariadic=*/false);
11957}
11958
11959/// VReg
11961 Register VReg, bool IsIndirect,
11962 const DebugLoc &DL, unsigned O) {
11963 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11964 "Expected inlined-at fields to agree");
11965 return new (DbgInfo->getAlloc())
11966 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
11967 {}, IsIndirect, DL, O,
11968 /*IsVariadic=*/false);
11969}
11970
11973 ArrayRef<SDNode *> Dependencies,
11974 bool IsIndirect, const DebugLoc &DL,
11975 unsigned O, bool IsVariadic) {
11976 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11977 "Expected inlined-at fields to agree");
11978 return new (DbgInfo->getAlloc())
11979 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
11980 DL, O, IsVariadic);
11981}
11982
11984 unsigned OffsetInBits, unsigned SizeInBits,
11985 bool InvalidateDbg) {
11986 SDNode *FromNode = From.getNode();
11987 SDNode *ToNode = To.getNode();
11988 assert(FromNode && ToNode && "Can't modify dbg values");
11989
11990 // PR35338
11991 // TODO: assert(From != To && "Redundant dbg value transfer");
11992 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
11993 if (From == To || FromNode == ToNode)
11994 return;
11995
11996 if (!FromNode->getHasDebugValue())
11997 return;
11998
11999 SDDbgOperand FromLocOp =
12000 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
12002
12004 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
12005 if (Dbg->isInvalidated())
12006 continue;
12007
12008 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
12009
12010 // Create a new location ops vector that is equal to the old vector, but
12011 // with each instance of FromLocOp replaced with ToLocOp.
12012 bool Changed = false;
12013 auto NewLocOps = Dbg->copyLocationOps();
12014 std::replace_if(
12015 NewLocOps.begin(), NewLocOps.end(),
12016 [&Changed, FromLocOp](const SDDbgOperand &Op) {
12017 bool Match = Op == FromLocOp;
12018 Changed |= Match;
12019 return Match;
12020 },
12021 ToLocOp);
12022 // Ignore this SDDbgValue if we didn't find a matching location.
12023 if (!Changed)
12024 continue;
12025
12026 DIVariable *Var = Dbg->getVariable();
12027 auto *Expr = Dbg->getExpression();
12028 // If a fragment is requested, update the expression.
12029 if (SizeInBits) {
12030 // When splitting a larger (e.g., sign-extended) value whose
12031 // lower bits are described with an SDDbgValue, do not attempt
12032 // to transfer the SDDbgValue to the upper bits.
12033 if (auto FI = Expr->getFragmentInfo())
12034 if (OffsetInBits + SizeInBits > FI->SizeInBits)
12035 continue;
12036 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
12037 SizeInBits);
12038 if (!Fragment)
12039 continue;
12040 Expr = *Fragment;
12041 }
12042
12043 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
12044 // Clone the SDDbgValue and move it to To.
12045 SDDbgValue *Clone = getDbgValueList(
12046 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
12047 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
12048 Dbg->isVariadic());
12049 ClonedDVs.push_back(Clone);
12050
12051 if (InvalidateDbg) {
12052 // Invalidate value and indicate the SDDbgValue should not be emitted.
12053 Dbg->setIsInvalidated();
12054 Dbg->setIsEmitted();
12055 }
12056 }
12057
12058 for (SDDbgValue *Dbg : ClonedDVs) {
12059 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
12060 "Transferred DbgValues should depend on the new SDNode");
12061 AddDbgValue(Dbg, false);
12062 }
12063}
12064
12066 if (!N.getHasDebugValue())
12067 return;
12068
12069 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
12070 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
12071 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
12072 return SDDbgOperand::fromNode(Node, ResNo);
12073 };
12074
12076 for (auto *DV : GetDbgValues(&N)) {
12077 if (DV->isInvalidated())
12078 continue;
12079 switch (N.getOpcode()) {
12080 default:
12081 break;
12082 case ISD::ADD: {
12083 SDValue N0 = N.getOperand(0);
12084 SDValue N1 = N.getOperand(1);
12085 if (!isa<ConstantSDNode>(N0)) {
12086 bool RHSConstant = isa<ConstantSDNode>(N1);
12088 if (RHSConstant)
12089 Offset = N.getConstantOperandVal(1);
12090 // We are not allowed to turn indirect debug values variadic, so
12091 // don't salvage those.
12092 if (!RHSConstant && DV->isIndirect())
12093 continue;
12094
12095 // Rewrite an ADD constant node into a DIExpression. Since we are
12096 // performing arithmetic to compute the variable's *value* in the
12097 // DIExpression, we need to mark the expression with a
12098 // DW_OP_stack_value.
12099 auto *DIExpr = DV->getExpression();
12100 auto NewLocOps = DV->copyLocationOps();
12101 bool Changed = false;
12102 size_t OrigLocOpsSize = NewLocOps.size();
12103 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
12104 // We're not given a ResNo to compare against because the whole
12105 // node is going away. We know that any ISD::ADD only has one
12106 // result, so we can assume any node match is using the result.
12107 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
12108 NewLocOps[i].getSDNode() != &N)
12109 continue;
12110 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
12111 if (RHSConstant) {
12114 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
12115 } else {
12116 // Convert to a variadic expression (if not already).
12117 // convertToVariadicExpression() returns a const pointer, so we use
12118 // a temporary const variable here.
12119 const auto *TmpDIExpr =
12123 ExprOps.push_back(NewLocOps.size());
12124 ExprOps.push_back(dwarf::DW_OP_plus);
12125 SDDbgOperand RHS =
12127 NewLocOps.push_back(RHS);
12128 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
12129 }
12130 Changed = true;
12131 }
12132 (void)Changed;
12133 assert(Changed && "Salvage target doesn't use N");
12134
12135 bool IsVariadic =
12136 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
12137
12138 auto AdditionalDependencies = DV->getAdditionalDependencies();
12139 SDDbgValue *Clone = getDbgValueList(
12140 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
12141 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
12142 ClonedDVs.push_back(Clone);
12143 DV->setIsInvalidated();
12144 DV->setIsEmitted();
12145 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
12146 N0.getNode()->dumprFull(this);
12147 dbgs() << " into " << *DIExpr << '\n');
12148 }
12149 break;
12150 }
12151 case ISD::TRUNCATE: {
12152 SDValue N0 = N.getOperand(0);
12153 TypeSize FromSize = N0.getValueSizeInBits();
12154 TypeSize ToSize = N.getValueSizeInBits(0);
12155
12156 DIExpression *DbgExpression = DV->getExpression();
12157 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
12158 auto NewLocOps = DV->copyLocationOps();
12159 bool Changed = false;
12160 for (size_t i = 0; i < NewLocOps.size(); ++i) {
12161 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
12162 NewLocOps[i].getSDNode() != &N)
12163 continue;
12164
12165 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
12166 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
12167 Changed = true;
12168 }
12169 assert(Changed && "Salvage target doesn't use N");
12170 (void)Changed;
12171
12172 SDDbgValue *Clone =
12173 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
12174 DV->getAdditionalDependencies(), DV->isIndirect(),
12175 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
12176
12177 ClonedDVs.push_back(Clone);
12178 DV->setIsInvalidated();
12179 DV->setIsEmitted();
12180 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
12181 dbgs() << " into " << *DbgExpression << '\n');
12182 break;
12183 }
12184 }
12185 }
12186
12187 for (SDDbgValue *Dbg : ClonedDVs) {
12188 assert((!Dbg->getSDNodes().empty() ||
12189 llvm::any_of(Dbg->getLocationOps(),
12190 [&](const SDDbgOperand &Op) {
12191 return Op.getKind() == SDDbgOperand::FRAMEIX;
12192 })) &&
12193 "Salvaged DbgValue should depend on a new SDNode");
12194 AddDbgValue(Dbg, false);
12195 }
12196}
12197
12198/// Creates a SDDbgLabel node.
12200 const DebugLoc &DL, unsigned O) {
12201 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
12202 "Expected inlined-at fields to agree");
12203 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
12204}
12205
12206namespace {
12207
12208/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
12209/// pointed to by a use iterator is deleted, increment the use iterator
12210/// so that it doesn't dangle.
12211///
12212class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
12215
12216 void NodeDeleted(SDNode *N, SDNode *E) override {
12217 // Increment the iterator as needed.
12218 while (UI != UE && N == UI->getUser())
12219 ++UI;
12220 }
12221
12222public:
12223 RAUWUpdateListener(SelectionDAG &d,
12226 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
12227};
12228
12229} // end anonymous namespace
12230
12231/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
12232/// This can cause recursive merging of nodes in the DAG.
12233///
12234/// This version assumes From has a single result value.
12235///
12237 SDNode *From = FromN.getNode();
12238 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
12239 "Cannot replace with this method!");
12240 assert(From != To.getNode() && "Cannot replace uses of with self");
12241
12242 // Preserve Debug Values
12243 transferDbgValues(FromN, To);
12244 // Preserve extra info.
12245 copyExtraInfo(From, To.getNode());
12246
12247 // Iterate over all the existing uses of From. New uses will be added
12248 // to the beginning of the use list, which we avoid visiting.
12249 // This specifically avoids visiting uses of From that arise while the
12250 // replacement is happening, because any such uses would be the result
12251 // of CSE: If an existing node looks like From after one of its operands
12252 // is replaced by To, we don't want to replace of all its users with To
12253 // too. See PR3018 for more info.
12254 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
12255 RAUWUpdateListener Listener(*this, UI, UE);
12256 while (UI != UE) {
12257 SDNode *User = UI->getUser();
12258
12259 // This node is about to morph, remove its old self from the CSE maps.
12260 RemoveNodeFromCSEMaps(User);
12261
12262 // A user can appear in a use list multiple times, and when this
12263 // happens the uses are usually next to each other in the list.
12264 // To help reduce the number of CSE recomputations, process all
12265 // the uses of this user that we can find this way.
12266 do {
12267 SDUse &Use = *UI;
12268 ++UI;
12269 Use.set(To);
12270 if (To->isDivergent() != From->isDivergent())
12272 } while (UI != UE && UI->getUser() == User);
12273 // Now that we have modified User, add it back to the CSE maps. If it
12274 // already exists there, recursively merge the results together.
12275 AddModifiedNodeToCSEMaps(User);
12276 }
12277
12278 // If we just RAUW'd the root, take note.
12279 if (FromN == getRoot())
12280 setRoot(To);
12281}
12282
12283/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
12284/// This can cause recursive merging of nodes in the DAG.
12285///
12286/// This version assumes that for each value of From, there is a
12287/// corresponding value in To in the same position with the same type.
12288///
12290#ifndef NDEBUG
12291 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
12292 assert((!From->hasAnyUseOfValue(i) ||
12293 From->getValueType(i) == To->getValueType(i)) &&
12294 "Cannot use this version of ReplaceAllUsesWith!");
12295#endif
12296
12297 // Handle the trivial case.
12298 if (From == To)
12299 return;
12300
12301 // Preserve Debug Info. Only do this if there's a use.
12302 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
12303 if (From->hasAnyUseOfValue(i)) {
12304 assert((i < To->getNumValues()) && "Invalid To location");
12305 transferDbgValues(SDValue(From, i), SDValue(To, i));
12306 }
12307 // Preserve extra info.
12308 copyExtraInfo(From, To);
12309
12310 // Iterate over just the existing users of From. See the comments in
12311 // the ReplaceAllUsesWith above.
12312 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
12313 RAUWUpdateListener Listener(*this, UI, UE);
12314 while (UI != UE) {
12315 SDNode *User = UI->getUser();
12316
12317 // This node is about to morph, remove its old self from the CSE maps.
12318 RemoveNodeFromCSEMaps(User);
12319
12320 // A user can appear in a use list multiple times, and when this
12321 // happens the uses are usually next to each other in the list.
12322 // To help reduce the number of CSE recomputations, process all
12323 // the uses of this user that we can find this way.
12324 do {
12325 SDUse &Use = *UI;
12326 ++UI;
12327 Use.setNode(To);
12328 if (To->isDivergent() != From->isDivergent())
12330 } while (UI != UE && UI->getUser() == User);
12331
12332 // Now that we have modified User, add it back to the CSE maps. If it
12333 // already exists there, recursively merge the results together.
12334 AddModifiedNodeToCSEMaps(User);
12335 }
12336
12337 // If we just RAUW'd the root, take note.
12338 if (From == getRoot().getNode())
12339 setRoot(SDValue(To, getRoot().getResNo()));
12340}
12341
12342/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
12343/// This can cause recursive merging of nodes in the DAG.
12344///
12345/// This version can replace From with any result values. To must match the
12346/// number and types of values returned by From.
12348 if (From->getNumValues() == 1) // Handle the simple case efficiently.
12349 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
12350
12351 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
12352 // Preserve Debug Info.
12353 transferDbgValues(SDValue(From, i), To[i]);
12354 // Preserve extra info.
12355 copyExtraInfo(From, To[i].getNode());
12356 }
12357
12358 // Iterate over just the existing users of From. See the comments in
12359 // the ReplaceAllUsesWith above.
12360 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
12361 RAUWUpdateListener Listener(*this, UI, UE);
12362 while (UI != UE) {
12363 SDNode *User = UI->getUser();
12364
12365 // This node is about to morph, remove its old self from the CSE maps.
12366 RemoveNodeFromCSEMaps(User);
12367
12368 // A user can appear in a use list multiple times, and when this happens the
12369 // uses are usually next to each other in the list. To help reduce the
12370 // number of CSE and divergence recomputations, process all the uses of this
12371 // user that we can find this way.
12372 bool To_IsDivergent = false;
12373 do {
12374 SDUse &Use = *UI;
12375 const SDValue &ToOp = To[Use.getResNo()];
12376 ++UI;
12377 Use.set(ToOp);
12378 To_IsDivergent |= ToOp->isDivergent();
12379 } while (UI != UE && UI->getUser() == User);
12380
12381 if (To_IsDivergent != From->isDivergent())
12383
12384 // Now that we have modified User, add it back to the CSE maps. If it
12385 // already exists there, recursively merge the results together.
12386 AddModifiedNodeToCSEMaps(User);
12387 }
12388
12389 // If we just RAUW'd the root, take note.
12390 if (From == getRoot().getNode())
12391 setRoot(SDValue(To[getRoot().getResNo()]));
12392}
12393
12394/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
12395/// uses of other values produced by From.getNode() alone. The Deleted
12396/// vector is handled the same way as for ReplaceAllUsesWith.
12398 // Handle the really simple, really trivial case efficiently.
12399 if (From == To) return;
12400
12401 // Handle the simple, trivial, case efficiently.
12402 if (From.getNode()->getNumValues() == 1) {
12403 ReplaceAllUsesWith(From, To);
12404 return;
12405 }
12406
12407 // Preserve Debug Info.
12408 transferDbgValues(From, To);
12409 copyExtraInfo(From.getNode(), To.getNode());
12410
12411 // Iterate over just the existing users of From. See the comments in
12412 // the ReplaceAllUsesWith above.
12413 SDNode::use_iterator UI = From.getNode()->use_begin(),
12414 UE = From.getNode()->use_end();
12415 RAUWUpdateListener Listener(*this, UI, UE);
12416 while (UI != UE) {
12417 SDNode *User = UI->getUser();
12418 bool UserRemovedFromCSEMaps = false;
12419
12420 // A user can appear in a use list multiple times, and when this
12421 // happens the uses are usually next to each other in the list.
12422 // To help reduce the number of CSE recomputations, process all
12423 // the uses of this user that we can find this way.
12424 do {
12425 SDUse &Use = *UI;
12426
12427 // Skip uses of different values from the same node.
12428 if (Use.getResNo() != From.getResNo()) {
12429 ++UI;
12430 continue;
12431 }
12432
12433 // If this node hasn't been modified yet, it's still in the CSE maps,
12434 // so remove its old self from the CSE maps.
12435 if (!UserRemovedFromCSEMaps) {
12436 RemoveNodeFromCSEMaps(User);
12437 UserRemovedFromCSEMaps = true;
12438 }
12439
12440 ++UI;
12441 Use.set(To);
12442 if (To->isDivergent() != From->isDivergent())
12444 } while (UI != UE && UI->getUser() == User);
12445 // We are iterating over all uses of the From node, so if a use
12446 // doesn't use the specific value, no changes are made.
12447 if (!UserRemovedFromCSEMaps)
12448 continue;
12449
12450 // Now that we have modified User, add it back to the CSE maps. If it
12451 // already exists there, recursively merge the results together.
12452 AddModifiedNodeToCSEMaps(User);
12453 }
12454
12455 // If we just RAUW'd the root, take note.
12456 if (From == getRoot())
12457 setRoot(To);
12458}
12459
12460namespace {
12461
12462/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
12463/// to record information about a use.
12464struct UseMemo {
12465 SDNode *User;
12466 unsigned Index;
12467 SDUse *Use;
12468};
12469
12470/// operator< - Sort Memos by User.
12471bool operator<(const UseMemo &L, const UseMemo &R) {
12472 return (intptr_t)L.User < (intptr_t)R.User;
12473}
12474
12475/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
12476/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
12477/// the node already has been taken care of recursively.
12478class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
12479 SmallVectorImpl<UseMemo> &Uses;
12480
12481 void NodeDeleted(SDNode *N, SDNode *E) override {
12482 for (UseMemo &Memo : Uses)
12483 if (Memo.User == N)
12484 Memo.User = nullptr;
12485 }
12486
12487public:
12488 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
12489 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
12490};
12491
12492} // end anonymous namespace
12493
12494/// Return true if a glue output should propagate divergence information.
12496 switch (Node->getOpcode()) {
12497 case ISD::CopyFromReg:
12498 case ISD::CopyToReg:
12499 return false;
12500 default:
12501 return true;
12502 }
12503
12504 llvm_unreachable("covered opcode switch");
12505}
12506
12508 if (TLI->isSDNodeAlwaysUniform(N)) {
12509 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
12510 "Conflicting divergence information!");
12511 return false;
12512 }
12513 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
12514 return true;
12515 for (const auto &Op : N->ops()) {
12516 EVT VT = Op.getValueType();
12517
12518 // Skip Chain. It does not carry divergence.
12519 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
12520 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
12521 return true;
12522 }
12523 return false;
12524}
12525
12527 SmallVector<SDNode *, 16> Worklist(1, N);
12528 do {
12529 N = Worklist.pop_back_val();
12530 bool IsDivergent = calculateDivergence(N);
12531 if (N->SDNodeBits.IsDivergent != IsDivergent) {
12532 N->SDNodeBits.IsDivergent = IsDivergent;
12533 llvm::append_range(Worklist, N->users());
12534 }
12535 } while (!Worklist.empty());
12536}
12537
12538void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
12540 Order.reserve(AllNodes.size());
12541 for (auto &N : allnodes()) {
12542 unsigned NOps = N.getNumOperands();
12543 Degree[&N] = NOps;
12544 if (0 == NOps)
12545 Order.push_back(&N);
12546 }
12547 for (size_t I = 0; I != Order.size(); ++I) {
12548 SDNode *N = Order[I];
12549 for (auto *U : N->users()) {
12550 unsigned &UnsortedOps = Degree[U];
12551 if (0 == --UnsortedOps)
12552 Order.push_back(U);
12553 }
12554 }
12555}
12556
12557#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
12558void SelectionDAG::VerifyDAGDivergence() {
12559 std::vector<SDNode *> TopoOrder;
12560 CreateTopologicalOrder(TopoOrder);
12561 for (auto *N : TopoOrder) {
12562 assert(calculateDivergence(N) == N->isDivergent() &&
12563 "Divergence bit inconsistency detected");
12564 }
12565}
12566#endif
12567
12568/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
12569/// uses of other values produced by From.getNode() alone. The same value
12570/// may appear in both the From and To list. The Deleted vector is
12571/// handled the same way as for ReplaceAllUsesWith.
12573 const SDValue *To,
12574 unsigned Num){
12575 // Handle the simple, trivial case efficiently.
12576 if (Num == 1)
12577 return ReplaceAllUsesOfValueWith(*From, *To);
12578
12579 transferDbgValues(*From, *To);
12580 copyExtraInfo(From->getNode(), To->getNode());
12581
12582 // Read up all the uses and make records of them. This helps
12583 // processing new uses that are introduced during the
12584 // replacement process.
12586 for (unsigned i = 0; i != Num; ++i) {
12587 unsigned FromResNo = From[i].getResNo();
12588 SDNode *FromNode = From[i].getNode();
12589 for (SDUse &Use : FromNode->uses()) {
12590 if (Use.getResNo() == FromResNo) {
12591 UseMemo Memo = {Use.getUser(), i, &Use};
12592 Uses.push_back(Memo);
12593 }
12594 }
12595 }
12596
12597 // Sort the uses, so that all the uses from a given User are together.
12599 RAUOVWUpdateListener Listener(*this, Uses);
12600
12601 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
12602 UseIndex != UseIndexEnd; ) {
12603 // We know that this user uses some value of From. If it is the right
12604 // value, update it.
12605 SDNode *User = Uses[UseIndex].User;
12606 // If the node has been deleted by recursive CSE updates when updating
12607 // another node, then just skip this entry.
12608 if (User == nullptr) {
12609 ++UseIndex;
12610 continue;
12611 }
12612
12613 // This node is about to morph, remove its old self from the CSE maps.
12614 RemoveNodeFromCSEMaps(User);
12615
12616 // The Uses array is sorted, so all the uses for a given User
12617 // are next to each other in the list.
12618 // To help reduce the number of CSE recomputations, process all
12619 // the uses of this user that we can find this way.
12620 do {
12621 unsigned i = Uses[UseIndex].Index;
12622 SDUse &Use = *Uses[UseIndex].Use;
12623 ++UseIndex;
12624
12625 Use.set(To[i]);
12626 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
12627
12628 // Now that we have modified User, add it back to the CSE maps. If it
12629 // already exists there, recursively merge the results together.
12630 AddModifiedNodeToCSEMaps(User);
12631 }
12632}
12633
12634/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
12635/// based on their topological order. It returns the maximum id and a vector
12636/// of the SDNodes* in assigned order by reference.
12638 unsigned DAGSize = 0;
12639
12640 // SortedPos tracks the progress of the algorithm. Nodes before it are
12641 // sorted, nodes after it are unsorted. When the algorithm completes
12642 // it is at the end of the list.
12643 allnodes_iterator SortedPos = allnodes_begin();
12644
12645 // Visit all the nodes. Move nodes with no operands to the front of
12646 // the list immediately. Annotate nodes that do have operands with their
12647 // operand count. Before we do this, the Node Id fields of the nodes
12648 // may contain arbitrary values. After, the Node Id fields for nodes
12649 // before SortedPos will contain the topological sort index, and the
12650 // Node Id fields for nodes At SortedPos and after will contain the
12651 // count of outstanding operands.
12653 checkForCycles(&N, this);
12654 unsigned Degree = N.getNumOperands();
12655 if (Degree == 0) {
12656 // A node with no uses, add it to the result array immediately.
12657 N.setNodeId(DAGSize++);
12658 allnodes_iterator Q(&N);
12659 if (Q != SortedPos)
12660 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
12661 assert(SortedPos != AllNodes.end() && "Overran node list");
12662 ++SortedPos;
12663 } else {
12664 // Temporarily use the Node Id as scratch space for the degree count.
12665 N.setNodeId(Degree);
12666 }
12667 }
12668
12669 // Visit all the nodes. As we iterate, move nodes into sorted order,
12670 // such that by the time the end is reached all nodes will be sorted.
12671 for (SDNode &Node : allnodes()) {
12672 SDNode *N = &Node;
12673 checkForCycles(N, this);
12674 // N is in sorted position, so all its uses have one less operand
12675 // that needs to be sorted.
12676 for (SDNode *P : N->users()) {
12677 unsigned Degree = P->getNodeId();
12678 assert(Degree != 0 && "Invalid node degree");
12679 --Degree;
12680 if (Degree == 0) {
12681 // All of P's operands are sorted, so P may sorted now.
12682 P->setNodeId(DAGSize++);
12683 if (P->getIterator() != SortedPos)
12684 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
12685 assert(SortedPos != AllNodes.end() && "Overran node list");
12686 ++SortedPos;
12687 } else {
12688 // Update P's outstanding operand count.
12689 P->setNodeId(Degree);
12690 }
12691 }
12692 if (Node.getIterator() == SortedPos) {
12693#ifndef NDEBUG
12695 SDNode *S = &*++I;
12696 dbgs() << "Overran sorted position:\n";
12697 S->dumprFull(this); dbgs() << "\n";
12698 dbgs() << "Checking if this is due to cycles\n";
12699 checkForCycles(this, true);
12700#endif
12701 llvm_unreachable(nullptr);
12702 }
12703 }
12704
12705 assert(SortedPos == AllNodes.end() &&
12706 "Topological sort incomplete!");
12707 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
12708 "First node in topological sort is not the entry token!");
12709 assert(AllNodes.front().getNodeId() == 0 &&
12710 "First node in topological sort has non-zero id!");
12711 assert(AllNodes.front().getNumOperands() == 0 &&
12712 "First node in topological sort has operands!");
12713 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
12714 "Last node in topologic sort has unexpected id!");
12715 assert(AllNodes.back().use_empty() &&
12716 "Last node in topologic sort has users!");
12717 assert(DAGSize == allnodes_size() && "Node count mismatch!");
12718 return DAGSize;
12719}
12720
12722 SmallVectorImpl<const SDNode *> &SortedNodes) const {
12723 SortedNodes.clear();
12724 // Node -> remaining number of outstanding operands.
12725 DenseMap<const SDNode *, unsigned> RemainingOperands;
12726
12727 // Put nodes without any operands into SortedNodes first.
12728 for (const SDNode &N : allnodes()) {
12729 checkForCycles(&N, this);
12730 unsigned NumOperands = N.getNumOperands();
12731 if (NumOperands == 0)
12732 SortedNodes.push_back(&N);
12733 else
12734 // Record their total number of outstanding operands.
12735 RemainingOperands[&N] = NumOperands;
12736 }
12737
12738 // A node is pushed into SortedNodes when all of its operands (predecessors in
12739 // the graph) are also in SortedNodes.
12740 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
12741 const SDNode *N = SortedNodes[i];
12742 for (const SDNode *U : N->users()) {
12743 // HandleSDNode is never part of a DAG and therefore has no entry in
12744 // RemainingOperands.
12745 if (U->getOpcode() == ISD::HANDLENODE)
12746 continue;
12747 unsigned &NumRemOperands = RemainingOperands[U];
12748 assert(NumRemOperands && "Invalid number of remaining operands");
12749 --NumRemOperands;
12750 if (!NumRemOperands)
12751 SortedNodes.push_back(U);
12752 }
12753 }
12754
12755 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
12756 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
12757 "First node in topological sort is not the entry token");
12758 assert(SortedNodes.front()->getNumOperands() == 0 &&
12759 "First node in topological sort has operands");
12760}
12761
12762/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
12763/// value is produced by SD.
12764void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
12765 for (SDNode *SD : DB->getSDNodes()) {
12766 if (!SD)
12767 continue;
12768 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
12769 SD->setHasDebugValue(true);
12770 }
12771 DbgInfo->add(DB, isParameter);
12772}
12773
12774void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
12775
12777 SDValue NewMemOpChain) {
12778 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
12779 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
12780 // The new memory operation must have the same position as the old load in
12781 // terms of memory dependency. Create a TokenFactor for the old load and new
12782 // memory operation and update uses of the old load's output chain to use that
12783 // TokenFactor.
12784 if (OldChain == NewMemOpChain || OldChain.use_empty())
12785 return NewMemOpChain;
12786
12787 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
12788 OldChain, NewMemOpChain);
12789 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
12790 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
12791 return TokenFactor;
12792}
12793
12795 SDValue NewMemOp) {
12796 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
12797 SDValue OldChain = SDValue(OldLoad, 1);
12798 SDValue NewMemOpChain = NewMemOp.getValue(1);
12799 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
12800}
12801
12803 Function **OutFunction) {
12804 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
12805
12806 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12807 auto *Module = MF->getFunction().getParent();
12808 auto *Function = Module->getFunction(Symbol);
12809
12810 if (OutFunction != nullptr)
12811 *OutFunction = Function;
12812
12813 if (Function != nullptr) {
12814 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
12815 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
12816 }
12817
12818 std::string ErrorStr;
12819 raw_string_ostream ErrorFormatter(ErrorStr);
12820 ErrorFormatter << "Undefined external symbol ";
12821 ErrorFormatter << '"' << Symbol << '"';
12822 report_fatal_error(Twine(ErrorStr));
12823}
12824
12825//===----------------------------------------------------------------------===//
12826// SDNode Class
12827//===----------------------------------------------------------------------===//
12828
12831 return Const != nullptr && Const->isZero();
12832}
12833
12835 return V.isUndef() || isNullConstant(V);
12836}
12837
12840 return Const != nullptr && Const->isZero() && !Const->isNegative();
12841}
12842
12845 return Const != nullptr && Const->isAllOnes();
12846}
12847
12850 return Const != nullptr && Const->isOne();
12851}
12852
12855 return Const != nullptr && Const->isMinSignedValue();
12856}
12857
12858bool llvm::isNeutralConstant(unsigned Opcode, SDNodeFlags Flags, SDValue V,
12859 unsigned OperandNo) {
12860 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
12861 // TODO: Target-specific opcodes could be added.
12862 if (auto *ConstV = isConstOrConstSplat(V, /*AllowUndefs*/ false,
12863 /*AllowTruncation*/ true)) {
12864 APInt Const = ConstV->getAPIntValue().trunc(V.getScalarValueSizeInBits());
12865 switch (Opcode) {
12866 case ISD::ADD:
12867 case ISD::OR:
12868 case ISD::XOR:
12869 case ISD::UMAX:
12870 return Const.isZero();
12871 case ISD::MUL:
12872 return Const.isOne();
12873 case ISD::AND:
12874 case ISD::UMIN:
12875 return Const.isAllOnes();
12876 case ISD::SMAX:
12877 return Const.isMinSignedValue();
12878 case ISD::SMIN:
12879 return Const.isMaxSignedValue();
12880 case ISD::SUB:
12881 case ISD::SHL:
12882 case ISD::SRA:
12883 case ISD::SRL:
12884 return OperandNo == 1 && Const.isZero();
12885 case ISD::UDIV:
12886 case ISD::SDIV:
12887 return OperandNo == 1 && Const.isOne();
12888 }
12889 } else if (auto *ConstFP = isConstOrConstSplatFP(V)) {
12890 switch (Opcode) {
12891 case ISD::FADD:
12892 return ConstFP->isZero() &&
12893 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
12894 case ISD::FSUB:
12895 return OperandNo == 1 && ConstFP->isZero() &&
12896 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
12897 case ISD::FMUL:
12898 return ConstFP->isExactlyValue(1.0);
12899 case ISD::FDIV:
12900 return OperandNo == 1 && ConstFP->isExactlyValue(1.0);
12901 case ISD::FMINNUM:
12902 case ISD::FMAXNUM: {
12903 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
12904 EVT VT = V.getValueType();
12905 const fltSemantics &Semantics = VT.getFltSemantics();
12906 APFloat NeutralAF = !Flags.hasNoNaNs()
12907 ? APFloat::getQNaN(Semantics)
12908 : !Flags.hasNoInfs()
12909 ? APFloat::getInf(Semantics)
12910 : APFloat::getLargest(Semantics);
12911 if (Opcode == ISD::FMAXNUM)
12912 NeutralAF.changeSign();
12913
12914 return ConstFP->isExactlyValue(NeutralAF);
12915 }
12916 }
12917 }
12918 return false;
12919}
12920
12922 while (V.getOpcode() == ISD::BITCAST)
12923 V = V.getOperand(0);
12924 return V;
12925}
12926
12928 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
12929 V = V.getOperand(0);
12930 return V;
12931}
12932
12934 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12935 V = V.getOperand(0);
12936 return V;
12937}
12938
12940 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12941 SDValue InVec = V.getOperand(0);
12942 SDValue EltNo = V.getOperand(2);
12943 EVT VT = InVec.getValueType();
12944 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
12945 if (IndexC && VT.isFixedLengthVector() &&
12946 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
12947 !DemandedElts[IndexC->getZExtValue()]) {
12948 V = InVec;
12949 continue;
12950 }
12951 break;
12952 }
12953 return V;
12954}
12955
12957 while (V.getOpcode() == ISD::TRUNCATE)
12958 V = V.getOperand(0);
12959 return V;
12960}
12961
12962bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
12963 if (V.getOpcode() != ISD::XOR)
12964 return false;
12965 V = peekThroughBitcasts(V.getOperand(1));
12966 unsigned NumBits = V.getScalarValueSizeInBits();
12967 ConstantSDNode *C =
12968 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
12969 return C && (C->getAPIntValue().countr_one() >= NumBits);
12970}
12971
12973 bool AllowTruncation) {
12974 EVT VT = N.getValueType();
12975 APInt DemandedElts = VT.isFixedLengthVector()
12977 : APInt(1, 1);
12978 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
12979}
12980
12982 bool AllowUndefs,
12983 bool AllowTruncation) {
12985 return CN;
12986
12987 // SplatVectors can truncate their operands. Ignore that case here unless
12988 // AllowTruncation is set.
12989 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
12990 EVT VecEltVT = N->getValueType(0).getVectorElementType();
12991 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12992 EVT CVT = CN->getValueType(0);
12993 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
12994 if (AllowTruncation || CVT == VecEltVT)
12995 return CN;
12996 }
12997 }
12998
13000 BitVector UndefElements;
13001 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
13002
13003 // BuildVectors can truncate their operands. Ignore that case here unless
13004 // AllowTruncation is set.
13005 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13006 if (CN && (UndefElements.none() || AllowUndefs)) {
13007 EVT CVT = CN->getValueType(0);
13008 EVT NSVT = N.getValueType().getScalarType();
13009 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
13010 if (AllowTruncation || (CVT == NSVT))
13011 return CN;
13012 }
13013 }
13014
13015 return nullptr;
13016}
13017
13019 EVT VT = N.getValueType();
13020 APInt DemandedElts = VT.isFixedLengthVector()
13022 : APInt(1, 1);
13023 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
13024}
13025
13027 const APInt &DemandedElts,
13028 bool AllowUndefs) {
13030 return CN;
13031
13033 BitVector UndefElements;
13034 ConstantFPSDNode *CN =
13035 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
13036 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13037 if (CN && (UndefElements.none() || AllowUndefs))
13038 return CN;
13039 }
13040
13041 if (N.getOpcode() == ISD::SPLAT_VECTOR)
13042 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
13043 return CN;
13044
13045 return nullptr;
13046}
13047
13048bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
13049 // TODO: may want to use peekThroughBitcast() here.
13050 ConstantSDNode *C =
13051 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13052 return C && C->isZero();
13053}
13054
13055bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
13056 ConstantSDNode *C =
13057 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
13058 return C && C->isOne();
13059}
13060
13061bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
13062 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13063 return C && C->isExactlyValue(1.0);
13064}
13065
13066bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
13068 unsigned BitWidth = N.getScalarValueSizeInBits();
13069 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
13070 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
13071}
13072
13073bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
13074 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
13075 return C && APInt::isSameValue(C->getAPIntValue(),
13076 APInt(C->getAPIntValue().getBitWidth(), 1));
13077}
13078
13079bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
13081 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
13082 return C && C->isZero();
13083}
13084
13085bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
13086 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13087 return C && C->isZero();
13088}
13089
13093
13094MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
13095 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
13096 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
13097 MemSDNodeBits.IsVolatile = MMO->isVolatile();
13098 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
13099 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
13100 MemSDNodeBits.IsInvariant = MMO->isInvariant();
13101
13102 // We check here that the size of the memory operand fits within the size of
13103 // the MMO. This is because the MMO might indicate only a possible address
13104 // range instead of specifying the affected memory addresses precisely.
13105 assert(
13106 (!MMO->getType().isValid() ||
13107 TypeSize::isKnownLE(memvt.getStoreSize(), MMO->getSize().getValue())) &&
13108 "Size mismatch!");
13109}
13110
13111/// Profile - Gather unique data for the node.
13112///
13114 AddNodeIDNode(ID, this);
13115}
13116
13117namespace {
13118
13119 struct EVTArray {
13120 std::vector<EVT> VTs;
13121
13122 EVTArray() {
13123 VTs.reserve(MVT::VALUETYPE_SIZE);
13124 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
13125 VTs.push_back(MVT((MVT::SimpleValueType)i));
13126 }
13127 };
13128
13129} // end anonymous namespace
13130
13131/// getValueTypeList - Return a pointer to the specified value type.
13132///
13133const EVT *SDNode::getValueTypeList(MVT VT) {
13134 static EVTArray SimpleVTArray;
13135
13136 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
13137 return &SimpleVTArray.VTs[VT.SimpleTy];
13138}
13139
13140/// hasAnyUseOfValue - Return true if there are any use of the indicated
13141/// value. This method ignores uses of other values defined by this operation.
13142bool SDNode::hasAnyUseOfValue(unsigned Value) const {
13143 assert(Value < getNumValues() && "Bad value!");
13144
13145 for (SDUse &U : uses())
13146 if (U.getResNo() == Value)
13147 return true;
13148
13149 return false;
13150}
13151
13152/// isOnlyUserOf - Return true if this node is the only use of N.
13153bool SDNode::isOnlyUserOf(const SDNode *N) const {
13154 bool Seen = false;
13155 for (const SDNode *User : N->users()) {
13156 if (User == this)
13157 Seen = true;
13158 else
13159 return false;
13160 }
13161
13162 return Seen;
13163}
13164
13165/// Return true if the only users of N are contained in Nodes.
13167 bool Seen = false;
13168 for (const SDNode *User : N->users()) {
13169 if (llvm::is_contained(Nodes, User))
13170 Seen = true;
13171 else
13172 return false;
13173 }
13174
13175 return Seen;
13176}
13177
13178/// Return true if the referenced return value is an operand of N.
13179bool SDValue::isOperandOf(const SDNode *N) const {
13180 return is_contained(N->op_values(), *this);
13181}
13182
13183bool SDNode::isOperandOf(const SDNode *N) const {
13184 return any_of(N->op_values(),
13185 [this](SDValue Op) { return this == Op.getNode(); });
13186}
13187
13188/// reachesChainWithoutSideEffects - Return true if this operand (which must
13189/// be a chain) reaches the specified operand without crossing any
13190/// side-effecting instructions on any chain path. In practice, this looks
13191/// through token factors and non-volatile loads. In order to remain efficient,
13192/// this only looks a couple of nodes in, it does not do an exhaustive search.
13193///
13194/// Note that we only need to examine chains when we're searching for
13195/// side-effects; SelectionDAG requires that all side-effects are represented
13196/// by chains, even if another operand would force a specific ordering. This
13197/// constraint is necessary to allow transformations like splitting loads.
13199 unsigned Depth) const {
13200 if (*this == Dest) return true;
13201
13202 // Don't search too deeply, we just want to be able to see through
13203 // TokenFactor's etc.
13204 if (Depth == 0) return false;
13205
13206 // If this is a token factor, all inputs to the TF happen in parallel.
13207 if (getOpcode() == ISD::TokenFactor) {
13208 // First, try a shallow search.
13209 if (is_contained((*this)->ops(), Dest)) {
13210 // We found the chain we want as an operand of this TokenFactor.
13211 // Essentially, we reach the chain without side-effects if we could
13212 // serialize the TokenFactor into a simple chain of operations with
13213 // Dest as the last operation. This is automatically true if the
13214 // chain has one use: there are no other ordering constraints.
13215 // If the chain has more than one use, we give up: some other
13216 // use of Dest might force a side-effect between Dest and the current
13217 // node.
13218 if (Dest.hasOneUse())
13219 return true;
13220 }
13221 // Next, try a deep search: check whether every operand of the TokenFactor
13222 // reaches Dest.
13223 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
13224 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
13225 });
13226 }
13227
13228 // Loads don't have side effects, look through them.
13229 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
13230 if (Ld->isUnordered())
13231 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
13232 }
13233 return false;
13234}
13235
13236bool SDNode::hasPredecessor(const SDNode *N) const {
13239 Worklist.push_back(this);
13240 return hasPredecessorHelper(N, Visited, Worklist);
13241}
13242
13244 this->Flags &= Flags;
13245}
13246
13247SDValue
13249 ArrayRef<ISD::NodeType> CandidateBinOps,
13250 bool AllowPartials) {
13251 // The pattern must end in an extract from index 0.
13252 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13253 !isNullConstant(Extract->getOperand(1)))
13254 return SDValue();
13255
13256 // Match against one of the candidate binary ops.
13257 SDValue Op = Extract->getOperand(0);
13258 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
13259 return Op.getOpcode() == unsigned(BinOp);
13260 }))
13261 return SDValue();
13262
13263 // Floating-point reductions may require relaxed constraints on the final step
13264 // of the reduction because they may reorder intermediate operations.
13265 unsigned CandidateBinOp = Op.getOpcode();
13266 if (Op.getValueType().isFloatingPoint()) {
13267 SDNodeFlags Flags = Op->getFlags();
13268 switch (CandidateBinOp) {
13269 case ISD::FADD:
13270 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
13271 return SDValue();
13272 break;
13273 default:
13274 llvm_unreachable("Unhandled FP opcode for binop reduction");
13275 }
13276 }
13277
13278 // Matching failed - attempt to see if we did enough stages that a partial
13279 // reduction from a subvector is possible.
13280 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
13281 if (!AllowPartials || !Op)
13282 return SDValue();
13283 EVT OpVT = Op.getValueType();
13284 EVT OpSVT = OpVT.getScalarType();
13285 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
13286 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
13287 return SDValue();
13288 BinOp = (ISD::NodeType)CandidateBinOp;
13289 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
13290 };
13291
13292 // At each stage, we're looking for something that looks like:
13293 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
13294 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
13295 // i32 undef, i32 undef, i32 undef, i32 undef>
13296 // %a = binop <8 x i32> %op, %s
13297 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
13298 // we expect something like:
13299 // <4,5,6,7,u,u,u,u>
13300 // <2,3,u,u,u,u,u,u>
13301 // <1,u,u,u,u,u,u,u>
13302 // While a partial reduction match would be:
13303 // <2,3,u,u,u,u,u,u>
13304 // <1,u,u,u,u,u,u,u>
13305 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
13306 SDValue PrevOp;
13307 for (unsigned i = 0; i < Stages; ++i) {
13308 unsigned MaskEnd = (1 << i);
13309
13310 if (Op.getOpcode() != CandidateBinOp)
13311 return PartialReduction(PrevOp, MaskEnd);
13312
13313 SDValue Op0 = Op.getOperand(0);
13314 SDValue Op1 = Op.getOperand(1);
13315
13317 if (Shuffle) {
13318 Op = Op1;
13319 } else {
13320 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
13321 Op = Op0;
13322 }
13323
13324 // The first operand of the shuffle should be the same as the other operand
13325 // of the binop.
13326 if (!Shuffle || Shuffle->getOperand(0) != Op)
13327 return PartialReduction(PrevOp, MaskEnd);
13328
13329 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
13330 for (int Index = 0; Index < (int)MaskEnd; ++Index)
13331 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
13332 return PartialReduction(PrevOp, MaskEnd);
13333
13334 PrevOp = Op;
13335 }
13336
13337 // Handle subvector reductions, which tend to appear after the shuffle
13338 // reduction stages.
13339 while (Op.getOpcode() == CandidateBinOp) {
13340 unsigned NumElts = Op.getValueType().getVectorNumElements();
13341 SDValue Op0 = Op.getOperand(0);
13342 SDValue Op1 = Op.getOperand(1);
13343 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13345 Op0.getOperand(0) != Op1.getOperand(0))
13346 break;
13347 SDValue Src = Op0.getOperand(0);
13348 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
13349 if (NumSrcElts != (2 * NumElts))
13350 break;
13351 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
13352 Op1.getConstantOperandAPInt(1) == NumElts) &&
13353 !(Op1.getConstantOperandAPInt(1) == 0 &&
13354 Op0.getConstantOperandAPInt(1) == NumElts))
13355 break;
13356 Op = Src;
13357 }
13358
13359 BinOp = (ISD::NodeType)CandidateBinOp;
13360 return Op;
13361}
13362
13364 EVT VT = N->getValueType(0);
13365 EVT EltVT = VT.getVectorElementType();
13366 unsigned NE = VT.getVectorNumElements();
13367
13368 SDLoc dl(N);
13369
13370 // If ResNE is 0, fully unroll the vector op.
13371 if (ResNE == 0)
13372 ResNE = NE;
13373 else if (NE > ResNE)
13374 NE = ResNE;
13375
13376 if (N->getNumValues() == 2) {
13377 SmallVector<SDValue, 8> Scalars0, Scalars1;
13378 SmallVector<SDValue, 4> Operands(N->getNumOperands());
13379 EVT VT1 = N->getValueType(1);
13380 EVT EltVT1 = VT1.getVectorElementType();
13381
13382 unsigned i;
13383 for (i = 0; i != NE; ++i) {
13384 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
13385 SDValue Operand = N->getOperand(j);
13386 EVT OperandVT = Operand.getValueType();
13387
13388 // A vector operand; extract a single element.
13389 EVT OperandEltVT = OperandVT.getVectorElementType();
13390 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
13391 }
13392
13393 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
13394 Scalars0.push_back(EltOp);
13395 Scalars1.push_back(EltOp.getValue(1));
13396 }
13397
13398 for (; i < ResNE; ++i) {
13399 Scalars0.push_back(getUNDEF(EltVT));
13400 Scalars1.push_back(getUNDEF(EltVT1));
13401 }
13402
13403 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
13404 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResNE);
13405 SDValue Vec0 = getBuildVector(VecVT, dl, Scalars0);
13406 SDValue Vec1 = getBuildVector(VecVT1, dl, Scalars1);
13407 return getMergeValues({Vec0, Vec1}, dl);
13408 }
13409
13410 assert(N->getNumValues() == 1 &&
13411 "Can't unroll a vector with multiple results!");
13412
13414 SmallVector<SDValue, 4> Operands(N->getNumOperands());
13415
13416 unsigned i;
13417 for (i= 0; i != NE; ++i) {
13418 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
13419 SDValue Operand = N->getOperand(j);
13420 EVT OperandVT = Operand.getValueType();
13421 if (OperandVT.isVector()) {
13422 // A vector operand; extract a single element.
13423 EVT OperandEltVT = OperandVT.getVectorElementType();
13424 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
13425 } else {
13426 // A scalar operand; just use it as is.
13427 Operands[j] = Operand;
13428 }
13429 }
13430
13431 switch (N->getOpcode()) {
13432 default: {
13433 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
13434 N->getFlags()));
13435 break;
13436 }
13437 case ISD::VSELECT:
13438 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
13439 break;
13440 case ISD::SHL:
13441 case ISD::SRA:
13442 case ISD::SRL:
13443 case ISD::ROTL:
13444 case ISD::ROTR:
13445 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
13446 getShiftAmountOperand(Operands[0].getValueType(),
13447 Operands[1])));
13448 break;
13450 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
13451 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
13452 Operands[0],
13453 getValueType(ExtVT)));
13454 break;
13455 }
13456 case ISD::ADDRSPACECAST: {
13457 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
13458 Scalars.push_back(getAddrSpaceCast(dl, EltVT, Operands[0],
13459 ASC->getSrcAddressSpace(),
13460 ASC->getDestAddressSpace()));
13461 break;
13462 }
13463 }
13464 }
13465
13466 for (; i < ResNE; ++i)
13467 Scalars.push_back(getUNDEF(EltVT));
13468
13469 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
13470 return getBuildVector(VecVT, dl, Scalars);
13471}
13472
13473std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
13474 SDNode *N, unsigned ResNE) {
13475 unsigned Opcode = N->getOpcode();
13476 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
13477 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
13478 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
13479 "Expected an overflow opcode");
13480
13481 EVT ResVT = N->getValueType(0);
13482 EVT OvVT = N->getValueType(1);
13483 EVT ResEltVT = ResVT.getVectorElementType();
13484 EVT OvEltVT = OvVT.getVectorElementType();
13485 SDLoc dl(N);
13486
13487 // If ResNE is 0, fully unroll the vector op.
13488 unsigned NE = ResVT.getVectorNumElements();
13489 if (ResNE == 0)
13490 ResNE = NE;
13491 else if (NE > ResNE)
13492 NE = ResNE;
13493
13494 SmallVector<SDValue, 8> LHSScalars;
13495 SmallVector<SDValue, 8> RHSScalars;
13496 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
13497 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
13498
13499 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
13500 SDVTList VTs = getVTList(ResEltVT, SVT);
13501 SmallVector<SDValue, 8> ResScalars;
13502 SmallVector<SDValue, 8> OvScalars;
13503 for (unsigned i = 0; i < NE; ++i) {
13504 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
13505 SDValue Ov =
13506 getSelect(dl, OvEltVT, Res.getValue(1),
13507 getBoolConstant(true, dl, OvEltVT, ResVT),
13508 getConstant(0, dl, OvEltVT));
13509
13510 ResScalars.push_back(Res);
13511 OvScalars.push_back(Ov);
13512 }
13513
13514 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
13515 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
13516
13517 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
13518 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
13519 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
13520 getBuildVector(NewOvVT, dl, OvScalars));
13521}
13522
13525 unsigned Bytes,
13526 int Dist) const {
13527 if (LD->isVolatile() || Base->isVolatile())
13528 return false;
13529 // TODO: probably too restrictive for atomics, revisit
13530 if (!LD->isSimple())
13531 return false;
13532 if (LD->isIndexed() || Base->isIndexed())
13533 return false;
13534 if (LD->getChain() != Base->getChain())
13535 return false;
13536 EVT VT = LD->getMemoryVT();
13537 if (VT.getSizeInBits() / 8 != Bytes)
13538 return false;
13539
13540 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
13541 auto LocDecomp = BaseIndexOffset::match(LD, *this);
13542
13543 int64_t Offset = 0;
13544 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
13545 return (Dist * (int64_t)Bytes == Offset);
13546 return false;
13547}
13548
13549/// InferPtrAlignment - Infer alignment of a load / store address. Return
13550/// std::nullopt if it cannot be inferred.
13552 // If this is a GlobalAddress + cst, return the alignment.
13553 const GlobalValue *GV = nullptr;
13554 int64_t GVOffset = 0;
13555 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
13556 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
13557 KnownBits Known(PtrWidth);
13559 unsigned AlignBits = Known.countMinTrailingZeros();
13560 if (AlignBits)
13561 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
13562 }
13563
13564 // If this is a direct reference to a stack slot, use information about the
13565 // stack slot's alignment.
13566 int FrameIdx = INT_MIN;
13567 int64_t FrameOffset = 0;
13569 FrameIdx = FI->getIndex();
13570 } else if (isBaseWithConstantOffset(Ptr) &&
13572 // Handle FI+Cst
13573 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
13574 FrameOffset = Ptr.getConstantOperandVal(1);
13575 }
13576
13577 if (FrameIdx != INT_MIN) {
13579 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
13580 }
13581
13582 return std::nullopt;
13583}
13584
13585/// Split the scalar node with EXTRACT_ELEMENT using the provided
13586/// VTs and return the low/high part.
13587std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
13588 const SDLoc &DL,
13589 const EVT &LoVT,
13590 const EVT &HiVT) {
13591 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
13592 "Split node must be a scalar type");
13593 SDValue Lo =
13595 SDValue Hi =
13597 return std::make_pair(Lo, Hi);
13598}
13599
13600/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
13601/// which is split (or expanded) into two not necessarily identical pieces.
13602std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
13603 // Currently all types are split in half.
13604 EVT LoVT, HiVT;
13605 if (!VT.isVector())
13606 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
13607 else
13608 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
13609
13610 return std::make_pair(LoVT, HiVT);
13611}
13612
13613/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
13614/// type, dependent on an enveloping VT that has been split into two identical
13615/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
13616std::pair<EVT, EVT>
13618 bool *HiIsEmpty) const {
13619 EVT EltTp = VT.getVectorElementType();
13620 // Examples:
13621 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
13622 // custom VL=9 with enveloping VL=8/8 yields 8/1
13623 // custom VL=10 with enveloping VL=8/8 yields 8/2
13624 // etc.
13625 ElementCount VTNumElts = VT.getVectorElementCount();
13626 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
13627 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
13628 "Mixing fixed width and scalable vectors when enveloping a type");
13629 EVT LoVT, HiVT;
13630 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
13631 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
13632 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
13633 *HiIsEmpty = false;
13634 } else {
13635 // Flag that hi type has zero storage size, but return split envelop type
13636 // (this would be easier if vector types with zero elements were allowed).
13637 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
13638 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
13639 *HiIsEmpty = true;
13640 }
13641 return std::make_pair(LoVT, HiVT);
13642}
13643
13644/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
13645/// low/high part.
13646std::pair<SDValue, SDValue>
13647SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
13648 const EVT &HiVT) {
13649 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
13650 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
13651 "Splitting vector with an invalid mixture of fixed and scalable "
13652 "vector types");
13654 N.getValueType().getVectorMinNumElements() &&
13655 "More vector elements requested than available!");
13656 SDValue Lo, Hi;
13657 Lo = getExtractSubvector(DL, LoVT, N, 0);
13658 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
13659 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
13660 // IDX with the runtime scaling factor of the result vector type. For
13661 // fixed-width result vectors, that runtime scaling factor is 1.
13664 return std::make_pair(Lo, Hi);
13665}
13666
13667std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
13668 const SDLoc &DL) {
13669 // Split the vector length parameter.
13670 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
13671 EVT VT = N.getValueType();
13673 "Expecting the mask to be an evenly-sized vector");
13674 SDValue HalfNumElts = getElementCount(
13676 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
13677 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
13678 return std::make_pair(Lo, Hi);
13679}
13680
13681/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
13683 EVT VT = N.getValueType();
13686 return getInsertSubvector(DL, getUNDEF(WideVT), N, 0);
13687}
13688
13691 unsigned Start, unsigned Count,
13692 EVT EltVT) {
13693 EVT VT = Op.getValueType();
13694 if (Count == 0)
13696 if (EltVT == EVT())
13697 EltVT = VT.getVectorElementType();
13698 SDLoc SL(Op);
13699 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
13700 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
13701 }
13702}
13703
13704// getAddressSpace - Return the address space this GlobalAddress belongs to.
13706 return getGlobal()->getType()->getAddressSpace();
13707}
13708
13711 return Val.MachineCPVal->getType();
13712 return Val.ConstVal->getType();
13713}
13714
13715bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
13716 unsigned &SplatBitSize,
13717 bool &HasAnyUndefs,
13718 unsigned MinSplatBits,
13719 bool IsBigEndian) const {
13720 EVT VT = getValueType(0);
13721 assert(VT.isVector() && "Expected a vector type");
13722 unsigned VecWidth = VT.getSizeInBits();
13723 if (MinSplatBits > VecWidth)
13724 return false;
13725
13726 // FIXME: The widths are based on this node's type, but build vectors can
13727 // truncate their operands.
13728 SplatValue = APInt(VecWidth, 0);
13729 SplatUndef = APInt(VecWidth, 0);
13730
13731 // Get the bits. Bits with undefined values (when the corresponding element
13732 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
13733 // in SplatValue. If any of the values are not constant, give up and return
13734 // false.
13735 unsigned int NumOps = getNumOperands();
13736 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
13737 unsigned EltWidth = VT.getScalarSizeInBits();
13738
13739 for (unsigned j = 0; j < NumOps; ++j) {
13740 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
13741 SDValue OpVal = getOperand(i);
13742 unsigned BitPos = j * EltWidth;
13743
13744 if (OpVal.isUndef())
13745 SplatUndef.setBits(BitPos, BitPos + EltWidth);
13746 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
13747 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
13748 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
13749 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
13750 else
13751 return false;
13752 }
13753
13754 // The build_vector is all constants or undefs. Find the smallest element
13755 // size that splats the vector.
13756 HasAnyUndefs = (SplatUndef != 0);
13757
13758 // FIXME: This does not work for vectors with elements less than 8 bits.
13759 while (VecWidth > 8) {
13760 // If we can't split in half, stop here.
13761 if (VecWidth & 1)
13762 break;
13763
13764 unsigned HalfSize = VecWidth / 2;
13765 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
13766 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
13767 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
13768 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
13769
13770 // If the two halves do not match (ignoring undef bits), stop here.
13771 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
13772 MinSplatBits > HalfSize)
13773 break;
13774
13775 SplatValue = HighValue | LowValue;
13776 SplatUndef = HighUndef & LowUndef;
13777
13778 VecWidth = HalfSize;
13779 }
13780
13781 // FIXME: The loop above only tries to split in halves. But if the input
13782 // vector for example is <3 x i16> it wouldn't be able to detect a
13783 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
13784 // optimizations. I guess that back in the days when this helper was created
13785 // vectors normally was power-of-2 sized.
13786
13787 SplatBitSize = VecWidth;
13788 return true;
13789}
13790
13792 BitVector *UndefElements) const {
13793 unsigned NumOps = getNumOperands();
13794 if (UndefElements) {
13795 UndefElements->clear();
13796 UndefElements->resize(NumOps);
13797 }
13798 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
13799 if (!DemandedElts)
13800 return SDValue();
13801 SDValue Splatted;
13802 for (unsigned i = 0; i != NumOps; ++i) {
13803 if (!DemandedElts[i])
13804 continue;
13805 SDValue Op = getOperand(i);
13806 if (Op.isUndef()) {
13807 if (UndefElements)
13808 (*UndefElements)[i] = true;
13809 } else if (!Splatted) {
13810 Splatted = Op;
13811 } else if (Splatted != Op) {
13812 return SDValue();
13813 }
13814 }
13815
13816 if (!Splatted) {
13817 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
13818 assert(getOperand(FirstDemandedIdx).isUndef() &&
13819 "Can only have a splat without a constant for all undefs.");
13820 return getOperand(FirstDemandedIdx);
13821 }
13822
13823 return Splatted;
13824}
13825
13827 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
13828 return getSplatValue(DemandedElts, UndefElements);
13829}
13830
13832 SmallVectorImpl<SDValue> &Sequence,
13833 BitVector *UndefElements) const {
13834 unsigned NumOps = getNumOperands();
13835 Sequence.clear();
13836 if (UndefElements) {
13837 UndefElements->clear();
13838 UndefElements->resize(NumOps);
13839 }
13840 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
13841 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
13842 return false;
13843
13844 // Set the undefs even if we don't find a sequence (like getSplatValue).
13845 if (UndefElements)
13846 for (unsigned I = 0; I != NumOps; ++I)
13847 if (DemandedElts[I] && getOperand(I).isUndef())
13848 (*UndefElements)[I] = true;
13849
13850 // Iteratively widen the sequence length looking for repetitions.
13851 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
13852 Sequence.append(SeqLen, SDValue());
13853 for (unsigned I = 0; I != NumOps; ++I) {
13854 if (!DemandedElts[I])
13855 continue;
13856 SDValue &SeqOp = Sequence[I % SeqLen];
13858 if (Op.isUndef()) {
13859 if (!SeqOp)
13860 SeqOp = Op;
13861 continue;
13862 }
13863 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
13864 Sequence.clear();
13865 break;
13866 }
13867 SeqOp = Op;
13868 }
13869 if (!Sequence.empty())
13870 return true;
13871 }
13872
13873 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
13874 return false;
13875}
13876
13878 BitVector *UndefElements) const {
13879 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
13880 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
13881}
13882
13885 BitVector *UndefElements) const {
13887 getSplatValue(DemandedElts, UndefElements));
13888}
13889
13892 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
13893}
13894
13897 BitVector *UndefElements) const {
13899 getSplatValue(DemandedElts, UndefElements));
13900}
13901
13906
13907int32_t
13909 uint32_t BitWidth) const {
13910 if (ConstantFPSDNode *CN =
13912 bool IsExact;
13913 APSInt IntVal(BitWidth);
13914 const APFloat &APF = CN->getValueAPF();
13915 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
13916 APFloat::opOK ||
13917 !IsExact)
13918 return -1;
13919
13920 return IntVal.exactLogBase2();
13921 }
13922 return -1;
13923}
13924
13926 bool IsLittleEndian, unsigned DstEltSizeInBits,
13927 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
13928 // Early-out if this contains anything but Undef/Constant/ConstantFP.
13929 if (!isConstant())
13930 return false;
13931
13932 unsigned NumSrcOps = getNumOperands();
13933 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
13934 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
13935 "Invalid bitcast scale");
13936
13937 // Extract raw src bits.
13938 SmallVector<APInt> SrcBitElements(NumSrcOps,
13939 APInt::getZero(SrcEltSizeInBits));
13940 BitVector SrcUndeElements(NumSrcOps, false);
13941
13942 for (unsigned I = 0; I != NumSrcOps; ++I) {
13944 if (Op.isUndef()) {
13945 SrcUndeElements.set(I);
13946 continue;
13947 }
13948 auto *CInt = dyn_cast<ConstantSDNode>(Op);
13949 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
13950 assert((CInt || CFP) && "Unknown constant");
13951 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
13952 : CFP->getValueAPF().bitcastToAPInt();
13953 }
13954
13955 // Recast to dst width.
13956 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
13957 SrcBitElements, UndefElements, SrcUndeElements);
13958 return true;
13959}
13960
13961void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
13962 unsigned DstEltSizeInBits,
13963 SmallVectorImpl<APInt> &DstBitElements,
13964 ArrayRef<APInt> SrcBitElements,
13965 BitVector &DstUndefElements,
13966 const BitVector &SrcUndefElements) {
13967 unsigned NumSrcOps = SrcBitElements.size();
13968 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
13969 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
13970 "Invalid bitcast scale");
13971 assert(NumSrcOps == SrcUndefElements.size() &&
13972 "Vector size mismatch");
13973
13974 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
13975 DstUndefElements.clear();
13976 DstUndefElements.resize(NumDstOps, false);
13977 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
13978
13979 // Concatenate src elements constant bits together into dst element.
13980 if (SrcEltSizeInBits <= DstEltSizeInBits) {
13981 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
13982 for (unsigned I = 0; I != NumDstOps; ++I) {
13983 DstUndefElements.set(I);
13984 APInt &DstBits = DstBitElements[I];
13985 for (unsigned J = 0; J != Scale; ++J) {
13986 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
13987 if (SrcUndefElements[Idx])
13988 continue;
13989 DstUndefElements.reset(I);
13990 const APInt &SrcBits = SrcBitElements[Idx];
13991 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
13992 "Illegal constant bitwidths");
13993 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
13994 }
13995 }
13996 return;
13997 }
13998
13999 // Split src element constant bits into dst elements.
14000 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
14001 for (unsigned I = 0; I != NumSrcOps; ++I) {
14002 if (SrcUndefElements[I]) {
14003 DstUndefElements.set(I * Scale, (I + 1) * Scale);
14004 continue;
14005 }
14006 const APInt &SrcBits = SrcBitElements[I];
14007 for (unsigned J = 0; J != Scale; ++J) {
14008 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14009 APInt &DstBits = DstBitElements[Idx];
14010 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
14011 }
14012 }
14013}
14014
14016 for (const SDValue &Op : op_values()) {
14017 unsigned Opc = Op.getOpcode();
14018 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
14019 return false;
14020 }
14021 return true;
14022}
14023
14024std::optional<std::pair<APInt, APInt>>
14026 unsigned NumOps = getNumOperands();
14027 if (NumOps < 2)
14028 return std::nullopt;
14029
14032 return std::nullopt;
14033
14034 unsigned EltSize = getValueType(0).getScalarSizeInBits();
14035 APInt Start = getConstantOperandAPInt(0).trunc(EltSize);
14036 APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start;
14037
14038 if (Stride.isZero())
14039 return std::nullopt;
14040
14041 for (unsigned i = 2; i < NumOps; ++i) {
14043 return std::nullopt;
14044
14045 APInt Val = getConstantOperandAPInt(i).trunc(EltSize);
14046 if (Val != (Start + (Stride * i)))
14047 return std::nullopt;
14048 }
14049
14050 return std::make_pair(Start, Stride);
14051}
14052
14054 // Find the first non-undef value in the shuffle mask.
14055 unsigned i, e;
14056 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
14057 /* search */;
14058
14059 // If all elements are undefined, this shuffle can be considered a splat
14060 // (although it should eventually get simplified away completely).
14061 if (i == e)
14062 return true;
14063
14064 // Make sure all remaining elements are either undef or the same as the first
14065 // non-undef value.
14066 for (int Idx = Mask[i]; i != e; ++i)
14067 if (Mask[i] >= 0 && Mask[i] != Idx)
14068 return false;
14069 return true;
14070}
14071
14072// Returns true if it is a constant integer BuildVector or constant integer,
14073// possibly hidden by a bitcast.
14075 SDValue N, bool AllowOpaques) const {
14077
14078 if (auto *C = dyn_cast<ConstantSDNode>(N))
14079 return AllowOpaques || !C->isOpaque();
14080
14082 return true;
14083
14084 // Treat a GlobalAddress supporting constant offset folding as a
14085 // constant integer.
14086 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
14087 if (GA->getOpcode() == ISD::GlobalAddress &&
14088 TLI->isOffsetFoldingLegal(GA))
14089 return true;
14090
14091 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
14092 isa<ConstantSDNode>(N.getOperand(0)))
14093 return true;
14094 return false;
14095}
14096
14097// Returns true if it is a constant float BuildVector or constant float.
14100 return true;
14101
14103 return true;
14104
14105 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
14106 isa<ConstantFPSDNode>(N.getOperand(0)))
14107 return true;
14108
14109 return false;
14110}
14111
14112std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
14113 ConstantSDNode *Const =
14114 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
14115 if (!Const)
14116 return std::nullopt;
14117
14118 EVT VT = N->getValueType(0);
14119 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
14120 switch (TLI->getBooleanContents(N.getValueType())) {
14122 if (CVal.isOne())
14123 return true;
14124 if (CVal.isZero())
14125 return false;
14126 return std::nullopt;
14128 if (CVal.isAllOnes())
14129 return true;
14130 if (CVal.isZero())
14131 return false;
14132 return std::nullopt;
14134 return CVal[0];
14135 }
14136 llvm_unreachable("Unknown BooleanContent enum");
14137}
14138
14139void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
14140 assert(!Node->OperandList && "Node already has operands");
14142 "too many operands to fit into SDNode");
14143 SDUse *Ops = OperandRecycler.allocate(
14144 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
14145
14146 bool IsDivergent = false;
14147 for (unsigned I = 0; I != Vals.size(); ++I) {
14148 Ops[I].setUser(Node);
14149 Ops[I].setInitial(Vals[I]);
14150 EVT VT = Ops[I].getValueType();
14151
14152 // Skip Chain. It does not carry divergence.
14153 if (VT != MVT::Other &&
14154 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
14155 Ops[I].getNode()->isDivergent()) {
14156 IsDivergent = true;
14157 }
14158 }
14159 Node->NumOperands = Vals.size();
14160 Node->OperandList = Ops;
14161 if (!TLI->isSDNodeAlwaysUniform(Node)) {
14162 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
14163 Node->SDNodeBits.IsDivergent = IsDivergent;
14164 }
14165 checkForCycles(Node);
14166}
14167
14170 size_t Limit = SDNode::getMaxNumOperands();
14171 while (Vals.size() > Limit) {
14172 unsigned SliceIdx = Vals.size() - Limit;
14173 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
14174 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
14175 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
14176 Vals.emplace_back(NewTF);
14177 }
14178 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
14179}
14180
14182 EVT VT, SDNodeFlags Flags) {
14183 switch (Opcode) {
14184 default:
14185 return SDValue();
14186 case ISD::ADD:
14187 case ISD::OR:
14188 case ISD::XOR:
14189 case ISD::UMAX:
14190 return getConstant(0, DL, VT);
14191 case ISD::MUL:
14192 return getConstant(1, DL, VT);
14193 case ISD::AND:
14194 case ISD::UMIN:
14195 return getAllOnesConstant(DL, VT);
14196 case ISD::SMAX:
14198 case ISD::SMIN:
14200 case ISD::FADD:
14201 // If flags allow, prefer positive zero since it's generally cheaper
14202 // to materialize on most targets.
14203 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
14204 case ISD::FMUL:
14205 return getConstantFP(1.0, DL, VT);
14206 case ISD::FMINNUM:
14207 case ISD::FMAXNUM: {
14208 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
14209 const fltSemantics &Semantics = VT.getFltSemantics();
14210 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
14211 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
14212 APFloat::getLargest(Semantics);
14213 if (Opcode == ISD::FMAXNUM)
14214 NeutralAF.changeSign();
14215
14216 return getConstantFP(NeutralAF, DL, VT);
14217 }
14218 case ISD::FMINIMUM:
14219 case ISD::FMAXIMUM: {
14220 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
14221 const fltSemantics &Semantics = VT.getFltSemantics();
14222 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
14223 : APFloat::getLargest(Semantics);
14224 if (Opcode == ISD::FMAXIMUM)
14225 NeutralAF.changeSign();
14226
14227 return getConstantFP(NeutralAF, DL, VT);
14228 }
14229
14230 }
14231}
14232
14233/// Helper used to make a call to a library function that has one argument of
14234/// pointer type.
14235///
14236/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
14237/// used to get or set floating-point state. They have one argument of pointer
14238/// type, which points to the memory region containing bits of the
14239/// floating-point state. The value returned by such function is ignored in the
14240/// created call.
14241///
14242/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
14243/// \param Ptr Pointer used to save/load state.
14244/// \param InChain Ingoing token chain.
14245/// \returns Outgoing chain token.
14247 SDValue InChain,
14248 const SDLoc &DLoc) {
14249 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
14251 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
14252 RTLIB::LibcallImpl LibcallImpl =
14253 TLI->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
14254 if (LibcallImpl == RTLIB::Unsupported)
14255 reportFatalUsageError("emitting call to unsupported libcall");
14256
14257 SDValue Callee =
14258 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
14260 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
14261 TLI->getLibcallImplCallingConv(LibcallImpl),
14262 Type::getVoidTy(*getContext()), Callee, std::move(Args));
14263 return TLI->LowerCallTo(CLI).second;
14264}
14265
14267 assert(From && To && "Invalid SDNode; empty source SDValue?");
14268 auto I = SDEI.find(From);
14269 if (I == SDEI.end())
14270 return;
14271
14272 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
14273 // the iterator, hence the need to make a copy to prevent a use-after-free.
14274 NodeExtraInfo NEI = I->second;
14275 if (LLVM_LIKELY(!NEI.PCSections)) {
14276 // No deep copy required for the types of extra info set.
14277 //
14278 // FIXME: Investigate if other types of extra info also need deep copy. This
14279 // depends on the types of nodes they can be attached to: if some extra info
14280 // is only ever attached to nodes where a replacement To node is always the
14281 // node where later use and propagation of the extra info has the intended
14282 // semantics, no deep copy is required.
14283 SDEI[To] = std::move(NEI);
14284 return;
14285 }
14286
14287 const SDNode *EntrySDN = getEntryNode().getNode();
14288
14289 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
14290 // through the replacement of From with To. Otherwise, replacements of a node
14291 // (From) with more complex nodes (To and its operands) may result in lost
14292 // extra info where the root node (To) is insignificant in further propagating
14293 // and using extra info when further lowering to MIR.
14294 //
14295 // In the first step pre-populate the visited set with the nodes reachable
14296 // from the old From node. This avoids copying NodeExtraInfo to parts of the
14297 // DAG that is not new and should be left untouched.
14298 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
14299 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
14300 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
14301 if (MaxDepth == 0) {
14302 // Remember this node in case we need to increase MaxDepth and continue
14303 // populating FromReach from this node.
14304 Leafs.emplace_back(N);
14305 return;
14306 }
14307 if (!FromReach.insert(N).second)
14308 return;
14309 for (const SDValue &Op : N->op_values())
14310 Self(Self, Op.getNode(), MaxDepth - 1);
14311 };
14312
14313 // Copy extra info to To and all its transitive operands (that are new).
14315 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
14316 if (FromReach.contains(N))
14317 return true;
14318 if (!Visited.insert(N).second)
14319 return true;
14320 if (EntrySDN == N)
14321 return false;
14322 for (const SDValue &Op : N->op_values()) {
14323 if (N == To && Op.getNode() == EntrySDN) {
14324 // Special case: New node's operand is the entry node; just need to
14325 // copy extra info to new node.
14326 break;
14327 }
14328 if (!Self(Self, Op.getNode()))
14329 return false;
14330 }
14331 // Copy only if entry node was not reached.
14332 SDEI[N] = NEI;
14333 return true;
14334 };
14335
14336 // We first try with a lower MaxDepth, assuming that the path to common
14337 // operands between From and To is relatively short. This significantly
14338 // improves performance in the common case. The initial MaxDepth is big
14339 // enough to avoid retry in the common case; the last MaxDepth is large
14340 // enough to avoid having to use the fallback below (and protects from
14341 // potential stack exhaustion from recursion).
14342 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
14343 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
14344 // StartFrom is the previous (or initial) set of leafs reachable at the
14345 // previous maximum depth.
14347 std::swap(StartFrom, Leafs);
14348 for (const SDNode *N : StartFrom)
14349 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
14350 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
14351 return;
14352 // This should happen very rarely (reached the entry node).
14353 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
14354 assert(!Leafs.empty());
14355 }
14356
14357 // This should not happen - but if it did, that means the subgraph reachable
14358 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
14359 // could not visit all reachable common operands. Consequently, we were able
14360 // to reach the entry node.
14361 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
14362 assert(false && "From subgraph too complex - increase max. MaxDepth?");
14363 // Best-effort fallback if assertions disabled.
14364 SDEI[To] = std::move(NEI);
14365}
14366
14367#ifndef NDEBUG
14368static void checkForCyclesHelper(const SDNode *N,
14371 const llvm::SelectionDAG *DAG) {
14372 // If this node has already been checked, don't check it again.
14373 if (Checked.count(N))
14374 return;
14375
14376 // If a node has already been visited on this depth-first walk, reject it as
14377 // a cycle.
14378 if (!Visited.insert(N).second) {
14379 errs() << "Detected cycle in SelectionDAG\n";
14380 dbgs() << "Offending node:\n";
14381 N->dumprFull(DAG); dbgs() << "\n";
14382 abort();
14383 }
14384
14385 for (const SDValue &Op : N->op_values())
14386 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
14387
14388 Checked.insert(N);
14389 Visited.erase(N);
14390}
14391#endif
14392
14394 const llvm::SelectionDAG *DAG,
14395 bool force) {
14396#ifndef NDEBUG
14397 bool check = force;
14398#ifdef EXPENSIVE_CHECKS
14399 check = true;
14400#endif // EXPENSIVE_CHECKS
14401 if (check) {
14402 assert(N && "Checking nonexistent SDNode");
14405 checkForCyclesHelper(N, visited, checked, DAG);
14406 }
14407#endif // !NDEBUG
14408}
14409
14410void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
14411 checkForCycles(DAG->getRoot().getNode(), DAG, force);
14412}
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
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
This file implements the BitVector class.
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")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
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:569
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:335
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.
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.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB)
static bool shouldLowerMemFuncForSize(const MachineFunction &MF)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG)
#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)
#define P(N)
PowerPC Reduce CR logical Operation
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
Contains matchers for matching SelectionDAG nodes and values.
static Type * getValueType(Value *V)
Returns the type of the given value/instruction V.
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 SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo, BatchAAResults *BatchAA)
static SDValue getFixedOrScalableQuantity(SelectionDAG &DAG, const SDLoc &DL, EVT VT, Ty Quantity)
static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo)
Lower the call to 'memset' intrinsic function into a series of store operations.
static std::optional< APInt > FoldValueWithUndef(unsigned Opcode, const APInt &C1, bool IsUndef1, const APInt &C2, bool IsUndef2)
static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, SelectionDAG &DAG)
static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC, SDVTList VTList, ArrayRef< SDValue > OpList)
static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, const TargetLowering &TLI, const ConstantDataArraySlice &Slice)
getMemsetStringVal - Similar to getMemsetValue.
static cl::opt< bool > EnableMemCpyDAGOpt("enable-memcpy-dag-opt", cl::Hidden, cl::init(true), cl::desc("Gang up loads and stores generated by inlining of memcpy"))
static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B)
static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList)
AddNodeIDValueTypes - Value type lists are intern'd so we can represent them solely with their pointe...
static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef< int > M)
Swaps the values of N1 and N2.
static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice)
Returns true if memcpy source is constant data.
static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo)
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 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"))
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
This file describes how to lower LLVM code to machine code.
static void removeOperands(MachineInstr &MI, unsigned i)
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static const fltSemantics & IEEEsingle()
Definition APFloat.h:296
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:334
static constexpr roundingMode rmTowardZero
Definition APFloat.h:348
static const fltSemantics & BFloat()
Definition APFloat.h:295
static const fltSemantics & IEEEquad()
Definition APFloat.h:298
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:347
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:346
static const fltSemantics & IEEEhalf()
Definition APFloat.h:294
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:360
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1102
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1190
void copySign(const APFloat &RHS)
Definition APFloat.h:1284
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6053
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1172
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Definition APFloat.h:1414
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1163
bool isFinite() const
Definition APFloat.h:1436
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1329
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1181
bool isSignaling() const
Definition APFloat.h:1433
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1217
bool isZero() const
Definition APFloat.h:1427
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1120
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1314
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1080
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1208
bool isPosZero() const
Definition APFloat.h:1442
bool isNegZero() const
Definition APFloat.h:1443
void changeSign()
Definition APFloat.h:1279
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1091
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1971
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2055
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1573
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1407
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1012
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1541
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1392
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1671
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition APInt.h:1386
LLVM_ABI APInt getHiBits(unsigned numBits) const
Compute an APInt containing numBits highbits from this APInt.
Definition APInt.cpp:639
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1033
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1513
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:936
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1331
APInt abs() const
Get the absolute value.
Definition APInt.h:1796
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2026
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1183
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:259
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1666
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1489
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1112
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1644
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1397
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1154
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:768
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:835
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1167
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1640
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1629
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1599
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:651
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2086
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2100
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1041
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1141
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:397
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1436
unsigned logBase2() const
Definition APInt.h:1762
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2036
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:828
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1736
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1151
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:985
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1368
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:874
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:746
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1258
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static bool isSameValue(const APInt &I1, const APInt &I2)
Determine if two APInts have the same value, after zero-extending one of them (if needed!...
Definition APInt.h:554
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1418
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1389
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:482
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1238
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:852
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1222
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2045
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
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()
Definition BitVector.h:411
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition BitVector.h:360
void clear()
clear - Removes all bits from the bitvector.
Definition BitVector.h:354
BitVector & set()
Definition BitVector.h:370
bool none() const
none - Returns true if none of the bits are set.
Definition BitVector.h:207
size_type size() const
size - 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:907
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 std::optional< std::pair< APInt, APInt > > isConstantSequence() const
If this BuildVector is constant and represents the numerical series "<a, a+n, a+2n,...
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 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:285
const APFloat & getValue() const
Definition Constants.h:329
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:165
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:162
LLVM_ABI Type * getType() const
This class represents a range of values.
LLVM_ABI ConstantRange multiply(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
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 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 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:214
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:123
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
const char * getSymbol() const
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:209
Data structure describing the variable locations in a function.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:703
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:352
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
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:1078
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1442
Machine Value Type.
SimpleValueType SimpleTy
static MVT getIntegerVT(unsigned BitWidth)
Abstract base class for all machine specific constantpool value subclasses.
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.
LLVM_ABI MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt, MachineMemOperand *MMO)
MachineMemOperand * MMO
Memory reference information.
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
unsigned getRawSubclassData() const
Return the SubclassData value, without HasDebugValue.
EVT getMemoryVT() const
Return the type of the in-memory value.
Representation for a specific memory location.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:230
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:298
The optimization diagnostic interface.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
Class to represent pointers.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Analysis providing profile information.
void Deallocate(SubClass *E)
Deallocate - Release storage for the pointed-to object.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Keeps track of dbg_value information through SDISel.
LLVM_ABI void add(SDDbgValue *V, bool isParameter)
LLVM_ABI void erase(const SDNode *Node)
Invalidate all DbgValues attached to the node and remove it from the Node-to-DbgValues map.
Holds the information from a dbg_label node through SDISel.
Holds the information for a single machine location through SDISel; either an SDNode,...
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
@ SDNODE
Value is the result of an expression.
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
unsigned getIROrder() const
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
LLVM_ABI void dumprFull(const SelectionDAG *G=nullptr) const
printrFull to dbgs().
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isDivergent() const
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
static constexpr size_t getMaxNumOperands()
Return the maximum number of operands that a SDNode can hold.
iterator_range< use_iterator > uses()
MemSDNodeBitfields MemSDNodeBits
LLVM_ABI void Profile(FoldingSetNodeID &ID) const
Gather unique data for the node.
bool getHasDebugValue() const
SDNodeFlags getFlags() const
void setNodeId(int Id)
Set unique node id.
LLVM_ABI void intersectFlagsWith(const SDNodeFlags Flags)
Clear any flags in this node that aren't also set in Flags.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
static LLVM_ABI bool areOnlyUsersOf(ArrayRef< const SDNode * > Nodes, const SDNode *N)
Return true if all the users of N are contained in Nodes.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if this node is an operand of N.
const APInt & getConstantOperandAPInt(unsigned Num) const
Helper method returns the APInt of a ConstantSDNode operand.
std::optional< APInt > bitcastToAPInt() const
LLVM_ABI bool hasPredecessor(const SDNode *N) const
Return true if N is a predecessor of this node.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
op_iterator op_end() const
op_iterator op_begin() const
static use_iterator use_end()
LLVM_ABI void DropOperands()
Release the operands and set this node to have zero operands.
SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
Create an SDNode.
Represents a use of a SDNode.
SDNode * getUser()
This returns the SDNode that contains this Use.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if the referenced return value is an operand of N.
SDValue()=default
LLVM_ABI bool reachesChainWithoutSideEffects(SDValue Dest, unsigned Depth=2) const
Return true if this operand (which must be a chain) reaches the specified operand without crossing an...
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
virtual void verifyTargetNode(const SelectionDAG &DAG, const SDNode *N) const
Checks that the given target-specific node is valid. Aborts if it is not.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC)
LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI)
In most cases this function returns the ABI alignment for a given type, except for illegal vector typ...
LLVM_ABI SDValue getVPZeroExtendInReg(SDValue Op, SDValue Mask, SDValue EVL, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI 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.
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 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 FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl)
Constant fold a setcc to true or false.
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 getNeutralElement(unsigned Opcode, const SDLoc &DL, EVT VT, SDNodeFlags Flags)
Get the (commutative) neutral element for the given opcode, if it exists.
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 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)
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false)
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
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 SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A)
Return an AssertAlignSDNode.
LLVM_ABI SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI bool canIgnoreSignBitOfZero(const SDUse &Use) const
Check if a use of a float value is insensitive to signed zeros.
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getBitcastedZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
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 SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask, SDValue EVL)
Convert a vector-predicated Op, which must be an integer vector, to the vector-type VT,...
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 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 void dump(bool Sorted=false) const
Dump the textual format of this DAG.
LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
For each demanded element of a vector, see if it is known to be zero.
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
LLVM_ABI void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI std::pair< SDValue, SDValue > UnrollVectorOverflowOp(SDNode *N, unsigned ResNE=0)
Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
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 expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
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 getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getLoadFFVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachineMemOperand *MMO)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
LLVM_ABI std::pair< SDValue, SDValue > getMemcmp(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, const CallInst *CI)
Lower a memcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, const SDLoc &DLoc)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly=false, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, if PoisonOnly is false,...
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getSrcValue(const Value *v)
Construct a node to track a Value* through the backend.
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const
Determine if the result of the signed mul of 2 nodes can overflow.
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
LLVM_ABI 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 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 bool isKnownToBeAPowerOfTwo(SDValue Val, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
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 isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI std::optional< unsigned > getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI std::pair< SDValue, SDValue > SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL)
Split the explicit vector length parameter of a VP operation.
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getVPLogicalNOT(const SDLoc &DL, SDValue Val, SDValue Mask, SDValue EVL, EVT VT)
Create a vector-predicated logical NOT operation as (VP_XOR Val, BooleanOne, Mask,...
LLVM_ABI SDValue getMaskFromElementCount(const SDLoc &DL, EVT VT, ElementCount Len)
Return a vector with the first 'Len' lanes set to true and remaining lanes set to false.
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
LLVM_ABI bool isKnownNeverZeroFloat(SDValue Op) const
Test whether the given floating point SDValue is known to never be positive or negative zero.
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 Alignment, bool isVol, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
LLVM_ABI SDValue getJumpTable(int JTI, EVT VT, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask, SDValue EVL)
Convert a vector-predicated Op, which must be of integer type, to the vector-type integer type VT,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void getTopologicallyOrderedNodes(SmallVectorImpl< const SDNode * > &SortedNodes) const
Get all the nodes in their topological order without modifying any states.
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI 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 bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, bool PoisonOnly=false, bool ConsiderFlags=true, unsigned Depth=0) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
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 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 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 void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE, Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, MachineModuleInfo &MMI, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
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)
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
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.
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.
unsigned getMaxStoresPerMemmove(bool OptSize) const
Get maximum # of store operations permitted for llvm.memmove.
virtual unsigned getMaxGluedStoresPerMemcpy() const
Get maximum # of store operations to be glued together.
std::vector< ArgListEntry > ArgListTy
unsigned getMaxStoresPerMemset(bool OptSize) const
Get maximum # of store operations permitted for llvm.memset.
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) const
Determines the optimal series of memory ops to replace the memset / memcpy.
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:628
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:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:294
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:230
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:905
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:233
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:256
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
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.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3131
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3118
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3108
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3182
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3123
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2269
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3173
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:3009
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2274
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3103
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3113
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, bool isIntegerLike)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:24
LLVM_ABI CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical AND between different comparisons of identical values: ((X op1 Y) & (X...
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:809
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:256
@ CTLZ_ZERO_UNDEF
Definition ISDOpcodes.h:782
@ TargetConstantPool
Definition ISDOpcodes.h:184
@ 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:506
@ 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:231
@ 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:533
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:270
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:595
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:773
@ TargetBlockAddress
Definition ISDOpcodes.h:186
@ 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:289
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:517
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:259
@ 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:843
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:513
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:215
@ 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:870
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:579
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:412
@ 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:746
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:900
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
Definition ISDOpcodes.h:993
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:523
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition ISDOpcodes.h:983
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:249
@ 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
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:834
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:714
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:664
@ TargetExternalSymbol
Definition ISDOpcodes.h:185
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ CTTZ_ZERO_UNDEF
Bit counting operators with an undefined result for zero inputs.
Definition ISDOpcodes.h:781
@ TargetJumpTable
Definition ISDOpcodes.h:183
@ TargetIndex
TargetIndex - Like a constant pool entry, but with completely target-dependent semantics.
Definition ISDOpcodes.h:193
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ 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:817
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:347
@ STEP_VECTOR
STEP_VECTOR(IMM) - Returns a scalable vector whose lanes are comprised of a linear sequence of unsign...
Definition ISDOpcodes.h:690
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:536
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:369
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:786
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:228
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:242
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:671
@ 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:225
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:343
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:180
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ 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:703
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:764
@ 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:644
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:609
@ 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:571
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:219
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:840
@ TargetConstantFP
Definition ISDOpcodes.h:175
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:801
@ 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:381
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:351
@ ATOMIC_LOAD_FMINIMUM
@ TargetFrameIndex
Definition ISDOpcodes.h:182
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:889
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:878
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:726
@ 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:968
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:795
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:323
@ 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
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:495
@ 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:916
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:174
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:500
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:738
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:200
@ 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:734
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:709
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:299
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:680
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:236
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:560
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ VECTOR_SPLICE
VECTOR_SPLICE(VEC1, VEC2, IMM) - Returns a subvector of the same type as VEC1/VEC2 from CONCAT_VECTOR...
Definition ISDOpcodes.h:656
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ 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:949
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:698
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:911
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
Definition ISDOpcodes.h:987
@ 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:935
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:846
@ 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:823
@ 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:529
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:360
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:721
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:333
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:208
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:181
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:551
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 matchUnaryFpPredicate(SDValue Op, std::function< bool(ConstantFPSDNode *)> Match, bool AllowUndefs=false)
Hook for matching ConstantFPSDNode predicate.
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 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 isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
unsigned getUnorderedFlavor(CondCode Cond)
This function returns 0 if the condition is always false if an operand is a NaN, 1 if the condition i...
LLVM_ABI std::optional< unsigned > getVPExplicitVectorLengthIdx(unsigned Opcode)
The operand position of the explicit vector length parameter.
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
LLVM_ABI bool isFreezeUndef(const SDNode *N)
Return true if the specified node is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI std::optional< unsigned > getVPForBaseOpcode(unsigned Opcode)
Translate this non-VP Opcode to its corresponding VP Opcode.
MemIndexType
MemIndexType enum - This enum defines how to interpret MGATHER/SCATTER's index parameter when calcula...
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
bool matchUnaryPredicateImpl(SDValue Op, std::function< bool(ConstNodeType *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant BUI...
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
LLVM_ABI NodeType getInverseMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns ISD::(U|S)MAX and ISD::(U|S)MIN,...
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
LLVM_ABI bool isVPReduction(unsigned Opcode)
Whether this is a vector-predicated reduction opcode.
bool matchUnaryPredicate(SDValue Op, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
LLVM_ABI bool isBuildVectorOfConstantFPSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantFPSDNode or undef.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
LLVM_ABI CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical OR between different comparisons of identical values: ((X op1 Y) | (X ...
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
deferredval_ty< 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()...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
LLVM_ABI Libcall getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMCPY_ELEMENT_UNORDERED_ATOMIC - Return MEMCPY_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMSET_ELEMENT_UNORDERED_ATOMIC - Return MEMSET_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMMOVE_ELEMENT_UNORDERED_ATOMIC - Return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_* value for the given e...
bool sd_match(SDNode *N, const SelectionDAG *DAG, Pattern &&P)
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:667
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:344
@ Offset
Definition DWP.cpp:532
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:362
ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:241
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:1757
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:1737
MaybeAlign getAlign(const CallInst &I, unsigned Index)
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:1613
LLVM_ABI SDValue getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs)
If V is a bitwise not, returns the inverted operand.
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:2530
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:293
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:303
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1625
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2184
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
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:632
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:1595
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:1537
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:1744
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:1580
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:331
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:279
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:1634
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1611
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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:1751
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
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:82
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_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
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1561
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
LLVM_ABI bool isNullConstantOrUndef(SDValue V)
Returns true if V is a constant integer zero or an UNDEF node.
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:543
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:1883
constexpr unsigned BitWidth
bool funcReturnsFirstArgOfCall(const CallInst &CI)
Returns true if the parent of CI returns CI's first argument after calling CI.
Definition Analysis.cpp:723
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.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
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:572
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:1598
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1638
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 isNeutralConstant(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo)
Returns true if V is a neutral element of Opc with Flags.
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:373
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:180
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:761
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:781
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:778
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
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:395
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:137
intptr_t getRawBits() const
Definition ValueTypes.h:512
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:74
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:121
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:284
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:300
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:147
ElementCount getVectorElementCount() const
Definition ValueTypes.h:350
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:373
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:359
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:385
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:316
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:65
bool isFixedLengthVector() const
Definition ValueTypes.h:181
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:168
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:323
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:292
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:256
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:174
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:328
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:142
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:336
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:308
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:453
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:152
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:301
LLVM_ABI KnownBits sextInReg(unsigned SrcBitWidth) const
Return known bits for a in-register sign extension of the value we're tracking.
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:255
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:108
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:80
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:124
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:242
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).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:66
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:274
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.
void makeNegative()
Make this value negative.
Definition KnownBits.h:119
void setAllConflict()
Make all bits known to be both zero and one.
Definition KnownBits.h:99
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:161
KnownBits byteSwap() const
Definition KnownBits.h:514
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:289
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:86
KnownBits reverseBits() const
Definition KnownBits.h:518
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:233
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:172
void resetAll()
Resets the known state of all bits.
Definition KnownBits.h:74
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:321
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:111
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:225
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:311
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:180
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:196
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:145
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).
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:60
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:114
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:326
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:105
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:53
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:280
void insertBits(const KnownBits &SubBits, unsigned BitPosition)
Insert the bits from a smaller known bits starting at bitPosition.
Definition KnownBits.h:219
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:167
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 avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
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
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)
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)