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());
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::Other, 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: {
5220 // If we are looking at the loaded value of the SDNode.
5221 if (Op.getResNo() != 0)
5222 break;
5223
5225 if (const MDNode *Ranges = LD->getRanges()) {
5226 if (DemandedElts != 1)
5227 break;
5228
5230 if (VTBits > CR.getBitWidth()) {
5231 switch (LD->getExtensionType()) {
5232 case ISD::SEXTLOAD:
5233 CR = CR.signExtend(VTBits);
5234 break;
5235 case ISD::ZEXTLOAD:
5236 CR = CR.zeroExtend(VTBits);
5237 break;
5238 default:
5239 break;
5240 }
5241 }
5242
5243 if (VTBits != CR.getBitWidth())
5244 break;
5245 return std::min(CR.getSignedMin().getNumSignBits(),
5247 }
5248
5249 unsigned ExtType = LD->getExtensionType();
5250 switch (ExtType) {
5251 default:
5252 break;
5253 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5254 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5255 return VTBits - Tmp + 1;
5256 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5257 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5258 return VTBits - Tmp;
5259 case ISD::NON_EXTLOAD:
5260 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5261 // We only need to handle vectors - computeKnownBits should handle
5262 // scalar cases.
5263 Type *CstTy = Cst->getType();
5264 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5265 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5266 VTBits == CstTy->getScalarSizeInBits()) {
5267 Tmp = VTBits;
5268 for (unsigned i = 0; i != NumElts; ++i) {
5269 if (!DemandedElts[i])
5270 continue;
5271 if (Constant *Elt = Cst->getAggregateElement(i)) {
5272 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5273 const APInt &Value = CInt->getValue();
5274 Tmp = std::min(Tmp, Value.getNumSignBits());
5275 continue;
5276 }
5277 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5278 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5279 Tmp = std::min(Tmp, Value.getNumSignBits());
5280 continue;
5281 }
5282 }
5283 // Unknown type. Conservatively assume no bits match sign bit.
5284 return 1;
5285 }
5286 return Tmp;
5287 }
5288 }
5289 break;
5290 }
5291
5292 break;
5293 }
5296 case ISD::ATOMIC_SWAP:
5308 case ISD::ATOMIC_LOAD: {
5309 auto *AT = cast<AtomicSDNode>(Op);
5310 // If we are looking at the loaded value.
5311 if (Op.getResNo() == 0) {
5312 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5313 if (Tmp == VTBits)
5314 return 1; // early-out
5315
5316 // For atomic_load, prefer to use the extension type.
5317 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5318 switch (AT->getExtensionType()) {
5319 default:
5320 break;
5321 case ISD::SEXTLOAD:
5322 return VTBits - Tmp + 1;
5323 case ISD::ZEXTLOAD:
5324 return VTBits - Tmp;
5325 }
5326 }
5327
5328 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5329 return VTBits - Tmp + 1;
5330 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5331 return VTBits - Tmp;
5332 }
5333 break;
5334 }
5335 }
5336
5337 // Allow the target to implement this method for its nodes.
5338 if (Opcode >= ISD::BUILTIN_OP_END ||
5339 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5340 Opcode == ISD::INTRINSIC_W_CHAIN ||
5341 Opcode == ISD::INTRINSIC_VOID) {
5342 // TODO: This can probably be removed once target code is audited. This
5343 // is here purely to reduce patch size and review complexity.
5344 if (!VT.isScalableVector()) {
5345 unsigned NumBits =
5346 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5347 if (NumBits > 1)
5348 FirstAnswer = std::max(FirstAnswer, NumBits);
5349 }
5350 }
5351
5352 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5353 // use this information.
5354 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5355 return std::max(FirstAnswer, Known.countMinSignBits());
5356}
5357
5359 unsigned Depth) const {
5360 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5361 return Op.getScalarValueSizeInBits() - SignBits + 1;
5362}
5363
5365 const APInt &DemandedElts,
5366 unsigned Depth) const {
5367 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5368 return Op.getScalarValueSizeInBits() - SignBits + 1;
5369}
5370
5372 unsigned Depth) const {
5373 // Early out for FREEZE.
5374 if (Op.getOpcode() == ISD::FREEZE)
5375 return true;
5376
5377 EVT VT = Op.getValueType();
5378 APInt DemandedElts = VT.isFixedLengthVector()
5380 : APInt(1, 1);
5381 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
5382}
5383
5385 const APInt &DemandedElts,
5386 bool PoisonOnly,
5387 unsigned Depth) const {
5388 unsigned Opcode = Op.getOpcode();
5389
5390 // Early out for FREEZE.
5391 if (Opcode == ISD::FREEZE)
5392 return true;
5393
5394 if (Depth >= MaxRecursionDepth)
5395 return false; // Limit search depth.
5396
5397 if (isIntOrFPConstant(Op))
5398 return true;
5399
5400 switch (Opcode) {
5401 case ISD::CONDCODE:
5402 case ISD::VALUETYPE:
5403 case ISD::FrameIndex:
5405 case ISD::CopyFromReg:
5406 return true;
5407
5408 case ISD::POISON:
5409 return false;
5410
5411 case ISD::UNDEF:
5412 return PoisonOnly;
5413
5414 case ISD::BUILD_VECTOR:
5415 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5416 // this shouldn't affect the result.
5417 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5418 if (!DemandedElts[i])
5419 continue;
5421 Depth + 1))
5422 return false;
5423 }
5424 return true;
5425
5427 SDValue Src = Op.getOperand(0);
5428 if (Src.getValueType().isScalableVector())
5429 break;
5430 uint64_t Idx = Op.getConstantOperandVal(1);
5431 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5432 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5433 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, PoisonOnly,
5434 Depth + 1);
5435 }
5436
5437 case ISD::INSERT_SUBVECTOR: {
5438 if (Op.getValueType().isScalableVector())
5439 break;
5440 SDValue Src = Op.getOperand(0);
5441 SDValue Sub = Op.getOperand(1);
5442 uint64_t Idx = Op.getConstantOperandVal(2);
5443 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5444 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5445 APInt DemandedSrcElts = DemandedElts;
5446 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5447
5448 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5449 Sub, DemandedSubElts, PoisonOnly, Depth + 1))
5450 return false;
5451 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5452 Src, DemandedSrcElts, PoisonOnly, Depth + 1))
5453 return false;
5454 return true;
5455 }
5456
5458 SDValue Src = Op.getOperand(0);
5459 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5460 EVT SrcVT = Src.getValueType();
5461 if (SrcVT.isFixedLengthVector() && IndexC &&
5462 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5463 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5464 IndexC->getZExtValue());
5465 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, PoisonOnly,
5466 Depth + 1);
5467 }
5468 break;
5469 }
5470
5472 SDValue InVec = Op.getOperand(0);
5473 SDValue InVal = Op.getOperand(1);
5474 SDValue EltNo = Op.getOperand(2);
5475 EVT VT = InVec.getValueType();
5476 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5477 if (IndexC && VT.isFixedLengthVector() &&
5478 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5479 if (DemandedElts[IndexC->getZExtValue()] &&
5481 return false;
5482 APInt InVecDemandedElts = DemandedElts;
5483 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5484 if (!!InVecDemandedElts &&
5486 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5487 InVecDemandedElts, PoisonOnly, Depth + 1))
5488 return false;
5489 return true;
5490 }
5491 break;
5492 }
5493
5495 // Check upper (known undef) elements.
5496 if (DemandedElts.ugt(1) && !PoisonOnly)
5497 return false;
5498 // Check element zero.
5499 if (DemandedElts[0] && !isGuaranteedNotToBeUndefOrPoison(
5500 Op.getOperand(0), PoisonOnly, Depth + 1))
5501 return false;
5502 return true;
5503
5504 case ISD::SPLAT_VECTOR:
5505 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), PoisonOnly,
5506 Depth + 1);
5507
5508 case ISD::VECTOR_SHUFFLE: {
5509 APInt DemandedLHS, DemandedRHS;
5510 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5511 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5512 DemandedElts, DemandedLHS, DemandedRHS,
5513 /*AllowUndefElts=*/false))
5514 return false;
5515 if (!DemandedLHS.isZero() &&
5516 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS,
5517 PoisonOnly, Depth + 1))
5518 return false;
5519 if (!DemandedRHS.isZero() &&
5520 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS,
5521 PoisonOnly, Depth + 1))
5522 return false;
5523 return true;
5524 }
5525
5526 case ISD::SHL:
5527 case ISD::SRL:
5528 case ISD::SRA:
5529 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5530 // enough to check operand 0 if Op can't create undef/poison.
5531 return !canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly,
5532 /*ConsiderFlags*/ true, Depth) &&
5533 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5534 PoisonOnly, Depth + 1);
5535
5536 case ISD::BSWAP:
5537 case ISD::CTPOP:
5538 case ISD::BITREVERSE:
5539 case ISD::AND:
5540 case ISD::OR:
5541 case ISD::XOR:
5542 case ISD::ADD:
5543 case ISD::SUB:
5544 case ISD::MUL:
5545 case ISD::SADDSAT:
5546 case ISD::UADDSAT:
5547 case ISD::SSUBSAT:
5548 case ISD::USUBSAT:
5549 case ISD::SSHLSAT:
5550 case ISD::USHLSAT:
5551 case ISD::SMIN:
5552 case ISD::SMAX:
5553 case ISD::UMIN:
5554 case ISD::UMAX:
5555 case ISD::ZERO_EXTEND:
5556 case ISD::SIGN_EXTEND:
5557 case ISD::ANY_EXTEND:
5558 case ISD::TRUNCATE:
5559 case ISD::VSELECT: {
5560 // If Op can't create undef/poison and none of its operands are undef/poison
5561 // then Op is never undef/poison. A difference from the more common check
5562 // below, outside the switch, is that we handle elementwise operations for
5563 // which the DemandedElts mask is valid for all operands here.
5564 return !canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly,
5565 /*ConsiderFlags*/ true, Depth) &&
5566 all_of(Op->ops(), [&](SDValue V) {
5567 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts,
5568 PoisonOnly, Depth + 1);
5569 });
5570 }
5571
5572 // TODO: Search for noundef attributes from library functions.
5573
5574 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5575
5576 default:
5577 // Allow the target to implement this method for its nodes.
5578 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5579 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5580 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5581 Op, DemandedElts, *this, PoisonOnly, Depth);
5582 break;
5583 }
5584
5585 // If Op can't create undef/poison and none of its operands are undef/poison
5586 // then Op is never undef/poison.
5587 // NOTE: TargetNodes can handle this in themselves in
5588 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5589 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5590 return !canCreateUndefOrPoison(Op, PoisonOnly, /*ConsiderFlags*/ true,
5591 Depth) &&
5592 all_of(Op->ops(), [&](SDValue V) {
5593 return isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, Depth + 1);
5594 });
5595}
5596
5598 bool ConsiderFlags,
5599 unsigned Depth) const {
5600 EVT VT = Op.getValueType();
5601 APInt DemandedElts = VT.isFixedLengthVector()
5603 : APInt(1, 1);
5604 return canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly, ConsiderFlags,
5605 Depth);
5606}
5607
5609 bool PoisonOnly, bool ConsiderFlags,
5610 unsigned Depth) const {
5611 if (ConsiderFlags && Op->hasPoisonGeneratingFlags())
5612 return true;
5613
5614 unsigned Opcode = Op.getOpcode();
5615 switch (Opcode) {
5616 case ISD::AssertSext:
5617 case ISD::AssertZext:
5618 case ISD::AssertAlign:
5620 // Assertion nodes can create poison if the assertion fails.
5621 return true;
5622
5623 case ISD::FREEZE:
5627 case ISD::SADDSAT:
5628 case ISD::UADDSAT:
5629 case ISD::SSUBSAT:
5630 case ISD::USUBSAT:
5631 case ISD::MULHU:
5632 case ISD::MULHS:
5633 case ISD::AVGFLOORS:
5634 case ISD::AVGFLOORU:
5635 case ISD::AVGCEILS:
5636 case ISD::AVGCEILU:
5637 case ISD::ABDU:
5638 case ISD::ABDS:
5639 case ISD::SMIN:
5640 case ISD::SMAX:
5641 case ISD::SCMP:
5642 case ISD::UMIN:
5643 case ISD::UMAX:
5644 case ISD::UCMP:
5645 case ISD::AND:
5646 case ISD::XOR:
5647 case ISD::ROTL:
5648 case ISD::ROTR:
5649 case ISD::FSHL:
5650 case ISD::FSHR:
5651 case ISD::BSWAP:
5652 case ISD::CTTZ:
5653 case ISD::CTLZ:
5654 case ISD::CTLS:
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 case ISD::CLMUL:
6893 return APIntOps::clmul(C1, C2);
6894 case ISD::CLMULR:
6895 return APIntOps::clmulr(C1, C2);
6896 case ISD::CLMULH:
6897 return APIntOps::clmulh(C1, C2);
6898 }
6899 return std::nullopt;
6900}
6901// Handle constant folding with UNDEF.
6902// TODO: Handle more cases.
6903static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
6904 bool IsUndef1, const APInt &C2,
6905 bool IsUndef2) {
6906 if (!(IsUndef1 || IsUndef2))
6907 return FoldValue(Opcode, C1, C2);
6908
6909 // Fold and(x, undef) -> 0
6910 // Fold mul(x, undef) -> 0
6911 if (Opcode == ISD::AND || Opcode == ISD::MUL)
6912 return APInt::getZero(C1.getBitWidth());
6913
6914 return std::nullopt;
6915}
6916
6918 const GlobalAddressSDNode *GA,
6919 const SDNode *N2) {
6920 if (GA->getOpcode() != ISD::GlobalAddress)
6921 return SDValue();
6922 if (!TLI->isOffsetFoldingLegal(GA))
6923 return SDValue();
6924 auto *C2 = dyn_cast<ConstantSDNode>(N2);
6925 if (!C2)
6926 return SDValue();
6927 int64_t Offset = C2->getSExtValue();
6928 switch (Opcode) {
6929 case ISD::ADD:
6930 case ISD::PTRADD:
6931 break;
6932 case ISD::SUB: Offset = -uint64_t(Offset); break;
6933 default: return SDValue();
6934 }
6935 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
6936 GA->getOffset() + uint64_t(Offset));
6937}
6938
6940 switch (Opcode) {
6941 case ISD::SDIV:
6942 case ISD::UDIV:
6943 case ISD::SREM:
6944 case ISD::UREM: {
6945 // If a divisor is zero/undef or any element of a divisor vector is
6946 // zero/undef, the whole op is undef.
6947 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
6948 SDValue Divisor = Ops[1];
6949 if (Divisor.isUndef() || isNullConstant(Divisor))
6950 return true;
6951
6952 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
6953 llvm::any_of(Divisor->op_values(),
6954 [](SDValue V) { return V.isUndef() ||
6955 isNullConstant(V); });
6956 // TODO: Handle signed overflow.
6957 }
6958 // TODO: Handle oversized shifts.
6959 default:
6960 return false;
6961 }
6962}
6963
6966 SDNodeFlags Flags) {
6967 // If the opcode is a target-specific ISD node, there's nothing we can
6968 // do here and the operand rules may not line up with the below, so
6969 // bail early.
6970 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
6971 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
6972 // foldCONCAT_VECTORS in getNode before this is called.
6973 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
6974 return SDValue();
6975
6976 unsigned NumOps = Ops.size();
6977 if (NumOps == 0)
6978 return SDValue();
6979
6980 if (isUndef(Opcode, Ops))
6981 return getUNDEF(VT);
6982
6983 // Handle unary special cases.
6984 if (NumOps == 1) {
6985 SDValue N1 = Ops[0];
6986
6987 // Constant fold unary operations with an integer constant operand. Even
6988 // opaque constant will be folded, because the folding of unary operations
6989 // doesn't create new constants with different values. Nevertheless, the
6990 // opaque flag is preserved during folding to prevent future folding with
6991 // other constants.
6992 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
6993 const APInt &Val = C->getAPIntValue();
6994 switch (Opcode) {
6995 case ISD::SIGN_EXTEND:
6996 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
6997 C->isTargetOpcode(), C->isOpaque());
6998 case ISD::TRUNCATE:
6999 if (C->isOpaque())
7000 break;
7001 [[fallthrough]];
7002 case ISD::ZERO_EXTEND:
7003 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7004 C->isTargetOpcode(), C->isOpaque());
7005 case ISD::ANY_EXTEND:
7006 // Some targets like RISCV prefer to sign extend some types.
7007 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7008 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7009 C->isTargetOpcode(), C->isOpaque());
7010 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7011 C->isTargetOpcode(), C->isOpaque());
7012 case ISD::ABS:
7013 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7014 C->isOpaque());
7015 case ISD::BITREVERSE:
7016 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7017 C->isOpaque());
7018 case ISD::BSWAP:
7019 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7020 C->isOpaque());
7021 case ISD::CTPOP:
7022 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7023 C->isOpaque());
7024 case ISD::CTLZ:
7026 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7027 C->isOpaque());
7028 case ISD::CTTZ:
7030 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7031 C->isOpaque());
7032 case ISD::UINT_TO_FP:
7033 case ISD::SINT_TO_FP: {
7035 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7037 return getConstantFP(FPV, DL, VT);
7038 }
7039 case ISD::FP16_TO_FP:
7040 case ISD::BF16_TO_FP: {
7041 bool Ignored;
7042 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7043 : APFloat::BFloat(),
7044 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7045
7046 // This can return overflow, underflow, or inexact; we don't care.
7047 // FIXME need to be more flexible about rounding mode.
7049 &Ignored);
7050 return getConstantFP(FPV, DL, VT);
7051 }
7052 case ISD::STEP_VECTOR:
7053 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7054 return V;
7055 break;
7056 case ISD::BITCAST:
7057 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7058 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7059 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7060 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7061 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7062 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7063 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7064 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7065 break;
7066 }
7067 }
7068
7069 // Constant fold unary operations with a floating point constant operand.
7070 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7071 APFloat V = C->getValueAPF(); // make copy
7072 switch (Opcode) {
7073 case ISD::FNEG:
7074 V.changeSign();
7075 return getConstantFP(V, DL, VT);
7076 case ISD::FABS:
7077 V.clearSign();
7078 return getConstantFP(V, DL, VT);
7079 case ISD::FCEIL: {
7080 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7082 return getConstantFP(V, DL, VT);
7083 return SDValue();
7084 }
7085 case ISD::FTRUNC: {
7086 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7088 return getConstantFP(V, DL, VT);
7089 return SDValue();
7090 }
7091 case ISD::FFLOOR: {
7092 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7094 return getConstantFP(V, DL, VT);
7095 return SDValue();
7096 }
7097 case ISD::FP_EXTEND: {
7098 bool ignored;
7099 // This can return overflow, underflow, or inexact; we don't care.
7100 // FIXME need to be more flexible about rounding mode.
7101 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7102 &ignored);
7103 return getConstantFP(V, DL, VT);
7104 }
7105 case ISD::FP_TO_SINT:
7106 case ISD::FP_TO_UINT: {
7107 bool ignored;
7108 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7109 // FIXME need to be more flexible about rounding mode.
7111 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7112 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7113 break;
7114 return getConstant(IntVal, DL, VT);
7115 }
7116 case ISD::FP_TO_FP16:
7117 case ISD::FP_TO_BF16: {
7118 bool Ignored;
7119 // This can return overflow, underflow, or inexact; we don't care.
7120 // FIXME need to be more flexible about rounding mode.
7121 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7122 : APFloat::BFloat(),
7124 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7125 }
7126 case ISD::BITCAST:
7127 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7128 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7129 VT);
7130 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7131 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7132 VT);
7133 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7134 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7135 VT);
7136 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7137 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7138 break;
7139 }
7140 }
7141
7142 // Early-out if we failed to constant fold a bitcast.
7143 if (Opcode == ISD::BITCAST)
7144 return SDValue();
7145 }
7146
7147 // Handle binops special cases.
7148 if (NumOps == 2) {
7149 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7150 return CFP;
7151
7152 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7153 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7154 if (C1->isOpaque() || C2->isOpaque())
7155 return SDValue();
7156
7157 std::optional<APInt> FoldAttempt =
7158 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7159 if (!FoldAttempt)
7160 return SDValue();
7161
7162 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7163 assert((!Folded || !VT.isVector()) &&
7164 "Can't fold vectors ops with scalar operands");
7165 return Folded;
7166 }
7167 }
7168
7169 // fold (add Sym, c) -> Sym+c
7171 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7172 if (TLI->isCommutativeBinOp(Opcode))
7174 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7175
7176 // fold (sext_in_reg c1) -> c2
7177 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7178 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7179
7180 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7181 unsigned FromBits = EVT.getScalarSizeInBits();
7182 Val <<= Val.getBitWidth() - FromBits;
7183 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7184 return getConstant(Val, DL, ConstantVT);
7185 };
7186
7187 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7188 const APInt &Val = C1->getAPIntValue();
7189 return SignExtendInReg(Val, VT);
7190 }
7191
7193 SmallVector<SDValue, 8> ScalarOps;
7194 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7195 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7196 SDValue Op = Ops[0].getOperand(I);
7197 if (Op.isUndef()) {
7198 ScalarOps.push_back(getUNDEF(OpVT));
7199 continue;
7200 }
7201 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7202 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7203 }
7204 return getBuildVector(VT, DL, ScalarOps);
7205 }
7206
7207 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7208 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7209 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7210 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7211 Ops[0].getOperand(0).getValueType()));
7212 }
7213 }
7214
7215 // Handle fshl/fshr special cases.
7216 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7217 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7218 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7219 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7220
7221 if (C1 && C2 && C3) {
7222 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7223 return SDValue();
7224 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7225 &V3 = C3->getAPIntValue();
7226
7227 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7228 : APIntOps::fshr(V1, V2, V3);
7229 return getConstant(FoldedVal, DL, VT);
7230 }
7231 }
7232
7233 // Handle fma/fmad special cases.
7234 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7235 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7236 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7237 Ops[2].getValueType() == VT && "FMA types must match!");
7241 if (C1 && C2 && C3) {
7242 APFloat V1 = C1->getValueAPF();
7243 const APFloat &V2 = C2->getValueAPF();
7244 const APFloat &V3 = C3->getValueAPF();
7245 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7248 } else
7250 return getConstantFP(V1, DL, VT);
7251 }
7252 }
7253
7254 // This is for vector folding only from here on.
7255 if (!VT.isVector())
7256 return SDValue();
7257
7258 ElementCount NumElts = VT.getVectorElementCount();
7259
7260 // See if we can fold through any bitcasted integer ops.
7261 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
7262 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7263 (Ops[0].getOpcode() == ISD::BITCAST ||
7264 Ops[1].getOpcode() == ISD::BITCAST)) {
7267 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7268 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
7269 if (BV1 && BV2 && N1.getValueType().isInteger() &&
7270 N2.getValueType().isInteger()) {
7271 bool IsLE = getDataLayout().isLittleEndian();
7272 unsigned EltBits = VT.getScalarSizeInBits();
7273 SmallVector<APInt> RawBits1, RawBits2;
7274 BitVector UndefElts1, UndefElts2;
7275 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
7276 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
7277 SmallVector<APInt> RawBits;
7278 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
7279 std::optional<APInt> Fold = FoldValueWithUndef(
7280 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
7281 if (!Fold)
7282 break;
7283 RawBits.push_back(*Fold);
7284 }
7285 if (RawBits.size() == NumElts.getFixedValue()) {
7286 // We have constant folded, but we might need to cast this again back
7287 // to the original (possibly legalized) type.
7288 EVT BVVT, BVEltVT;
7289 if (N1.getValueType() == VT) {
7290 BVVT = N1.getValueType();
7291 BVEltVT = BV1->getOperand(0).getValueType();
7292 } else {
7293 BVVT = N2.getValueType();
7294 BVEltVT = BV2->getOperand(0).getValueType();
7295 }
7296 unsigned BVEltBits = BVEltVT.getSizeInBits();
7297 SmallVector<APInt> DstBits;
7298 BitVector DstUndefs;
7300 DstBits, RawBits, DstUndefs,
7301 BitVector(RawBits.size(), false));
7302 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
7303 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
7304 if (DstUndefs[I])
7305 continue;
7306 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
7307 }
7308 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
7309 }
7310 }
7311 }
7312 }
7313
7314 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
7315 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
7316 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
7317 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
7318 APInt RHSVal;
7319 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
7320 APInt NewStep = Opcode == ISD::MUL
7321 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
7322 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
7323 return getStepVector(DL, VT, NewStep);
7324 }
7325 }
7326
7327 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
7328 return !Op.getValueType().isVector() ||
7329 Op.getValueType().getVectorElementCount() == NumElts;
7330 };
7331
7332 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
7333 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
7334 Op.getOpcode() == ISD::BUILD_VECTOR ||
7335 Op.getOpcode() == ISD::SPLAT_VECTOR;
7336 };
7337
7338 // All operands must be vector types with the same number of elements as
7339 // the result type and must be either UNDEF or a build/splat vector
7340 // or UNDEF scalars.
7341 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
7342 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
7343 return SDValue();
7344
7345 // If we are comparing vectors, then the result needs to be a i1 boolean that
7346 // is then extended back to the legal result type depending on how booleans
7347 // are represented.
7348 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
7349 ISD::NodeType ExtendCode =
7350 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
7351 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
7353
7354 // Find legal integer scalar type for constant promotion and
7355 // ensure that its scalar size is at least as large as source.
7356 EVT LegalSVT = VT.getScalarType();
7357 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
7358 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
7359 if (LegalSVT.bitsLT(VT.getScalarType()))
7360 return SDValue();
7361 }
7362
7363 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
7364 // only have one operand to check. For fixed-length vector types we may have
7365 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
7366 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
7367
7368 // Constant fold each scalar lane separately.
7369 SmallVector<SDValue, 4> ScalarResults;
7370 for (unsigned I = 0; I != NumVectorElts; I++) {
7371 SmallVector<SDValue, 4> ScalarOps;
7372 for (SDValue Op : Ops) {
7373 EVT InSVT = Op.getValueType().getScalarType();
7374 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
7375 Op.getOpcode() != ISD::SPLAT_VECTOR) {
7376 if (Op.isUndef())
7377 ScalarOps.push_back(getUNDEF(InSVT));
7378 else
7379 ScalarOps.push_back(Op);
7380 continue;
7381 }
7382
7383 SDValue ScalarOp =
7384 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
7385 EVT ScalarVT = ScalarOp.getValueType();
7386
7387 // Build vector (integer) scalar operands may need implicit
7388 // truncation - do this before constant folding.
7389 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
7390 // Don't create illegally-typed nodes unless they're constants or undef
7391 // - if we fail to constant fold we can't guarantee the (dead) nodes
7392 // we're creating will be cleaned up before being visited for
7393 // legalization.
7394 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
7395 !isa<ConstantSDNode>(ScalarOp) &&
7396 TLI->getTypeAction(*getContext(), InSVT) !=
7398 return SDValue();
7399 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
7400 }
7401
7402 ScalarOps.push_back(ScalarOp);
7403 }
7404
7405 // Constant fold the scalar operands.
7406 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
7407
7408 // Scalar folding only succeeded if the result is a constant or UNDEF.
7409 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
7410 ScalarResult.getOpcode() != ISD::ConstantFP)
7411 return SDValue();
7412
7413 // Legalize the (integer) scalar constant if necessary. We only do
7414 // this once we know the folding succeeded, since otherwise we would
7415 // get a node with illegal type which has a user.
7416 if (LegalSVT != SVT)
7417 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
7418
7419 ScalarResults.push_back(ScalarResult);
7420 }
7421
7422 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
7423 : getBuildVector(VT, DL, ScalarResults);
7424 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
7425 return V;
7426}
7427
7430 // TODO: Add support for unary/ternary fp opcodes.
7431 if (Ops.size() != 2)
7432 return SDValue();
7433
7434 // TODO: We don't do any constant folding for strict FP opcodes here, but we
7435 // should. That will require dealing with a potentially non-default
7436 // rounding mode, checking the "opStatus" return value from the APFloat
7437 // math calculations, and possibly other variations.
7438 SDValue N1 = Ops[0];
7439 SDValue N2 = Ops[1];
7440 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
7441 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
7442 if (N1CFP && N2CFP) {
7443 APFloat C1 = N1CFP->getValueAPF(); // make copy
7444 const APFloat &C2 = N2CFP->getValueAPF();
7445 switch (Opcode) {
7446 case ISD::FADD:
7448 return getConstantFP(C1, DL, VT);
7449 case ISD::FSUB:
7451 return getConstantFP(C1, DL, VT);
7452 case ISD::FMUL:
7454 return getConstantFP(C1, DL, VT);
7455 case ISD::FDIV:
7457 return getConstantFP(C1, DL, VT);
7458 case ISD::FREM:
7459 C1.mod(C2);
7460 return getConstantFP(C1, DL, VT);
7461 case ISD::FCOPYSIGN:
7462 C1.copySign(C2);
7463 return getConstantFP(C1, DL, VT);
7464 case ISD::FMINNUM:
7465 if (C1.isSignaling() || C2.isSignaling())
7466 return SDValue();
7467 return getConstantFP(minnum(C1, C2), DL, VT);
7468 case ISD::FMAXNUM:
7469 if (C1.isSignaling() || C2.isSignaling())
7470 return SDValue();
7471 return getConstantFP(maxnum(C1, C2), DL, VT);
7472 case ISD::FMINIMUM:
7473 return getConstantFP(minimum(C1, C2), DL, VT);
7474 case ISD::FMAXIMUM:
7475 return getConstantFP(maximum(C1, C2), DL, VT);
7476 case ISD::FMINIMUMNUM:
7477 return getConstantFP(minimumnum(C1, C2), DL, VT);
7478 case ISD::FMAXIMUMNUM:
7479 return getConstantFP(maximumnum(C1, C2), DL, VT);
7480 default: break;
7481 }
7482 }
7483 if (N1CFP && Opcode == ISD::FP_ROUND) {
7484 APFloat C1 = N1CFP->getValueAPF(); // make copy
7485 bool Unused;
7486 // This can return overflow, underflow, or inexact; we don't care.
7487 // FIXME need to be more flexible about rounding mode.
7489 &Unused);
7490 return getConstantFP(C1, DL, VT);
7491 }
7492
7493 switch (Opcode) {
7494 case ISD::FSUB:
7495 // -0.0 - undef --> undef (consistent with "fneg undef")
7496 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
7497 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
7498 return getUNDEF(VT);
7499 [[fallthrough]];
7500
7501 case ISD::FADD:
7502 case ISD::FMUL:
7503 case ISD::FDIV:
7504 case ISD::FREM:
7505 // If both operands are undef, the result is undef. If 1 operand is undef,
7506 // the result is NaN. This should match the behavior of the IR optimizer.
7507 if (N1.isUndef() && N2.isUndef())
7508 return getUNDEF(VT);
7509 if (N1.isUndef() || N2.isUndef())
7511 }
7512 return SDValue();
7513}
7514
7516 const SDLoc &DL, EVT DstEltVT) {
7517 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7518
7519 // If this is already the right type, we're done.
7520 if (SrcEltVT == DstEltVT)
7521 return SDValue(BV, 0);
7522
7523 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7524 unsigned DstBitSize = DstEltVT.getSizeInBits();
7525
7526 // If this is a conversion of N elements of one type to N elements of another
7527 // type, convert each element. This handles FP<->INT cases.
7528 if (SrcBitSize == DstBitSize) {
7530 for (SDValue Op : BV->op_values()) {
7531 // If the vector element type is not legal, the BUILD_VECTOR operands
7532 // are promoted and implicitly truncated. Make that explicit here.
7533 if (Op.getValueType() != SrcEltVT)
7534 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
7535 Ops.push_back(getBitcast(DstEltVT, Op));
7536 }
7537 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
7539 return getBuildVector(VT, DL, Ops);
7540 }
7541
7542 // Otherwise, we're growing or shrinking the elements. To avoid having to
7543 // handle annoying details of growing/shrinking FP values, we convert them to
7544 // int first.
7545 if (SrcEltVT.isFloatingPoint()) {
7546 // Convert the input float vector to a int vector where the elements are the
7547 // same sizes.
7548 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
7549 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
7551 DstEltVT);
7552 return SDValue();
7553 }
7554
7555 // Now we know the input is an integer vector. If the output is a FP type,
7556 // convert to integer first, then to FP of the right size.
7557 if (DstEltVT.isFloatingPoint()) {
7558 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
7559 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
7561 DstEltVT);
7562 return SDValue();
7563 }
7564
7565 // Okay, we know the src/dst types are both integers of differing types.
7566 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7567
7568 // Extract the constant raw bit data.
7569 BitVector UndefElements;
7570 SmallVector<APInt> RawBits;
7571 bool IsLE = getDataLayout().isLittleEndian();
7572 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
7573 return SDValue();
7574
7576 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
7577 if (UndefElements[I])
7578 Ops.push_back(getUNDEF(DstEltVT));
7579 else
7580 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
7581 }
7582
7583 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
7584 return getBuildVector(VT, DL, Ops);
7585}
7586
7588 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
7589
7590 // There's no need to assert on a byte-aligned pointer. All pointers are at
7591 // least byte aligned.
7592 if (A == Align(1))
7593 return Val;
7594
7595 SDVTList VTs = getVTList(Val.getValueType());
7597 AddNodeIDNode(ID, ISD::AssertAlign, VTs, {Val});
7598 ID.AddInteger(A.value());
7599
7600 void *IP = nullptr;
7601 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7602 return SDValue(E, 0);
7603
7604 auto *N =
7605 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
7606 createOperands(N, {Val});
7607
7608 CSEMap.InsertNode(N, IP);
7609 InsertNode(N);
7610
7611 SDValue V(N, 0);
7612 NewSDValueDbgMsg(V, "Creating new node: ", this);
7613 return V;
7614}
7615
7616SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7617 SDValue N1, SDValue N2) {
7618 SDNodeFlags Flags;
7619 if (Inserter)
7620 Flags = Inserter->getFlags();
7621 return getNode(Opcode, DL, VT, N1, N2, Flags);
7622}
7623
7625 SDValue &N2) const {
7626 if (!TLI->isCommutativeBinOp(Opcode))
7627 return;
7628
7629 // Canonicalize:
7630 // binop(const, nonconst) -> binop(nonconst, const)
7633 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
7634 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
7635 if ((N1C && !N2C) || (N1CFP && !N2CFP))
7636 std::swap(N1, N2);
7637
7638 // Canonicalize:
7639 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
7640 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
7642 std::swap(N1, N2);
7643}
7644
7645SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7646 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
7648 N2.getOpcode() != ISD::DELETED_NODE &&
7649 "Operand is DELETED_NODE!");
7650
7651 canonicalizeCommutativeBinop(Opcode, N1, N2);
7652
7653 auto *N1C = dyn_cast<ConstantSDNode>(N1);
7654 auto *N2C = dyn_cast<ConstantSDNode>(N2);
7655
7656 // Don't allow undefs in vector splats - we might be returning N2 when folding
7657 // to zero etc.
7658 ConstantSDNode *N2CV =
7659 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
7660
7661 switch (Opcode) {
7662 default: break;
7663 case ISD::TokenFactor:
7664 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
7665 N2.getValueType() == MVT::Other && "Invalid token factor!");
7666 // Fold trivial token factors.
7667 if (N1.getOpcode() == ISD::EntryToken) return N2;
7668 if (N2.getOpcode() == ISD::EntryToken) return N1;
7669 if (N1 == N2) return N1;
7670 break;
7671 case ISD::BUILD_VECTOR: {
7672 // Attempt to simplify BUILD_VECTOR.
7673 SDValue Ops[] = {N1, N2};
7674 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7675 return V;
7676 break;
7677 }
7678 case ISD::CONCAT_VECTORS: {
7679 SDValue Ops[] = {N1, N2};
7680 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7681 return V;
7682 break;
7683 }
7684 case ISD::AND:
7685 assert(VT.isInteger() && "This operator does not apply to FP types!");
7686 assert(N1.getValueType() == N2.getValueType() &&
7687 N1.getValueType() == VT && "Binary operator types must match!");
7688 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
7689 // worth handling here.
7690 if (N2CV && N2CV->isZero())
7691 return N2;
7692 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
7693 return N1;
7694 break;
7695 case ISD::OR:
7696 case ISD::XOR:
7697 case ISD::ADD:
7698 case ISD::PTRADD:
7699 case ISD::SUB:
7700 assert(VT.isInteger() && "This operator does not apply to FP types!");
7701 assert(N1.getValueType() == N2.getValueType() &&
7702 N1.getValueType() == VT && "Binary operator types must match!");
7703 // The equal operand types requirement is unnecessarily strong for PTRADD.
7704 // However, the SelectionDAGBuilder does not generate PTRADDs with different
7705 // operand types, and we'd need to re-implement GEP's non-standard wrapping
7706 // logic everywhere where PTRADDs may be folded or combined to properly
7707 // support them. If/when we introduce pointer types to the SDAG, we will
7708 // need to relax this constraint.
7709
7710 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
7711 // it's worth handling here.
7712 if (N2CV && N2CV->isZero())
7713 return N1;
7714 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
7715 VT.getScalarType() == MVT::i1)
7716 return getNode(ISD::XOR, DL, VT, N1, N2);
7717 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
7718 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
7719 N2.getOpcode() == ISD::VSCALE) {
7720 const APInt &C1 = N1->getConstantOperandAPInt(0);
7721 const APInt &C2 = N2->getConstantOperandAPInt(0);
7722 return getVScale(DL, VT, C1 + C2);
7723 }
7724 break;
7725 case ISD::MUL:
7726 assert(VT.isInteger() && "This operator does not apply to FP types!");
7727 assert(N1.getValueType() == N2.getValueType() &&
7728 N1.getValueType() == VT && "Binary operator types must match!");
7729 if (VT.getScalarType() == MVT::i1)
7730 return getNode(ISD::AND, DL, VT, N1, N2);
7731 if (N2CV && N2CV->isZero())
7732 return N2;
7733 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
7734 const APInt &MulImm = N1->getConstantOperandAPInt(0);
7735 const APInt &N2CImm = N2C->getAPIntValue();
7736 return getVScale(DL, VT, MulImm * N2CImm);
7737 }
7738 break;
7739 case ISD::UDIV:
7740 case ISD::UREM:
7741 case ISD::MULHU:
7742 case ISD::MULHS:
7743 case ISD::SDIV:
7744 case ISD::SREM:
7745 case ISD::SADDSAT:
7746 case ISD::SSUBSAT:
7747 case ISD::UADDSAT:
7748 case ISD::USUBSAT:
7749 assert(VT.isInteger() && "This operator does not apply to FP types!");
7750 assert(N1.getValueType() == N2.getValueType() &&
7751 N1.getValueType() == VT && "Binary operator types must match!");
7752 if (VT.getScalarType() == MVT::i1) {
7753 // fold (add_sat x, y) -> (or x, y) for bool types.
7754 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
7755 return getNode(ISD::OR, DL, VT, N1, N2);
7756 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
7757 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
7758 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
7759 }
7760 break;
7761 case ISD::SCMP:
7762 case ISD::UCMP:
7763 assert(N1.getValueType() == N2.getValueType() &&
7764 "Types of operands of UCMP/SCMP must match");
7765 assert(N1.getValueType().isVector() == VT.isVector() &&
7766 "Operands and return type of must both be scalars or vectors");
7767 if (VT.isVector())
7770 "Result and operands must have the same number of elements");
7771 break;
7772 case ISD::AVGFLOORS:
7773 case ISD::AVGFLOORU:
7774 case ISD::AVGCEILS:
7775 case ISD::AVGCEILU:
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 break;
7780 case ISD::ABDS:
7781 case ISD::ABDU:
7782 assert(VT.isInteger() && "This operator does not apply to FP types!");
7783 assert(N1.getValueType() == N2.getValueType() &&
7784 N1.getValueType() == VT && "Binary operator types must match!");
7785 if (VT.getScalarType() == MVT::i1)
7786 return getNode(ISD::XOR, DL, VT, N1, N2);
7787 break;
7788 case ISD::SMIN:
7789 case ISD::UMAX:
7790 assert(VT.isInteger() && "This operator does not apply to FP types!");
7791 assert(N1.getValueType() == N2.getValueType() &&
7792 N1.getValueType() == VT && "Binary operator types must match!");
7793 if (VT.getScalarType() == MVT::i1)
7794 return getNode(ISD::OR, DL, VT, N1, N2);
7795 break;
7796 case ISD::SMAX:
7797 case ISD::UMIN:
7798 assert(VT.isInteger() && "This operator does not apply to FP types!");
7799 assert(N1.getValueType() == N2.getValueType() &&
7800 N1.getValueType() == VT && "Binary operator types must match!");
7801 if (VT.getScalarType() == MVT::i1)
7802 return getNode(ISD::AND, DL, VT, N1, N2);
7803 break;
7804 case ISD::FADD:
7805 case ISD::FSUB:
7806 case ISD::FMUL:
7807 case ISD::FDIV:
7808 case ISD::FREM:
7809 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7810 assert(N1.getValueType() == N2.getValueType() &&
7811 N1.getValueType() == VT && "Binary operator types must match!");
7812 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
7813 return V;
7814 break;
7815 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
7816 assert(N1.getValueType() == VT &&
7819 "Invalid FCOPYSIGN!");
7820 break;
7821 case ISD::SHL:
7822 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
7823 const APInt &MulImm = N1->getConstantOperandAPInt(0);
7824 const APInt &ShiftImm = N2C->getAPIntValue();
7825 return getVScale(DL, VT, MulImm << ShiftImm);
7826 }
7827 [[fallthrough]];
7828 case ISD::SRA:
7829 case ISD::SRL:
7830 if (SDValue V = simplifyShift(N1, N2))
7831 return V;
7832 [[fallthrough]];
7833 case ISD::ROTL:
7834 case ISD::ROTR:
7835 case ISD::SSHLSAT:
7836 case ISD::USHLSAT:
7837 assert(VT == N1.getValueType() &&
7838 "Shift operators return type must be the same as their first arg");
7839 assert(VT.isInteger() && N2.getValueType().isInteger() &&
7840 "Shifts only work on integers");
7841 assert((!VT.isVector() || VT == N2.getValueType()) &&
7842 "Vector shift amounts must be in the same as their first arg");
7843 // Verify that the shift amount VT is big enough to hold valid shift
7844 // amounts. This catches things like trying to shift an i1024 value by an
7845 // i8, which is easy to fall into in generic code that uses
7846 // TLI.getShiftAmount().
7849 "Invalid use of small shift amount with oversized value!");
7850
7851 // Always fold shifts of i1 values so the code generator doesn't need to
7852 // handle them. Since we know the size of the shift has to be less than the
7853 // size of the value, the shift/rotate count is guaranteed to be zero.
7854 if (VT == MVT::i1)
7855 return N1;
7856 if (N2CV && N2CV->isZero())
7857 return N1;
7858 break;
7859 case ISD::FP_ROUND:
7861 VT.bitsLE(N1.getValueType()) && N2C &&
7862 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
7863 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
7864 if (N1.getValueType() == VT) return N1; // noop conversion.
7865 break;
7866 case ISD::AssertNoFPClass: {
7868 "AssertNoFPClass is used for a non-floating type");
7869 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
7870 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
7871 assert(llvm::to_underlying(NoFPClass) <=
7873 "FPClassTest value too large");
7874 (void)NoFPClass;
7875 break;
7876 }
7877 case ISD::AssertSext:
7878 case ISD::AssertZext: {
7879 EVT EVT = cast<VTSDNode>(N2)->getVT();
7880 assert(VT == N1.getValueType() && "Not an inreg extend!");
7881 assert(VT.isInteger() && EVT.isInteger() &&
7882 "Cannot *_EXTEND_INREG FP types");
7883 assert(!EVT.isVector() &&
7884 "AssertSExt/AssertZExt type should be the vector element type "
7885 "rather than the vector type!");
7886 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
7887 if (VT.getScalarType() == EVT) return N1; // noop assertion.
7888 break;
7889 }
7891 EVT EVT = cast<VTSDNode>(N2)->getVT();
7892 assert(VT == N1.getValueType() && "Not an inreg extend!");
7893 assert(VT.isInteger() && EVT.isInteger() &&
7894 "Cannot *_EXTEND_INREG FP types");
7895 assert(EVT.isVector() == VT.isVector() &&
7896 "SIGN_EXTEND_INREG type should be vector iff the operand "
7897 "type is vector!");
7898 assert((!EVT.isVector() ||
7900 "Vector element counts must match in SIGN_EXTEND_INREG");
7901 assert(EVT.bitsLE(VT) && "Not extending!");
7902 if (EVT == VT) return N1; // Not actually extending
7903 break;
7904 }
7906 case ISD::FP_TO_UINT_SAT: {
7907 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
7908 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
7909 assert(N1.getValueType().isVector() == VT.isVector() &&
7910 "FP_TO_*INT_SAT type should be vector iff the operand type is "
7911 "vector!");
7912 assert((!VT.isVector() || VT.getVectorElementCount() ==
7914 "Vector element counts must match in FP_TO_*INT_SAT");
7915 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
7916 "Type to saturate to must be a scalar.");
7917 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
7918 "Not extending!");
7919 break;
7920 }
7923 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
7924 element type of the vector.");
7925
7926 // Extract from an undefined value or using an undefined index is undefined.
7927 if (N1.isUndef() || N2.isUndef())
7928 return getUNDEF(VT);
7929
7930 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
7931 // vectors. For scalable vectors we will provide appropriate support for
7932 // dealing with arbitrary indices.
7933 if (N2C && N1.getValueType().isFixedLengthVector() &&
7934 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
7935 return getUNDEF(VT);
7936
7937 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
7938 // expanding copies of large vectors from registers. This only works for
7939 // fixed length vectors, since we need to know the exact number of
7940 // elements.
7941 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
7943 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
7944 return getExtractVectorElt(DL, VT,
7945 N1.getOperand(N2C->getZExtValue() / Factor),
7946 N2C->getZExtValue() % Factor);
7947 }
7948
7949 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
7950 // lowering is expanding large vector constants.
7951 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
7952 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
7955 "BUILD_VECTOR used for scalable vectors");
7956 unsigned Index =
7957 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
7958 SDValue Elt = N1.getOperand(Index);
7959
7960 if (VT != Elt.getValueType())
7961 // If the vector element type is not legal, the BUILD_VECTOR operands
7962 // are promoted and implicitly truncated, and the result implicitly
7963 // extended. Make that explicit here.
7964 Elt = getAnyExtOrTrunc(Elt, DL, VT);
7965
7966 return Elt;
7967 }
7968
7969 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
7970 // operations are lowered to scalars.
7971 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
7972 // If the indices are the same, return the inserted element else
7973 // if the indices are known different, extract the element from
7974 // the original vector.
7975 SDValue N1Op2 = N1.getOperand(2);
7977
7978 if (N1Op2C && N2C) {
7979 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
7980 if (VT == N1.getOperand(1).getValueType())
7981 return N1.getOperand(1);
7982 if (VT.isFloatingPoint()) {
7984 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
7985 }
7986 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
7987 }
7988 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
7989 }
7990 }
7991
7992 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
7993 // when vector types are scalarized and v1iX is legal.
7994 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
7995 // Here we are completely ignoring the extract element index (N2),
7996 // which is fine for fixed width vectors, since any index other than 0
7997 // is undefined anyway. However, this cannot be ignored for scalable
7998 // vectors - in theory we could support this, but we don't want to do this
7999 // without a profitability check.
8000 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8002 N1.getValueType().getVectorNumElements() == 1) {
8003 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8004 N1.getOperand(1));
8005 }
8006 break;
8008 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8009 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8010 (N1.getValueType().isInteger() == VT.isInteger()) &&
8011 N1.getValueType() != VT &&
8012 "Wrong types for EXTRACT_ELEMENT!");
8013
8014 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8015 // 64-bit integers into 32-bit parts. Instead of building the extract of
8016 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8017 if (N1.getOpcode() == ISD::BUILD_PAIR)
8018 return N1.getOperand(N2C->getZExtValue());
8019
8020 // EXTRACT_ELEMENT of a constant int is also very common.
8021 if (N1C) {
8022 unsigned ElementSize = VT.getSizeInBits();
8023 unsigned Shift = ElementSize * N2C->getZExtValue();
8024 const APInt &Val = N1C->getAPIntValue();
8025 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8026 }
8027 break;
8029 EVT N1VT = N1.getValueType();
8030 assert(VT.isVector() && N1VT.isVector() &&
8031 "Extract subvector VTs must be vectors!");
8033 "Extract subvector VTs must have the same element type!");
8034 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8035 "Cannot extract a scalable vector from a fixed length vector!");
8036 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8038 "Extract subvector must be from larger vector to smaller vector!");
8039 assert(N2C && "Extract subvector index must be a constant");
8040 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8041 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8042 N1VT.getVectorMinNumElements()) &&
8043 "Extract subvector overflow!");
8044 assert(N2C->getAPIntValue().getBitWidth() ==
8045 TLI->getVectorIdxWidth(getDataLayout()) &&
8046 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8047 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8048 "Extract index is not a multiple of the output vector length");
8049
8050 // Trivial extraction.
8051 if (VT == N1VT)
8052 return N1;
8053
8054 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8055 if (N1.isUndef())
8056 return getUNDEF(VT);
8057
8058 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8059 // the concat have the same type as the extract.
8060 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8061 VT == N1.getOperand(0).getValueType()) {
8062 unsigned Factor = VT.getVectorMinNumElements();
8063 return N1.getOperand(N2C->getZExtValue() / Factor);
8064 }
8065
8066 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8067 // during shuffle legalization.
8068 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8069 VT == N1.getOperand(1).getValueType())
8070 return N1.getOperand(1);
8071 break;
8072 }
8073 }
8074
8075 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8076 switch (Opcode) {
8077 case ISD::XOR:
8078 case ISD::ADD:
8079 case ISD::PTRADD:
8080 case ISD::SUB:
8082 case ISD::UDIV:
8083 case ISD::SDIV:
8084 case ISD::UREM:
8085 case ISD::SREM:
8086 case ISD::MUL:
8087 case ISD::AND:
8088 case ISD::SSUBSAT:
8089 case ISD::USUBSAT:
8090 case ISD::UMIN:
8091 case ISD::OR:
8092 case ISD::SADDSAT:
8093 case ISD::UADDSAT:
8094 case ISD::UMAX:
8095 case ISD::SMAX:
8096 case ISD::SMIN:
8097 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8098 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8099 }
8100 }
8101
8102 // Canonicalize an UNDEF to the RHS, even over a constant.
8103 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8104 if (TLI->isCommutativeBinOp(Opcode)) {
8105 std::swap(N1, N2);
8106 } else {
8107 switch (Opcode) {
8108 case ISD::PTRADD:
8109 case ISD::SUB:
8110 // fold op(undef, non_undef_arg2) -> undef.
8111 return N1;
8113 case ISD::UDIV:
8114 case ISD::SDIV:
8115 case ISD::UREM:
8116 case ISD::SREM:
8117 case ISD::SSUBSAT:
8118 case ISD::USUBSAT:
8119 // fold op(undef, non_undef_arg2) -> 0.
8120 return getConstant(0, DL, VT);
8121 }
8122 }
8123 }
8124
8125 // Fold a bunch of operators when the RHS is undef.
8126 if (N2.getOpcode() == ISD::UNDEF) {
8127 switch (Opcode) {
8128 case ISD::XOR:
8129 if (N1.getOpcode() == ISD::UNDEF)
8130 // Handle undef ^ undef -> 0 special case. This is a common
8131 // idiom (misuse).
8132 return getConstant(0, DL, VT);
8133 [[fallthrough]];
8134 case ISD::ADD:
8135 case ISD::PTRADD:
8136 case ISD::SUB:
8137 // fold op(arg1, undef) -> undef.
8138 return N2;
8139 case ISD::UDIV:
8140 case ISD::SDIV:
8141 case ISD::UREM:
8142 case ISD::SREM:
8143 // fold op(arg1, undef) -> poison.
8144 return getPOISON(VT);
8145 case ISD::MUL:
8146 case ISD::AND:
8147 case ISD::SSUBSAT:
8148 case ISD::USUBSAT:
8149 case ISD::UMIN:
8150 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8151 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8152 case ISD::OR:
8153 case ISD::SADDSAT:
8154 case ISD::UADDSAT:
8155 case ISD::UMAX:
8156 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8157 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8158 case ISD::SMAX:
8159 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8160 return N1.getOpcode() == ISD::UNDEF
8161 ? N2
8162 : getConstant(
8164 VT);
8165 case ISD::SMIN:
8166 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8167 return N1.getOpcode() == ISD::UNDEF
8168 ? N2
8169 : getConstant(
8171 VT);
8172 }
8173 }
8174
8175 // Perform trivial constant folding.
8176 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
8177 return SV;
8178
8179 // Memoize this node if possible.
8180 SDNode *N;
8181 SDVTList VTs = getVTList(VT);
8182 SDValue Ops[] = {N1, N2};
8183 if (VT != MVT::Glue) {
8185 AddNodeIDNode(ID, Opcode, VTs, Ops);
8186 void *IP = nullptr;
8187 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8188 E->intersectFlagsWith(Flags);
8189 return SDValue(E, 0);
8190 }
8191
8192 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8193 N->setFlags(Flags);
8194 createOperands(N, Ops);
8195 CSEMap.InsertNode(N, IP);
8196 } else {
8197 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8198 createOperands(N, Ops);
8199 }
8200
8201 InsertNode(N);
8202 SDValue V = SDValue(N, 0);
8203 NewSDValueDbgMsg(V, "Creating new node: ", this);
8204 return V;
8205}
8206
8207SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8208 SDValue N1, SDValue N2, SDValue N3) {
8209 SDNodeFlags Flags;
8210 if (Inserter)
8211 Flags = Inserter->getFlags();
8212 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
8213}
8214
8215SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8216 SDValue N1, SDValue N2, SDValue N3,
8217 const SDNodeFlags Flags) {
8219 N2.getOpcode() != ISD::DELETED_NODE &&
8220 N3.getOpcode() != ISD::DELETED_NODE &&
8221 "Operand is DELETED_NODE!");
8222 // Perform various simplifications.
8223 switch (Opcode) {
8224 case ISD::BUILD_VECTOR: {
8225 // Attempt to simplify BUILD_VECTOR.
8226 SDValue Ops[] = {N1, N2, N3};
8227 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8228 return V;
8229 break;
8230 }
8231 case ISD::CONCAT_VECTORS: {
8232 SDValue Ops[] = {N1, N2, N3};
8233 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8234 return V;
8235 break;
8236 }
8237 case ISD::SETCC: {
8238 assert(VT.isInteger() && "SETCC result type must be an integer!");
8239 assert(N1.getValueType() == N2.getValueType() &&
8240 "SETCC operands must have the same type!");
8241 assert(VT.isVector() == N1.getValueType().isVector() &&
8242 "SETCC type should be vector iff the operand type is vector!");
8243 assert((!VT.isVector() || VT.getVectorElementCount() ==
8245 "SETCC vector element counts must match!");
8246 // Use FoldSetCC to simplify SETCC's.
8247 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
8248 return V;
8249 break;
8250 }
8251 case ISD::SELECT:
8252 case ISD::VSELECT:
8253 if (SDValue V = simplifySelect(N1, N2, N3))
8254 return V;
8255 break;
8257 llvm_unreachable("should use getVectorShuffle constructor!");
8259 if (isNullConstant(N3))
8260 return N1;
8261 break;
8263 if (isNullConstant(N3))
8264 return N2;
8265 break;
8267 assert(VT.isVector() && VT == N1.getValueType() &&
8268 "INSERT_VECTOR_ELT vector type mismatch");
8270 "INSERT_VECTOR_ELT scalar fp/int mismatch");
8271 assert((!VT.isFloatingPoint() ||
8272 VT.getVectorElementType() == N2.getValueType()) &&
8273 "INSERT_VECTOR_ELT fp scalar type mismatch");
8274 assert((!VT.isInteger() ||
8276 "INSERT_VECTOR_ELT int scalar size mismatch");
8277
8278 auto *N3C = dyn_cast<ConstantSDNode>(N3);
8279 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
8280 // for scalable vectors where we will generate appropriate code to
8281 // deal with out-of-bounds cases correctly.
8282 if (N3C && VT.isFixedLengthVector() &&
8283 N3C->getZExtValue() >= VT.getVectorNumElements())
8284 return getUNDEF(VT);
8285
8286 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
8287 if (N3.isUndef())
8288 return getUNDEF(VT);
8289
8290 // If inserting poison, just use the input vector.
8291 if (N2.getOpcode() == ISD::POISON)
8292 return N1;
8293
8294 // Inserting undef into undef/poison is still undef.
8295 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
8296 return getUNDEF(VT);
8297
8298 // If the inserted element is an UNDEF, just use the input vector.
8299 // But not if skipping the insert could make the result more poisonous.
8300 if (N2.isUndef()) {
8301 if (N3C && VT.isFixedLengthVector()) {
8302 APInt EltMask =
8303 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
8304 if (isGuaranteedNotToBePoison(N1, EltMask))
8305 return N1;
8306 } else if (isGuaranteedNotToBePoison(N1))
8307 return N1;
8308 }
8309 break;
8310 }
8311 case ISD::INSERT_SUBVECTOR: {
8312 // If inserting poison, just use the input vector,
8313 if (N2.getOpcode() == ISD::POISON)
8314 return N1;
8315
8316 // Inserting undef into undef/poison is still undef.
8317 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
8318 return getUNDEF(VT);
8319
8320 EVT N2VT = N2.getValueType();
8321 assert(VT == N1.getValueType() &&
8322 "Dest and insert subvector source types must match!");
8323 assert(VT.isVector() && N2VT.isVector() &&
8324 "Insert subvector VTs must be vectors!");
8326 "Insert subvector VTs must have the same element type!");
8327 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
8328 "Cannot insert a scalable vector into a fixed length vector!");
8329 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
8331 "Insert subvector must be from smaller vector to larger vector!");
8333 "Insert subvector index must be constant");
8334 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
8335 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
8337 "Insert subvector overflow!");
8339 TLI->getVectorIdxWidth(getDataLayout()) &&
8340 "Constant index for INSERT_SUBVECTOR has an invalid size");
8341
8342 // Trivial insertion.
8343 if (VT == N2VT)
8344 return N2;
8345
8346 // If this is an insert of an extracted vector into an undef/poison vector,
8347 // we can just use the input to the extract. But not if skipping the
8348 // extract+insert could make the result more poisonous.
8349 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8350 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
8351 if (N1.getOpcode() == ISD::POISON)
8352 return N2.getOperand(0);
8353 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
8354 unsigned LoBit = N3->getAsZExtVal();
8355 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
8356 APInt EltMask =
8357 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
8358 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
8359 return N2.getOperand(0);
8360 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
8361 return N2.getOperand(0);
8362 }
8363
8364 // If the inserted subvector is UNDEF, just use the input vector.
8365 // But not if skipping the insert could make the result more poisonous.
8366 if (N2.isUndef()) {
8367 if (VT.isFixedLengthVector()) {
8368 unsigned LoBit = N3->getAsZExtVal();
8369 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
8370 APInt EltMask =
8371 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
8372 if (isGuaranteedNotToBePoison(N1, EltMask))
8373 return N1;
8374 } else if (isGuaranteedNotToBePoison(N1))
8375 return N1;
8376 }
8377 break;
8378 }
8379 case ISD::BITCAST:
8380 // Fold bit_convert nodes from a type to themselves.
8381 if (N1.getValueType() == VT)
8382 return N1;
8383 break;
8384 case ISD::VP_TRUNCATE:
8385 case ISD::VP_SIGN_EXTEND:
8386 case ISD::VP_ZERO_EXTEND:
8387 // Don't create noop casts.
8388 if (N1.getValueType() == VT)
8389 return N1;
8390 break;
8391 case ISD::VECTOR_COMPRESS: {
8392 [[maybe_unused]] EVT VecVT = N1.getValueType();
8393 [[maybe_unused]] EVT MaskVT = N2.getValueType();
8394 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
8395 assert(VT == VecVT && "Vector and result type don't match.");
8396 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
8397 "All inputs must be vectors.");
8398 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
8400 "Vector and mask must have same number of elements.");
8401
8402 if (N1.isUndef() || N2.isUndef())
8403 return N3;
8404
8405 break;
8406 }
8411 [[maybe_unused]] EVT AccVT = N1.getValueType();
8412 [[maybe_unused]] EVT Input1VT = N2.getValueType();
8413 [[maybe_unused]] EVT Input2VT = N3.getValueType();
8414 assert(Input1VT.isVector() && Input1VT == Input2VT &&
8415 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
8416 "node to have the same type!");
8417 assert(VT.isVector() && VT == AccVT &&
8418 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
8419 "the same type as its result!");
8421 AccVT.getVectorElementCount()) &&
8422 "Expected the element count of the second and third operands of the "
8423 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
8424 "element count of the first operand and the result!");
8426 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
8427 "node to have an element type which is the same as or smaller than "
8428 "the element type of the first operand and result!");
8429 break;
8430 }
8431 }
8432
8433 // Perform trivial constant folding for arithmetic operators.
8434 switch (Opcode) {
8435 case ISD::FMA:
8436 case ISD::FMAD:
8437 case ISD::SETCC:
8438 case ISD::FSHL:
8439 case ISD::FSHR:
8440 if (SDValue SV =
8441 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
8442 return SV;
8443 break;
8444 }
8445
8446 // Memoize node if it doesn't produce a glue result.
8447 SDNode *N;
8448 SDVTList VTs = getVTList(VT);
8449 SDValue Ops[] = {N1, N2, N3};
8450 if (VT != MVT::Glue) {
8452 AddNodeIDNode(ID, Opcode, VTs, Ops);
8453 void *IP = nullptr;
8454 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8455 E->intersectFlagsWith(Flags);
8456 return SDValue(E, 0);
8457 }
8458
8459 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8460 N->setFlags(Flags);
8461 createOperands(N, Ops);
8462 CSEMap.InsertNode(N, IP);
8463 } else {
8464 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8465 createOperands(N, Ops);
8466 }
8467
8468 InsertNode(N);
8469 SDValue V = SDValue(N, 0);
8470 NewSDValueDbgMsg(V, "Creating new node: ", this);
8471 return V;
8472}
8473
8474SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8475 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8476 const SDNodeFlags Flags) {
8477 SDValue Ops[] = { N1, N2, N3, N4 };
8478 return getNode(Opcode, DL, VT, Ops, Flags);
8479}
8480
8481SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8482 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8483 SDNodeFlags Flags;
8484 if (Inserter)
8485 Flags = Inserter->getFlags();
8486 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
8487}
8488
8489SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8490 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8491 SDValue N5, const SDNodeFlags Flags) {
8492 SDValue Ops[] = { N1, N2, N3, N4, N5 };
8493 return getNode(Opcode, DL, VT, Ops, Flags);
8494}
8495
8496SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8497 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8498 SDValue N5) {
8499 SDNodeFlags Flags;
8500 if (Inserter)
8501 Flags = Inserter->getFlags();
8502 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
8503}
8504
8505/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
8506/// the incoming stack arguments to be loaded from the stack.
8508 SmallVector<SDValue, 8> ArgChains;
8509
8510 // Include the original chain at the beginning of the list. When this is
8511 // used by target LowerCall hooks, this helps legalize find the
8512 // CALLSEQ_BEGIN node.
8513 ArgChains.push_back(Chain);
8514
8515 // Add a chain value for each stack argument.
8516 for (SDNode *U : getEntryNode().getNode()->users())
8517 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
8518 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
8519 if (FI->getIndex() < 0)
8520 ArgChains.push_back(SDValue(L, 1));
8521
8522 // Build a tokenfactor for all the chains.
8523 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
8524}
8525
8526/// getMemsetValue - Vectorized representation of the memset value
8527/// operand.
8529 const SDLoc &dl) {
8530 assert(!Value.isUndef());
8531
8532 unsigned NumBits = VT.getScalarSizeInBits();
8534 assert(C->getAPIntValue().getBitWidth() == 8);
8535 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
8536 if (VT.isInteger()) {
8537 bool IsOpaque = VT.getSizeInBits() > 64 ||
8538 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
8539 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
8540 }
8541 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
8542 }
8543
8544 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
8545 EVT IntVT = VT.getScalarType();
8546 if (!IntVT.isInteger())
8547 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
8548
8549 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
8550 if (NumBits > 8) {
8551 // Use a multiplication with 0x010101... to extend the input to the
8552 // required length.
8553 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
8554 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
8555 DAG.getConstant(Magic, dl, IntVT));
8556 }
8557
8558 if (VT != Value.getValueType() && !VT.isInteger())
8559 Value = DAG.getBitcast(VT.getScalarType(), Value);
8560 if (VT != Value.getValueType())
8561 Value = DAG.getSplatBuildVector(VT, dl, Value);
8562
8563 return Value;
8564}
8565
8566/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
8567/// used when a memcpy is turned into a memset when the source is a constant
8568/// string ptr.
8570 const TargetLowering &TLI,
8571 const ConstantDataArraySlice &Slice) {
8572 // Handle vector with all elements zero.
8573 if (Slice.Array == nullptr) {
8574 if (VT.isInteger())
8575 return DAG.getConstant(0, dl, VT);
8576 return DAG.getNode(ISD::BITCAST, dl, VT,
8577 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
8578 }
8579
8580 assert(!VT.isVector() && "Can't handle vector type here!");
8581 unsigned NumVTBits = VT.getSizeInBits();
8582 unsigned NumVTBytes = NumVTBits / 8;
8583 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
8584
8585 APInt Val(NumVTBits, 0);
8586 if (DAG.getDataLayout().isLittleEndian()) {
8587 for (unsigned i = 0; i != NumBytes; ++i)
8588 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
8589 } else {
8590 for (unsigned i = 0; i != NumBytes; ++i)
8591 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
8592 }
8593
8594 // If the "cost" of materializing the integer immediate is less than the cost
8595 // of a load, then it is cost effective to turn the load into the immediate.
8596 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
8597 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
8598 return DAG.getConstant(Val, dl, VT);
8599 return SDValue();
8600}
8601
8603 const SDLoc &DL,
8604 const SDNodeFlags Flags) {
8605 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
8606 return getMemBasePlusOffset(Base, Index, DL, Flags);
8607}
8608
8610 const SDLoc &DL,
8611 const SDNodeFlags Flags) {
8612 assert(Offset.getValueType().isInteger());
8613 EVT BasePtrVT = Ptr.getValueType();
8614 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
8615 BasePtrVT))
8616 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
8617 // InBounds only applies to PTRADD, don't set it if we generate ADD.
8618 SDNodeFlags AddFlags = Flags;
8619 AddFlags.setInBounds(false);
8620 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
8621}
8622
8623/// Returns true if memcpy source is constant data.
8625 uint64_t SrcDelta = 0;
8626 GlobalAddressSDNode *G = nullptr;
8627 if (Src.getOpcode() == ISD::GlobalAddress)
8629 else if (Src->isAnyAdd() &&
8630 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
8631 Src.getOperand(1).getOpcode() == ISD::Constant) {
8632 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
8633 SrcDelta = Src.getConstantOperandVal(1);
8634 }
8635 if (!G)
8636 return false;
8637
8638 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
8639 SrcDelta + G->getOffset());
8640}
8641
8643 SelectionDAG &DAG) {
8644 // On Darwin, -Os means optimize for size without hurting performance, so
8645 // only really optimize for size when -Oz (MinSize) is used.
8647 return MF.getFunction().hasMinSize();
8648 return DAG.shouldOptForSize();
8649}
8650
8652 SmallVector<SDValue, 32> &OutChains, unsigned From,
8653 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
8654 SmallVector<SDValue, 16> &OutStoreChains) {
8655 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
8656 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
8657 SmallVector<SDValue, 16> GluedLoadChains;
8658 for (unsigned i = From; i < To; ++i) {
8659 OutChains.push_back(OutLoadChains[i]);
8660 GluedLoadChains.push_back(OutLoadChains[i]);
8661 }
8662
8663 // Chain for all loads.
8664 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8665 GluedLoadChains);
8666
8667 for (unsigned i = From; i < To; ++i) {
8668 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
8669 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
8670 ST->getBasePtr(), ST->getMemoryVT(),
8671 ST->getMemOperand());
8672 OutChains.push_back(NewStore);
8673 }
8674}
8675
8677 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
8678 uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline,
8679 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
8680 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
8681 // Turn a memcpy of undef to nop.
8682 // FIXME: We need to honor volatile even is Src is undef.
8683 if (Src.isUndef())
8684 return Chain;
8685
8686 // Expand memcpy to a series of load and store ops if the size operand falls
8687 // below a certain threshold.
8688 // TODO: In the AlwaysInline case, if the size is big then generate a loop
8689 // rather than maybe a humongous number of loads and stores.
8690 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8691 const DataLayout &DL = DAG.getDataLayout();
8692 LLVMContext &C = *DAG.getContext();
8693 std::vector<EVT> MemOps;
8694 bool DstAlignCanChange = false;
8696 MachineFrameInfo &MFI = MF.getFrameInfo();
8697 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
8699 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
8700 DstAlignCanChange = true;
8701 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
8702 if (!SrcAlign || Alignment > *SrcAlign)
8703 SrcAlign = Alignment;
8704 assert(SrcAlign && "SrcAlign must be set");
8706 // If marked as volatile, perform a copy even when marked as constant.
8707 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
8708 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
8709 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
8710 const MemOp Op = isZeroConstant
8711 ? MemOp::Set(Size, DstAlignCanChange, Alignment,
8712 /*IsZeroMemset*/ true, isVol)
8713 : MemOp::Copy(Size, DstAlignCanChange, Alignment,
8714 *SrcAlign, isVol, CopyFromConstant);
8715 if (!TLI.findOptimalMemOpLowering(
8716 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
8717 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
8718 return SDValue();
8719
8720 if (DstAlignCanChange) {
8721 Type *Ty = MemOps[0].getTypeForEVT(C);
8722 Align NewAlign = DL.getABITypeAlign(Ty);
8723
8724 // Don't promote to an alignment that would require dynamic stack
8725 // realignment which may conflict with optimizations such as tail call
8726 // optimization.
8728 if (!TRI->hasStackRealignment(MF))
8729 if (MaybeAlign StackAlign = DL.getStackAlignment())
8730 NewAlign = std::min(NewAlign, *StackAlign);
8731
8732 if (NewAlign > Alignment) {
8733 // Give the stack frame object a larger alignment if needed.
8734 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
8735 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
8736 Alignment = NewAlign;
8737 }
8738 }
8739
8740 // Prepare AAInfo for loads/stores after lowering this memcpy.
8741 AAMDNodes NewAAInfo = AAInfo;
8742 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
8743
8744 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
8745 bool isConstant =
8746 BatchAA && SrcVal &&
8747 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
8748
8749 MachineMemOperand::Flags MMOFlags =
8751 SmallVector<SDValue, 16> OutLoadChains;
8752 SmallVector<SDValue, 16> OutStoreChains;
8753 SmallVector<SDValue, 32> OutChains;
8754 unsigned NumMemOps = MemOps.size();
8755 uint64_t SrcOff = 0, DstOff = 0;
8756 for (unsigned i = 0; i != NumMemOps; ++i) {
8757 EVT VT = MemOps[i];
8758 unsigned VTSize = VT.getSizeInBits() / 8;
8759 SDValue Value, Store;
8760
8761 if (VTSize > Size) {
8762 // Issuing an unaligned load / store pair that overlaps with the previous
8763 // pair. Adjust the offset accordingly.
8764 assert(i == NumMemOps-1 && i != 0);
8765 SrcOff -= VTSize - Size;
8766 DstOff -= VTSize - Size;
8767 }
8768
8769 if (CopyFromConstant &&
8770 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
8771 // It's unlikely a store of a vector immediate can be done in a single
8772 // instruction. It would require a load from a constantpool first.
8773 // We only handle zero vectors here.
8774 // FIXME: Handle other cases where store of vector immediate is done in
8775 // a single instruction.
8776 ConstantDataArraySlice SubSlice;
8777 if (SrcOff < Slice.Length) {
8778 SubSlice = Slice;
8779 SubSlice.move(SrcOff);
8780 } else {
8781 // This is an out-of-bounds access and hence UB. Pretend we read zero.
8782 SubSlice.Array = nullptr;
8783 SubSlice.Offset = 0;
8784 SubSlice.Length = VTSize;
8785 }
8786 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
8787 if (Value.getNode()) {
8788 Store = DAG.getStore(
8789 Chain, dl, Value,
8790 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
8791 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
8792 OutChains.push_back(Store);
8793 }
8794 }
8795
8796 if (!Store.getNode()) {
8797 // The type might not be legal for the target. This should only happen
8798 // if the type is smaller than a legal type, as on PPC, so the right
8799 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
8800 // to Load/Store if NVT==VT.
8801 // FIXME does the case above also need this?
8802 EVT NVT = TLI.getTypeToTransformTo(C, VT);
8803 assert(NVT.bitsGE(VT));
8804
8805 bool isDereferenceable =
8806 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
8807 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
8808 if (isDereferenceable)
8810 if (isConstant)
8811 SrcMMOFlags |= MachineMemOperand::MOInvariant;
8812
8813 Value = DAG.getExtLoad(
8814 ISD::EXTLOAD, dl, NVT, Chain,
8815 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
8816 SrcPtrInfo.getWithOffset(SrcOff), VT,
8817 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
8818 OutLoadChains.push_back(Value.getValue(1));
8819
8820 Store = DAG.getTruncStore(
8821 Chain, dl, Value,
8822 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
8823 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
8824 OutStoreChains.push_back(Store);
8825 }
8826 SrcOff += VTSize;
8827 DstOff += VTSize;
8828 Size -= VTSize;
8829 }
8830
8831 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
8833 unsigned NumLdStInMemcpy = OutStoreChains.size();
8834
8835 if (NumLdStInMemcpy) {
8836 // It may be that memcpy might be converted to memset if it's memcpy
8837 // of constants. In such a case, we won't have loads and stores, but
8838 // just stores. In the absence of loads, there is nothing to gang up.
8839 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
8840 // If target does not care, just leave as it.
8841 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
8842 OutChains.push_back(OutLoadChains[i]);
8843 OutChains.push_back(OutStoreChains[i]);
8844 }
8845 } else {
8846 // Ld/St less than/equal limit set by target.
8847 if (NumLdStInMemcpy <= GluedLdStLimit) {
8848 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
8849 NumLdStInMemcpy, OutLoadChains,
8850 OutStoreChains);
8851 } else {
8852 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
8853 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
8854 unsigned GlueIter = 0;
8855
8856 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
8857 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
8858 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
8859
8860 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
8861 OutLoadChains, OutStoreChains);
8862 GlueIter += GluedLdStLimit;
8863 }
8864
8865 // Residual ld/st.
8866 if (RemainingLdStInMemcpy) {
8867 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
8868 RemainingLdStInMemcpy, OutLoadChains,
8869 OutStoreChains);
8870 }
8871 }
8872 }
8873 }
8874 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
8875}
8876
8878 SDValue Chain, SDValue Dst, SDValue Src,
8879 uint64_t Size, Align Alignment,
8880 bool isVol, bool AlwaysInline,
8881 MachinePointerInfo DstPtrInfo,
8882 MachinePointerInfo SrcPtrInfo,
8883 const AAMDNodes &AAInfo) {
8884 // Turn a memmove of undef to nop.
8885 // FIXME: We need to honor volatile even is Src is undef.
8886 if (Src.isUndef())
8887 return Chain;
8888
8889 // Expand memmove to a series of load and store ops if the size operand falls
8890 // below a certain threshold.
8891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8892 const DataLayout &DL = DAG.getDataLayout();
8893 LLVMContext &C = *DAG.getContext();
8894 std::vector<EVT> MemOps;
8895 bool DstAlignCanChange = false;
8897 MachineFrameInfo &MFI = MF.getFrameInfo();
8898 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
8900 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
8901 DstAlignCanChange = true;
8902 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
8903 if (!SrcAlign || Alignment > *SrcAlign)
8904 SrcAlign = Alignment;
8905 assert(SrcAlign && "SrcAlign must be set");
8906 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
8907 if (!TLI.findOptimalMemOpLowering(
8908 C, MemOps, Limit,
8909 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
8910 /*IsVolatile*/ true),
8911 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
8912 MF.getFunction().getAttributes()))
8913 return SDValue();
8914
8915 if (DstAlignCanChange) {
8916 Type *Ty = MemOps[0].getTypeForEVT(C);
8917 Align NewAlign = DL.getABITypeAlign(Ty);
8918
8919 // Don't promote to an alignment that would require dynamic stack
8920 // realignment which may conflict with optimizations such as tail call
8921 // optimization.
8923 if (!TRI->hasStackRealignment(MF))
8924 if (MaybeAlign StackAlign = DL.getStackAlignment())
8925 NewAlign = std::min(NewAlign, *StackAlign);
8926
8927 if (NewAlign > Alignment) {
8928 // Give the stack frame object a larger alignment if needed.
8929 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
8930 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
8931 Alignment = NewAlign;
8932 }
8933 }
8934
8935 // Prepare AAInfo for loads/stores after lowering this memmove.
8936 AAMDNodes NewAAInfo = AAInfo;
8937 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
8938
8939 MachineMemOperand::Flags MMOFlags =
8941 uint64_t SrcOff = 0, DstOff = 0;
8942 SmallVector<SDValue, 8> LoadValues;
8943 SmallVector<SDValue, 8> LoadChains;
8944 SmallVector<SDValue, 8> OutChains;
8945 unsigned NumMemOps = MemOps.size();
8946 for (unsigned i = 0; i < NumMemOps; i++) {
8947 EVT VT = MemOps[i];
8948 unsigned VTSize = VT.getSizeInBits() / 8;
8949 SDValue Value;
8950
8951 bool isDereferenceable =
8952 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
8953 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
8954 if (isDereferenceable)
8956
8957 Value = DAG.getLoad(
8958 VT, dl, Chain,
8959 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
8960 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
8961 LoadValues.push_back(Value);
8962 LoadChains.push_back(Value.getValue(1));
8963 SrcOff += VTSize;
8964 }
8965 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8966 OutChains.clear();
8967 for (unsigned i = 0; i < NumMemOps; i++) {
8968 EVT VT = MemOps[i];
8969 unsigned VTSize = VT.getSizeInBits() / 8;
8970 SDValue Store;
8971
8972 Store = DAG.getStore(
8973 Chain, dl, LoadValues[i],
8974 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
8975 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
8976 OutChains.push_back(Store);
8977 DstOff += VTSize;
8978 }
8979
8980 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
8981}
8982
8983/// Lower the call to 'memset' intrinsic function into a series of store
8984/// operations.
8985///
8986/// \param DAG Selection DAG where lowered code is placed.
8987/// \param dl Link to corresponding IR location.
8988/// \param Chain Control flow dependency.
8989/// \param Dst Pointer to destination memory location.
8990/// \param Src Value of byte to write into the memory.
8991/// \param Size Number of bytes to write.
8992/// \param Alignment Alignment of the destination in bytes.
8993/// \param isVol True if destination is volatile.
8994/// \param AlwaysInline Makes sure no function call is generated.
8995/// \param DstPtrInfo IR information on the memory pointer.
8996/// \returns New head in the control flow, if lowering was successful, empty
8997/// SDValue otherwise.
8998///
8999/// The function tries to replace 'llvm.memset' intrinsic with several store
9000/// operations and value calculation code. This is usually profitable for small
9001/// memory size or when the semantic requires inlining.
9003 SDValue Chain, SDValue Dst, SDValue Src,
9004 uint64_t Size, Align Alignment, bool isVol,
9005 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9006 const AAMDNodes &AAInfo) {
9007 // Turn a memset of undef to nop.
9008 // FIXME: We need to honor volatile even is Src is undef.
9009 if (Src.isUndef())
9010 return Chain;
9011
9012 // Expand memset to a series of load/store ops if the size operand
9013 // falls below a certain threshold.
9014 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9015 std::vector<EVT> MemOps;
9016 bool DstAlignCanChange = false;
9017 LLVMContext &C = *DAG.getContext();
9019 MachineFrameInfo &MFI = MF.getFrameInfo();
9020 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9022 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9023 DstAlignCanChange = true;
9024 bool IsZeroVal = isNullConstant(Src);
9025 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9026
9027 if (!TLI.findOptimalMemOpLowering(
9028 C, MemOps, Limit,
9029 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9030 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
9031 return SDValue();
9032
9033 if (DstAlignCanChange) {
9034 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9035 const DataLayout &DL = DAG.getDataLayout();
9036 Align NewAlign = DL.getABITypeAlign(Ty);
9037
9038 // Don't promote to an alignment that would require dynamic stack
9039 // realignment which may conflict with optimizations such as tail call
9040 // optimization.
9042 if (!TRI->hasStackRealignment(MF))
9043 if (MaybeAlign StackAlign = DL.getStackAlignment())
9044 NewAlign = std::min(NewAlign, *StackAlign);
9045
9046 if (NewAlign > Alignment) {
9047 // Give the stack frame object a larger alignment if needed.
9048 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9049 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9050 Alignment = NewAlign;
9051 }
9052 }
9053
9054 SmallVector<SDValue, 8> OutChains;
9055 uint64_t DstOff = 0;
9056 unsigned NumMemOps = MemOps.size();
9057
9058 // Find the largest store and generate the bit pattern for it.
9059 EVT LargestVT = MemOps[0];
9060 for (unsigned i = 1; i < NumMemOps; i++)
9061 if (MemOps[i].bitsGT(LargestVT))
9062 LargestVT = MemOps[i];
9063 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9064
9065 // Prepare AAInfo for loads/stores after lowering this memset.
9066 AAMDNodes NewAAInfo = AAInfo;
9067 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9068
9069 for (unsigned i = 0; i < NumMemOps; i++) {
9070 EVT VT = MemOps[i];
9071 unsigned VTSize = VT.getSizeInBits() / 8;
9072 if (VTSize > Size) {
9073 // Issuing an unaligned load / store pair that overlaps with the previous
9074 // pair. Adjust the offset accordingly.
9075 assert(i == NumMemOps-1 && i != 0);
9076 DstOff -= VTSize - Size;
9077 }
9078
9079 // If this store is smaller than the largest store see whether we can get
9080 // the smaller value for free with a truncate or extract vector element and
9081 // then store.
9082 SDValue Value = MemSetValue;
9083 if (VT.bitsLT(LargestVT)) {
9084 unsigned Index;
9085 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9086 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9087 if (!LargestVT.isVector() && !VT.isVector() &&
9088 TLI.isTruncateFree(LargestVT, VT))
9089 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9090 else if (LargestVT.isVector() && !VT.isVector() &&
9092 LargestVT.getTypeForEVT(*DAG.getContext()),
9093 VT.getSizeInBits(), Index) &&
9094 TLI.isTypeLegal(SVT) &&
9095 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9096 // Target which can combine store(extractelement VectorTy, Idx) can get
9097 // the smaller value for free.
9098 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9099 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9100 } else
9101 Value = getMemsetValue(Src, VT, DAG, dl);
9102 }
9103 assert(Value.getValueType() == VT && "Value with wrong type.");
9104 SDValue Store = DAG.getStore(
9105 Chain, dl, Value,
9106 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9107 DstPtrInfo.getWithOffset(DstOff), Alignment,
9109 NewAAInfo);
9110 OutChains.push_back(Store);
9111 DstOff += VT.getSizeInBits() / 8;
9112 Size -= VTSize;
9113 }
9114
9115 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
9116}
9117
9119 unsigned AS) {
9120 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
9121 // pointer operands can be losslessly bitcasted to pointers of address space 0
9122 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
9123 report_fatal_error("cannot lower memory intrinsic in address space " +
9124 Twine(AS));
9125 }
9126}
9127
9129 const SelectionDAG *SelDAG,
9130 bool AllowReturnsFirstArg) {
9131 if (!CI || !CI->isTailCall())
9132 return false;
9133 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
9134 // helper symbol we lower to.
9135 return isInTailCallPosition(*CI, SelDAG->getTarget(),
9136 AllowReturnsFirstArg &&
9138}
9139
9140std::pair<SDValue, SDValue>
9142 SDValue Mem1, SDValue Size, const CallInst *CI) {
9143 RTLIB::LibcallImpl MemcmpImpl = TLI->getLibcallImpl(RTLIB::MEMCMP);
9144 if (MemcmpImpl == RTLIB::Unsupported)
9145 return {};
9146
9149 {Mem0, PT},
9150 {Mem1, PT},
9152
9154 bool IsTailCall =
9155 isInTailCallPositionWrapper(CI, this, /*AllowReturnsFirstArg*/ true);
9156
9157 CLI.setDebugLoc(dl)
9158 .setChain(Chain)
9159 .setLibCallee(
9160 TLI->getLibcallImplCallingConv(MemcmpImpl),
9162 getExternalSymbol(MemcmpImpl, TLI->getPointerTy(getDataLayout())),
9163 std::move(Args))
9164 .setTailCall(IsTailCall);
9165
9166 return TLI->LowerCallTo(CLI);
9167}
9168
9169std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
9170 const SDLoc &dl,
9171 SDValue Src,
9172 const CallInst *CI) {
9173 RTLIB::LibcallImpl StrlenImpl = TLI->getLibcallImpl(RTLIB::STRLEN);
9174 if (StrlenImpl == RTLIB::Unsupported)
9175 return {};
9176
9177 // Emit a library call.
9180
9182 bool IsTailCall =
9183 isInTailCallPositionWrapper(CI, this, /*AllowReturnsFirstArg*/ true);
9184
9185 CLI.setDebugLoc(dl)
9186 .setChain(Chain)
9187 .setLibCallee(TLI->getLibcallImplCallingConv(StrlenImpl), CI->getType(),
9189 StrlenImpl, TLI->getProgramPointerTy(getDataLayout())),
9190 std::move(Args))
9191 .setTailCall(IsTailCall);
9192
9193 return TLI->LowerCallTo(CLI);
9194}
9195
9197 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
9198 Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI,
9199 std::optional<bool> OverrideTailCall, MachinePointerInfo DstPtrInfo,
9200 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9201 BatchAAResults *BatchAA) {
9202 // Check to see if we should lower the memcpy to loads and stores first.
9203 // For cases within the target-specified limits, this is the best choice.
9205 if (ConstantSize) {
9206 // Memcpy with size zero? Just return the original chain.
9207 if (ConstantSize->isZero())
9208 return Chain;
9209
9211 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
9212 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA);
9213 if (Result.getNode())
9214 return Result;
9215 }
9216
9217 // Then check to see if we should lower the memcpy with target-specific
9218 // code. If the target chooses to do this, this is the next best.
9219 if (TSI) {
9220 SDValue Result = TSI->EmitTargetCodeForMemcpy(
9221 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
9222 DstPtrInfo, SrcPtrInfo);
9223 if (Result.getNode())
9224 return Result;
9225 }
9226
9227 // If we really need inline code and the target declined to provide it,
9228 // use a (potentially long) sequence of loads and stores.
9229 if (AlwaysInline) {
9230 assert(ConstantSize && "AlwaysInline requires a constant size!");
9232 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
9233 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA);
9234 }
9235
9238
9239 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
9240 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
9241 // respect volatile, so they may do things like read or write memory
9242 // beyond the given memory regions. But fixing this isn't easy, and most
9243 // people don't care.
9244
9245 // Emit a library call.
9248 Args.emplace_back(Dst, PtrTy);
9249 Args.emplace_back(Src, PtrTy);
9250 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
9251 // FIXME: pass in SDLoc
9253 bool IsTailCall = false;
9254 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
9255
9256 if (OverrideTailCall.has_value()) {
9257 IsTailCall = *OverrideTailCall;
9258 } else {
9259 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
9260 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
9261 }
9262
9263 CLI.setDebugLoc(dl)
9264 .setChain(Chain)
9265 .setLibCallee(
9266 TLI->getLibcallImplCallingConv(MemCpyImpl),
9267 Dst.getValueType().getTypeForEVT(*getContext()),
9268 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
9269 std::move(Args))
9271 .setTailCall(IsTailCall);
9272
9273 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
9274 return CallResult.second;
9275}
9276
9278 SDValue Dst, SDValue Src, SDValue Size,
9279 Type *SizeTy, unsigned ElemSz,
9280 bool isTailCall,
9281 MachinePointerInfo DstPtrInfo,
9282 MachinePointerInfo SrcPtrInfo) {
9283 // Emit a library call.
9286 Args.emplace_back(Dst, ArgTy);
9287 Args.emplace_back(Src, ArgTy);
9288 Args.emplace_back(Size, SizeTy);
9289
9290 RTLIB::Libcall LibraryCall =
9292 RTLIB::LibcallImpl LibcallImpl = TLI->getLibcallImpl(LibraryCall);
9293 if (LibcallImpl == RTLIB::Unsupported)
9294 report_fatal_error("Unsupported element size");
9295
9297 CLI.setDebugLoc(dl)
9298 .setChain(Chain)
9299 .setLibCallee(
9300 TLI->getLibcallImplCallingConv(LibcallImpl),
9302 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
9303 std::move(Args))
9305 .setTailCall(isTailCall);
9306
9307 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9308 return CallResult.second;
9309}
9310
9312 SDValue Src, SDValue Size, Align Alignment,
9313 bool isVol, const CallInst *CI,
9314 std::optional<bool> OverrideTailCall,
9315 MachinePointerInfo DstPtrInfo,
9316 MachinePointerInfo SrcPtrInfo,
9317 const AAMDNodes &AAInfo,
9318 BatchAAResults *BatchAA) {
9319 // Check to see if we should lower the memmove to loads and stores first.
9320 // For cases within the target-specified limits, this is the best choice.
9322 if (ConstantSize) {
9323 // Memmove with size zero? Just return the original chain.
9324 if (ConstantSize->isZero())
9325 return Chain;
9326
9328 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
9329 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
9330 if (Result.getNode())
9331 return Result;
9332 }
9333
9334 // Then check to see if we should lower the memmove with target-specific
9335 // code. If the target chooses to do this, this is the next best.
9336 if (TSI) {
9337 SDValue Result =
9338 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
9339 Alignment, isVol, DstPtrInfo, SrcPtrInfo);
9340 if (Result.getNode())
9341 return Result;
9342 }
9343
9346
9347 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
9348 // not be safe. See memcpy above for more details.
9349
9350 // Emit a library call.
9353 Args.emplace_back(Dst, PtrTy);
9354 Args.emplace_back(Src, PtrTy);
9355 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
9356 // FIXME: pass in SDLoc
9358
9359 RTLIB::LibcallImpl MemmoveImpl = TLI->getLibcallImpl(RTLIB::MEMMOVE);
9360
9361 bool IsTailCall = false;
9362 if (OverrideTailCall.has_value()) {
9363 IsTailCall = *OverrideTailCall;
9364 } else {
9365 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
9366 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
9367 }
9368
9369 CLI.setDebugLoc(dl)
9370 .setChain(Chain)
9371 .setLibCallee(
9372 TLI->getLibcallImplCallingConv(MemmoveImpl),
9373 Dst.getValueType().getTypeForEVT(*getContext()),
9374 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
9375 std::move(Args))
9377 .setTailCall(IsTailCall);
9378
9379 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
9380 return CallResult.second;
9381}
9382
9384 SDValue Dst, SDValue Src, SDValue Size,
9385 Type *SizeTy, unsigned ElemSz,
9386 bool isTailCall,
9387 MachinePointerInfo DstPtrInfo,
9388 MachinePointerInfo SrcPtrInfo) {
9389 // Emit a library call.
9391 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
9392 Args.emplace_back(Dst, IntPtrTy);
9393 Args.emplace_back(Src, IntPtrTy);
9394 Args.emplace_back(Size, SizeTy);
9395
9396 RTLIB::Libcall LibraryCall =
9398 RTLIB::LibcallImpl LibcallImpl = TLI->getLibcallImpl(LibraryCall);
9399 if (LibcallImpl == RTLIB::Unsupported)
9400 report_fatal_error("Unsupported element size");
9401
9403 CLI.setDebugLoc(dl)
9404 .setChain(Chain)
9405 .setLibCallee(
9406 TLI->getLibcallImplCallingConv(LibcallImpl),
9408 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
9409 std::move(Args))
9411 .setTailCall(isTailCall);
9412
9413 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9414 return CallResult.second;
9415}
9416
9418 SDValue Src, SDValue Size, Align Alignment,
9419 bool isVol, bool AlwaysInline,
9420 const CallInst *CI,
9421 MachinePointerInfo DstPtrInfo,
9422 const AAMDNodes &AAInfo) {
9423 // Check to see if we should lower the memset to stores first.
9424 // For cases within the target-specified limits, this is the best choice.
9426 if (ConstantSize) {
9427 // Memset with size zero? Just return the original chain.
9428 if (ConstantSize->isZero())
9429 return Chain;
9430
9431 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
9432 ConstantSize->getZExtValue(), Alignment,
9433 isVol, false, DstPtrInfo, AAInfo);
9434
9435 if (Result.getNode())
9436 return Result;
9437 }
9438
9439 // Then check to see if we should lower the memset with target-specific
9440 // code. If the target chooses to do this, this is the next best.
9441 if (TSI) {
9442 SDValue Result = TSI->EmitTargetCodeForMemset(
9443 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
9444 if (Result.getNode())
9445 return Result;
9446 }
9447
9448 // If we really need inline code and the target declined to provide it,
9449 // use a (potentially long) sequence of loads and stores.
9450 if (AlwaysInline) {
9451 assert(ConstantSize && "AlwaysInline requires a constant size!");
9452 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
9453 ConstantSize->getZExtValue(), Alignment,
9454 isVol, true, DstPtrInfo, AAInfo);
9455 assert(Result &&
9456 "getMemsetStores must return a valid sequence when AlwaysInline");
9457 return Result;
9458 }
9459
9461
9462 // Emit a library call.
9463 auto &Ctx = *getContext();
9464 const auto& DL = getDataLayout();
9465
9467 // FIXME: pass in SDLoc
9468 CLI.setDebugLoc(dl).setChain(Chain);
9469
9470 RTLIB::LibcallImpl BzeroImpl = TLI->getLibcallImpl(RTLIB::BZERO);
9471 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
9472
9473 // If zeroing out and bzero is present, use it.
9474 if (UseBZero) {
9476 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
9477 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
9478 CLI.setLibCallee(
9479 TLI->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
9480 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
9481 } else {
9482 RTLIB::LibcallImpl MemsetImpl = TLI->getLibcallImpl(RTLIB::MEMSET);
9483
9485 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
9486 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
9487 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
9488 CLI.setLibCallee(TLI->getLibcallImplCallingConv(MemsetImpl),
9489 Dst.getValueType().getTypeForEVT(Ctx),
9490 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
9491 std::move(Args));
9492 }
9493
9494 RTLIB::LibcallImpl MemsetImpl = TLI->getLibcallImpl(RTLIB::MEMSET);
9495 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
9496
9497 // If we're going to use bzero, make sure not to tail call unless the
9498 // subsequent return doesn't need a value, as bzero doesn't return the first
9499 // arg unlike memset.
9500 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
9501 bool IsTailCall =
9502 CI && CI->isTailCall() &&
9503 isInTailCallPosition(*CI, getTarget(), ReturnsFirstArg && LowersToMemset);
9504 CLI.setDiscardResult().setTailCall(IsTailCall);
9505
9506 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9507 return CallResult.second;
9508}
9509
9512 Type *SizeTy, unsigned ElemSz,
9513 bool isTailCall,
9514 MachinePointerInfo DstPtrInfo) {
9515 // Emit a library call.
9517 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
9518 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
9519 Args.emplace_back(Size, SizeTy);
9520
9521 RTLIB::Libcall LibraryCall =
9523 RTLIB::LibcallImpl LibcallImpl = TLI->getLibcallImpl(LibraryCall);
9524 if (LibcallImpl == RTLIB::Unsupported)
9525 report_fatal_error("Unsupported element size");
9526
9528 CLI.setDebugLoc(dl)
9529 .setChain(Chain)
9530 .setLibCallee(
9531 TLI->getLibcallImplCallingConv(LibcallImpl),
9533 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
9534 std::move(Args))
9536 .setTailCall(isTailCall);
9537
9538 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
9539 return CallResult.second;
9540}
9541
9542SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
9544 MachineMemOperand *MMO,
9545 ISD::LoadExtType ExtType) {
9547 AddNodeIDNode(ID, Opcode, VTList, Ops);
9548 ID.AddInteger(MemVT.getRawBits());
9549 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
9550 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
9551 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9552 ID.AddInteger(MMO->getFlags());
9553 void* IP = nullptr;
9554 if (auto *E = cast_or_null<AtomicSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
9555 E->refineAlignment(MMO);
9556 E->refineRanges(MMO);
9557 return SDValue(E, 0);
9558 }
9559
9560 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
9561 VTList, MemVT, MMO, ExtType);
9562 createOperands(N, Ops);
9563
9564 CSEMap.InsertNode(N, IP);
9565 InsertNode(N);
9566 SDValue V(N, 0);
9567 NewSDValueDbgMsg(V, "Creating new node: ", this);
9568 return V;
9569}
9570
9572 EVT MemVT, SDVTList VTs, SDValue Chain,
9573 SDValue Ptr, SDValue Cmp, SDValue Swp,
9574 MachineMemOperand *MMO) {
9575 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
9577 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
9578
9579 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
9580 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
9581}
9582
9583SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
9584 SDValue Chain, SDValue Ptr, SDValue Val,
9585 MachineMemOperand *MMO) {
9586 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
9587 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
9588 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
9589 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
9590 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
9591 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
9592 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
9593 Opcode == ISD::ATOMIC_LOAD_FMIN ||
9594 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
9595 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
9596 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
9597 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
9598 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
9599 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
9600 Opcode == ISD::ATOMIC_STORE) &&
9601 "Invalid Atomic Op");
9602
9603 EVT VT = Val.getValueType();
9604
9605 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
9606 getVTList(VT, MVT::Other);
9607 SDValue Ops[] = {Chain, Ptr, Val};
9608 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
9609}
9610
9612 EVT MemVT, EVT VT, SDValue Chain,
9613 SDValue Ptr, MachineMemOperand *MMO) {
9614 SDVTList VTs = getVTList(VT, MVT::Other);
9615 SDValue Ops[] = {Chain, Ptr};
9616 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
9617}
9618
9619/// getMergeValues - Create a MERGE_VALUES node from the given operands.
9621 if (Ops.size() == 1)
9622 return Ops[0];
9623
9625 VTs.reserve(Ops.size());
9626 for (const SDValue &Op : Ops)
9627 VTs.push_back(Op.getValueType());
9628 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
9629}
9630
9632 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
9633 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
9635 const AAMDNodes &AAInfo) {
9636 if (Size.hasValue() && !Size.getValue())
9638
9640 MachineMemOperand *MMO =
9641 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
9642
9643 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
9644}
9645
9647 SDVTList VTList,
9648 ArrayRef<SDValue> Ops, EVT MemVT,
9649 MachineMemOperand *MMO) {
9650 assert(
9651 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
9652 Opcode == ISD::PREFETCH ||
9653 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
9654 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
9655 "Opcode is not a memory-accessing opcode!");
9656
9657 // Memoize the node unless it returns a glue result.
9659 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9661 AddNodeIDNode(ID, Opcode, VTList, Ops);
9662 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
9663 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
9664 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9665 ID.AddInteger(MMO->getFlags());
9666 ID.AddInteger(MemVT.getRawBits());
9667 void *IP = nullptr;
9668 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9669 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
9670 return SDValue(E, 0);
9671 }
9672
9673 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
9674 VTList, MemVT, MMO);
9675 createOperands(N, Ops);
9676
9677 CSEMap.InsertNode(N, IP);
9678 } else {
9679 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
9680 VTList, MemVT, MMO);
9681 createOperands(N, Ops);
9682 }
9683 InsertNode(N);
9684 SDValue V(N, 0);
9685 NewSDValueDbgMsg(V, "Creating new node: ", this);
9686 return V;
9687}
9688
9690 SDValue Chain, int FrameIndex) {
9691 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
9692 const auto VTs = getVTList(MVT::Other);
9693 SDValue Ops[2] = {
9694 Chain,
9695 getFrameIndex(FrameIndex,
9696 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
9697 true)};
9698
9700 AddNodeIDNode(ID, Opcode, VTs, Ops);
9701 ID.AddInteger(FrameIndex);
9702 void *IP = nullptr;
9703 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
9704 return SDValue(E, 0);
9705
9706 LifetimeSDNode *N =
9707 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
9708 createOperands(N, Ops);
9709 CSEMap.InsertNode(N, IP);
9710 InsertNode(N);
9711 SDValue V(N, 0);
9712 NewSDValueDbgMsg(V, "Creating new node: ", this);
9713 return V;
9714}
9715
9717 uint64_t Guid, uint64_t Index,
9718 uint32_t Attr) {
9719 const unsigned Opcode = ISD::PSEUDO_PROBE;
9720 const auto VTs = getVTList(MVT::Other);
9721 SDValue Ops[] = {Chain};
9723 AddNodeIDNode(ID, Opcode, VTs, Ops);
9724 ID.AddInteger(Guid);
9725 ID.AddInteger(Index);
9726 void *IP = nullptr;
9727 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
9728 return SDValue(E, 0);
9729
9730 auto *N = newSDNode<PseudoProbeSDNode>(
9731 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
9732 createOperands(N, Ops);
9733 CSEMap.InsertNode(N, IP);
9734 InsertNode(N);
9735 SDValue V(N, 0);
9736 NewSDValueDbgMsg(V, "Creating new node: ", this);
9737 return V;
9738}
9739
9740/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
9741/// MachinePointerInfo record from it. This is particularly useful because the
9742/// code generator has many cases where it doesn't bother passing in a
9743/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
9745 SelectionDAG &DAG, SDValue Ptr,
9746 int64_t Offset = 0) {
9747 // If this is FI+Offset, we can model it.
9748 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
9750 FI->getIndex(), Offset);
9751
9752 // If this is (FI+Offset1)+Offset2, we can model it.
9753 if (Ptr.getOpcode() != ISD::ADD ||
9756 return Info;
9757
9758 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9760 DAG.getMachineFunction(), FI,
9761 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
9762}
9763
9764/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
9765/// MachinePointerInfo record from it. This is particularly useful because the
9766/// code generator has many cases where it doesn't bother passing in a
9767/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
9769 SelectionDAG &DAG, SDValue Ptr,
9770 SDValue OffsetOp) {
9771 // If the 'Offset' value isn't a constant, we can't handle this.
9773 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
9774 if (OffsetOp.isUndef())
9775 return InferPointerInfo(Info, DAG, Ptr);
9776 return Info;
9777}
9778
9780 EVT VT, const SDLoc &dl, SDValue Chain,
9781 SDValue Ptr, SDValue Offset,
9782 MachinePointerInfo PtrInfo, EVT MemVT,
9783 Align Alignment,
9784 MachineMemOperand::Flags MMOFlags,
9785 const AAMDNodes &AAInfo, const MDNode *Ranges) {
9786 assert(Chain.getValueType() == MVT::Other &&
9787 "Invalid chain type");
9788
9789 MMOFlags |= MachineMemOperand::MOLoad;
9790 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
9791 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
9792 // clients.
9793 if (PtrInfo.V.isNull())
9794 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
9795
9796 TypeSize Size = MemVT.getStoreSize();
9798 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
9799 Alignment, AAInfo, Ranges);
9800 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
9801}
9802
9804 EVT VT, const SDLoc &dl, SDValue Chain,
9805 SDValue Ptr, SDValue Offset, EVT MemVT,
9806 MachineMemOperand *MMO) {
9807 if (VT == MemVT) {
9808 ExtType = ISD::NON_EXTLOAD;
9809 } else if (ExtType == ISD::NON_EXTLOAD) {
9810 assert(VT == MemVT && "Non-extending load from different memory type!");
9811 } else {
9812 // Extending load.
9813 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
9814 "Should only be an extending load, not truncating!");
9815 assert(VT.isInteger() == MemVT.isInteger() &&
9816 "Cannot convert from FP to Int or Int -> FP!");
9817 assert(VT.isVector() == MemVT.isVector() &&
9818 "Cannot use an ext load to convert to or from a vector!");
9819 assert((!VT.isVector() ||
9821 "Cannot use an ext load to change the number of vector elements!");
9822 }
9823
9824 assert((!MMO->getRanges() ||
9826 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
9827 MemVT.isInteger())) &&
9828 "Range metadata and load type must match!");
9829
9830 bool Indexed = AM != ISD::UNINDEXED;
9831 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
9832
9833 SDVTList VTs = Indexed ?
9834 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
9835 SDValue Ops[] = { Chain, Ptr, Offset };
9837 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
9838 ID.AddInteger(MemVT.getRawBits());
9839 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
9840 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
9841 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9842 ID.AddInteger(MMO->getFlags());
9843 void *IP = nullptr;
9844 if (auto *E = cast_or_null<LoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
9845 E->refineAlignment(MMO);
9846 E->refineRanges(MMO);
9847 return SDValue(E, 0);
9848 }
9849 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
9850 ExtType, MemVT, MMO);
9851 createOperands(N, Ops);
9852
9853 CSEMap.InsertNode(N, IP);
9854 InsertNode(N);
9855 SDValue V(N, 0);
9856 NewSDValueDbgMsg(V, "Creating new node: ", this);
9857 return V;
9858}
9859
9861 SDValue Ptr, MachinePointerInfo PtrInfo,
9862 MaybeAlign Alignment,
9863 MachineMemOperand::Flags MMOFlags,
9864 const AAMDNodes &AAInfo, const MDNode *Ranges) {
9865 SDValue Undef = getUNDEF(Ptr.getValueType());
9866 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
9867 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
9868}
9869
9871 SDValue Ptr, MachineMemOperand *MMO) {
9872 SDValue Undef = getUNDEF(Ptr.getValueType());
9873 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
9874 VT, MMO);
9875}
9876
9878 EVT VT, SDValue Chain, SDValue Ptr,
9879 MachinePointerInfo PtrInfo, EVT MemVT,
9880 MaybeAlign Alignment,
9881 MachineMemOperand::Flags MMOFlags,
9882 const AAMDNodes &AAInfo) {
9883 SDValue Undef = getUNDEF(Ptr.getValueType());
9884 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
9885 MemVT, Alignment, MMOFlags, AAInfo);
9886}
9887
9889 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
9890 MachineMemOperand *MMO) {
9891 SDValue Undef = getUNDEF(Ptr.getValueType());
9892 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
9893 MemVT, MMO);
9894}
9895
9899 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
9900 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
9901 // Don't propagate the invariant or dereferenceable flags.
9902 auto MMOFlags =
9903 LD->getMemOperand()->getFlags() &
9905 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
9906 LD->getChain(), Base, Offset, LD->getPointerInfo(),
9907 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
9908}
9909
9911 SDValue Ptr, MachinePointerInfo PtrInfo,
9912 Align Alignment,
9913 MachineMemOperand::Flags MMOFlags,
9914 const AAMDNodes &AAInfo) {
9915 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
9916
9917 MMOFlags |= MachineMemOperand::MOStore;
9918 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
9919
9920 if (PtrInfo.V.isNull())
9921 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
9922
9925 MachineMemOperand *MMO =
9926 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
9927 return getStore(Chain, dl, Val, Ptr, MMO);
9928}
9929
9931 SDValue Ptr, MachineMemOperand *MMO) {
9932 SDValue Undef = getUNDEF(Ptr.getValueType());
9933 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
9935}
9936
9938 SDValue Ptr, SDValue Offset, EVT SVT,
9940 bool IsTruncating) {
9941 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
9942 EVT VT = Val.getValueType();
9943 if (VT == SVT) {
9944 IsTruncating = false;
9945 } else if (!IsTruncating) {
9946 assert(VT == SVT && "No-truncating store from different memory type!");
9947 } else {
9949 "Should only be a truncating store, not extending!");
9950 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
9951 assert(VT.isVector() == SVT.isVector() &&
9952 "Cannot use trunc store to convert to or from a vector!");
9953 assert((!VT.isVector() ||
9955 "Cannot use trunc store to change the number of vector elements!");
9956 }
9957
9958 bool Indexed = AM != ISD::UNINDEXED;
9959 assert((Indexed || Offset.isUndef()) && "Unindexed store with an offset!");
9960 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
9961 : getVTList(MVT::Other);
9962 SDValue Ops[] = {Chain, Val, Ptr, Offset};
9965 ID.AddInteger(SVT.getRawBits());
9966 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
9967 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
9968 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9969 ID.AddInteger(MMO->getFlags());
9970 void *IP = nullptr;
9971 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9972 cast<StoreSDNode>(E)->refineAlignment(MMO);
9973 return SDValue(E, 0);
9974 }
9975 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
9976 IsTruncating, SVT, MMO);
9977 createOperands(N, Ops);
9978
9979 CSEMap.InsertNode(N, IP);
9980 InsertNode(N);
9981 SDValue V(N, 0);
9982 NewSDValueDbgMsg(V, "Creating new node: ", this);
9983 return V;
9984}
9985
9987 SDValue Ptr, MachinePointerInfo PtrInfo,
9988 EVT SVT, Align Alignment,
9989 MachineMemOperand::Flags MMOFlags,
9990 const AAMDNodes &AAInfo) {
9991 assert(Chain.getValueType() == MVT::Other &&
9992 "Invalid chain type");
9993
9994 MMOFlags |= MachineMemOperand::MOStore;
9995 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
9996
9997 if (PtrInfo.V.isNull())
9998 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
9999
10001 MachineMemOperand *MMO = MF.getMachineMemOperand(
10002 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
10003 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
10004}
10005
10007 SDValue Ptr, EVT SVT,
10008 MachineMemOperand *MMO) {
10009 SDValue Undef = getUNDEF(Ptr.getValueType());
10010 return getStore(Chain, dl, Val, Ptr, Undef, SVT, MMO, ISD::UNINDEXED, true);
10011}
10012
10016 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
10017 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
10018 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10019 ST->getMemoryVT(), ST->getMemOperand(), AM,
10020 ST->isTruncatingStore());
10021}
10022
10024 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
10025 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
10026 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
10027 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
10028 const MDNode *Ranges, bool IsExpanding) {
10029 MMOFlags |= MachineMemOperand::MOLoad;
10030 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10031 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10032 // clients.
10033 if (PtrInfo.V.isNull())
10034 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10035
10036 TypeSize Size = MemVT.getStoreSize();
10038 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
10039 Alignment, AAInfo, Ranges);
10040 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
10041 MMO, IsExpanding);
10042}
10043
10045 ISD::LoadExtType ExtType, EVT VT,
10046 const SDLoc &dl, SDValue Chain, SDValue Ptr,
10047 SDValue Offset, SDValue Mask, SDValue EVL,
10048 EVT MemVT, MachineMemOperand *MMO,
10049 bool IsExpanding) {
10050 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10051 assert(Mask.getValueType().getVectorElementCount() ==
10052 VT.getVectorElementCount() &&
10053 "Vector width mismatch between mask and data");
10054
10055 bool Indexed = AM != ISD::UNINDEXED;
10056 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
10057
10058 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
10059 : getVTList(VT, MVT::Other);
10060 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
10062 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
10063 ID.AddInteger(MemVT.getRawBits());
10064 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
10065 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
10066 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10067 ID.AddInteger(MMO->getFlags());
10068 void *IP = nullptr;
10069 if (auto *E = cast_or_null<VPLoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10070 E->refineAlignment(MMO);
10071 E->refineRanges(MMO);
10072 return SDValue(E, 0);
10073 }
10074 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10075 ExtType, IsExpanding, MemVT, MMO);
10076 createOperands(N, Ops);
10077
10078 CSEMap.InsertNode(N, IP);
10079 InsertNode(N);
10080 SDValue V(N, 0);
10081 NewSDValueDbgMsg(V, "Creating new node: ", this);
10082 return V;
10083}
10084
10086 SDValue Ptr, SDValue Mask, SDValue EVL,
10087 MachinePointerInfo PtrInfo,
10088 MaybeAlign Alignment,
10089 MachineMemOperand::Flags MMOFlags,
10090 const AAMDNodes &AAInfo, const MDNode *Ranges,
10091 bool IsExpanding) {
10092 SDValue Undef = getUNDEF(Ptr.getValueType());
10093 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10094 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
10095 IsExpanding);
10096}
10097
10099 SDValue Ptr, SDValue Mask, SDValue EVL,
10100 MachineMemOperand *MMO, bool IsExpanding) {
10101 SDValue Undef = getUNDEF(Ptr.getValueType());
10102 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10103 Mask, EVL, VT, MMO, IsExpanding);
10104}
10105
10107 EVT VT, SDValue Chain, SDValue Ptr,
10108 SDValue Mask, SDValue EVL,
10109 MachinePointerInfo PtrInfo, EVT MemVT,
10110 MaybeAlign Alignment,
10111 MachineMemOperand::Flags MMOFlags,
10112 const AAMDNodes &AAInfo, bool IsExpanding) {
10113 SDValue Undef = getUNDEF(Ptr.getValueType());
10114 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
10115 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
10116 IsExpanding);
10117}
10118
10120 EVT VT, SDValue Chain, SDValue Ptr,
10121 SDValue Mask, SDValue EVL, EVT MemVT,
10122 MachineMemOperand *MMO, bool IsExpanding) {
10123 SDValue Undef = getUNDEF(Ptr.getValueType());
10124 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
10125 EVL, MemVT, MMO, IsExpanding);
10126}
10127
10131 auto *LD = cast<VPLoadSDNode>(OrigLoad);
10132 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
10133 // Don't propagate the invariant or dereferenceable flags.
10134 auto MMOFlags =
10135 LD->getMemOperand()->getFlags() &
10137 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
10138 LD->getChain(), Base, Offset, LD->getMask(),
10139 LD->getVectorLength(), LD->getPointerInfo(),
10140 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
10141 nullptr, LD->isExpandingLoad());
10142}
10143
10145 SDValue Ptr, SDValue Offset, SDValue Mask,
10146 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
10147 ISD::MemIndexedMode AM, bool IsTruncating,
10148 bool IsCompressing) {
10149 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10150 assert(Mask.getValueType().getVectorElementCount() ==
10152 "Vector width mismatch between mask and data");
10153
10154 bool Indexed = AM != ISD::UNINDEXED;
10155 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
10156 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10157 : getVTList(MVT::Other);
10158 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
10160 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
10161 ID.AddInteger(MemVT.getRawBits());
10162 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
10163 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
10164 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10165 ID.AddInteger(MMO->getFlags());
10166 void *IP = nullptr;
10167 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10168 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
10169 return SDValue(E, 0);
10170 }
10171 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10172 IsTruncating, IsCompressing, MemVT, MMO);
10173 createOperands(N, Ops);
10174
10175 CSEMap.InsertNode(N, IP);
10176 InsertNode(N);
10177 SDValue V(N, 0);
10178 NewSDValueDbgMsg(V, "Creating new node: ", this);
10179 return V;
10180}
10181
10183 SDValue Val, SDValue Ptr, SDValue Mask,
10184 SDValue EVL, MachinePointerInfo PtrInfo,
10185 EVT SVT, Align Alignment,
10186 MachineMemOperand::Flags MMOFlags,
10187 const AAMDNodes &AAInfo,
10188 bool IsCompressing) {
10189 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10190
10191 MMOFlags |= MachineMemOperand::MOStore;
10192 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10193
10194 if (PtrInfo.V.isNull())
10195 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10196
10198 MachineMemOperand *MMO = MF.getMachineMemOperand(
10199 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
10200 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
10201 IsCompressing);
10202}
10203
10205 SDValue Val, SDValue Ptr, SDValue Mask,
10206 SDValue EVL, EVT SVT,
10207 MachineMemOperand *MMO,
10208 bool IsCompressing) {
10209 EVT VT = Val.getValueType();
10210
10211 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10212 if (VT == SVT)
10213 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
10214 EVL, VT, MMO, ISD::UNINDEXED,
10215 /*IsTruncating*/ false, IsCompressing);
10216
10218 "Should only be a truncating store, not extending!");
10219 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10220 assert(VT.isVector() == SVT.isVector() &&
10221 "Cannot use trunc store to convert to or from a vector!");
10222 assert((!VT.isVector() ||
10224 "Cannot use trunc store to change the number of vector elements!");
10225
10226 SDVTList VTs = getVTList(MVT::Other);
10227 SDValue Undef = getUNDEF(Ptr.getValueType());
10228 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
10230 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
10231 ID.AddInteger(SVT.getRawBits());
10232 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
10233 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
10234 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10235 ID.AddInteger(MMO->getFlags());
10236 void *IP = nullptr;
10237 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10238 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
10239 return SDValue(E, 0);
10240 }
10241 auto *N =
10242 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10243 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
10244 createOperands(N, Ops);
10245
10246 CSEMap.InsertNode(N, IP);
10247 InsertNode(N);
10248 SDValue V(N, 0);
10249 NewSDValueDbgMsg(V, "Creating new node: ", this);
10250 return V;
10251}
10252
10256 auto *ST = cast<VPStoreSDNode>(OrigStore);
10257 assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
10258 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
10259 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
10260 Offset, ST->getMask(), ST->getVectorLength()};
10262 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
10263 ID.AddInteger(ST->getMemoryVT().getRawBits());
10264 ID.AddInteger(ST->getRawSubclassData());
10265 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
10266 ID.AddInteger(ST->getMemOperand()->getFlags());
10267 void *IP = nullptr;
10268 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10269 return SDValue(E, 0);
10270
10271 auto *N = newSDNode<VPStoreSDNode>(
10272 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
10273 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
10274 createOperands(N, Ops);
10275
10276 CSEMap.InsertNode(N, IP);
10277 InsertNode(N);
10278 SDValue V(N, 0);
10279 NewSDValueDbgMsg(V, "Creating new node: ", this);
10280 return V;
10281}
10282
10284 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
10285 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
10286 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
10287 bool Indexed = AM != ISD::UNINDEXED;
10288 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
10289
10290 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
10291 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
10292 : getVTList(VT, MVT::Other);
10294 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
10295 ID.AddInteger(VT.getRawBits());
10296 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
10297 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
10298 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10299
10300 void *IP = nullptr;
10301 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10302 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
10303 return SDValue(E, 0);
10304 }
10305
10306 auto *N =
10307 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
10308 ExtType, IsExpanding, MemVT, MMO);
10309 createOperands(N, Ops);
10310 CSEMap.InsertNode(N, IP);
10311 InsertNode(N);
10312 SDValue V(N, 0);
10313 NewSDValueDbgMsg(V, "Creating new node: ", this);
10314 return V;
10315}
10316
10318 SDValue Ptr, SDValue Stride,
10319 SDValue Mask, SDValue EVL,
10320 MachineMemOperand *MMO,
10321 bool IsExpanding) {
10322 SDValue Undef = getUNDEF(Ptr.getValueType());
10323 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
10324 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
10325}
10326
10328 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
10329 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
10330 MachineMemOperand *MMO, bool IsExpanding) {
10331 SDValue Undef = getUNDEF(Ptr.getValueType());
10332 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
10333 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
10334}
10335
10337 SDValue Val, SDValue Ptr,
10338 SDValue Offset, SDValue Stride,
10339 SDValue Mask, SDValue EVL, EVT MemVT,
10340 MachineMemOperand *MMO,
10342 bool IsTruncating, bool IsCompressing) {
10343 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10344 bool Indexed = AM != ISD::UNINDEXED;
10345 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
10346 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10347 : getVTList(MVT::Other);
10348 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
10350 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
10351 ID.AddInteger(MemVT.getRawBits());
10352 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
10353 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
10354 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10355 void *IP = nullptr;
10356 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10357 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
10358 return SDValue(E, 0);
10359 }
10360 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
10361 VTs, AM, IsTruncating,
10362 IsCompressing, MemVT, MMO);
10363 createOperands(N, Ops);
10364
10365 CSEMap.InsertNode(N, IP);
10366 InsertNode(N);
10367 SDValue V(N, 0);
10368 NewSDValueDbgMsg(V, "Creating new node: ", this);
10369 return V;
10370}
10371
10373 SDValue Val, SDValue Ptr,
10374 SDValue Stride, SDValue Mask,
10375 SDValue EVL, EVT SVT,
10376 MachineMemOperand *MMO,
10377 bool IsCompressing) {
10378 EVT VT = Val.getValueType();
10379
10380 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10381 if (VT == SVT)
10382 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
10383 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
10384 /*IsTruncating*/ false, IsCompressing);
10385
10387 "Should only be a truncating store, not extending!");
10388 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10389 assert(VT.isVector() == SVT.isVector() &&
10390 "Cannot use trunc store to convert to or from a vector!");
10391 assert((!VT.isVector() ||
10393 "Cannot use trunc store to change the number of vector elements!");
10394
10395 SDVTList VTs = getVTList(MVT::Other);
10396 SDValue Undef = getUNDEF(Ptr.getValueType());
10397 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
10399 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
10400 ID.AddInteger(SVT.getRawBits());
10401 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
10402 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
10403 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10404 void *IP = nullptr;
10405 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10406 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
10407 return SDValue(E, 0);
10408 }
10409 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
10410 VTs, ISD::UNINDEXED, true,
10411 IsCompressing, SVT, MMO);
10412 createOperands(N, Ops);
10413
10414 CSEMap.InsertNode(N, IP);
10415 InsertNode(N);
10416 SDValue V(N, 0);
10417 NewSDValueDbgMsg(V, "Creating new node: ", this);
10418 return V;
10419}
10420
10423 ISD::MemIndexType IndexType) {
10424 assert(Ops.size() == 6 && "Incompatible number of operands");
10425
10427 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
10428 ID.AddInteger(VT.getRawBits());
10429 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
10430 dl.getIROrder(), VTs, VT, MMO, IndexType));
10431 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10432 ID.AddInteger(MMO->getFlags());
10433 void *IP = nullptr;
10434 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10435 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
10436 return SDValue(E, 0);
10437 }
10438
10439 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10440 VT, MMO, IndexType);
10441 createOperands(N, Ops);
10442
10443 assert(N->getMask().getValueType().getVectorElementCount() ==
10444 N->getValueType(0).getVectorElementCount() &&
10445 "Vector width mismatch between mask and data");
10446 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10447 N->getValueType(0).getVectorElementCount().isScalable() &&
10448 "Scalable flags of index and data do not match");
10450 N->getIndex().getValueType().getVectorElementCount(),
10451 N->getValueType(0).getVectorElementCount()) &&
10452 "Vector width mismatch between index and data");
10453 assert(isa<ConstantSDNode>(N->getScale()) &&
10454 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10455 "Scale should be a constant power of 2");
10456
10457 CSEMap.InsertNode(N, IP);
10458 InsertNode(N);
10459 SDValue V(N, 0);
10460 NewSDValueDbgMsg(V, "Creating new node: ", this);
10461 return V;
10462}
10463
10466 MachineMemOperand *MMO,
10467 ISD::MemIndexType IndexType) {
10468 assert(Ops.size() == 7 && "Incompatible number of operands");
10469
10471 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
10472 ID.AddInteger(VT.getRawBits());
10473 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
10474 dl.getIROrder(), VTs, VT, MMO, IndexType));
10475 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10476 ID.AddInteger(MMO->getFlags());
10477 void *IP = nullptr;
10478 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10479 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
10480 return SDValue(E, 0);
10481 }
10482 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10483 VT, MMO, IndexType);
10484 createOperands(N, Ops);
10485
10486 assert(N->getMask().getValueType().getVectorElementCount() ==
10487 N->getValue().getValueType().getVectorElementCount() &&
10488 "Vector width mismatch between mask and data");
10489 assert(
10490 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10491 N->getValue().getValueType().getVectorElementCount().isScalable() &&
10492 "Scalable flags of index and data do not match");
10494 N->getIndex().getValueType().getVectorElementCount(),
10495 N->getValue().getValueType().getVectorElementCount()) &&
10496 "Vector width mismatch between index and data");
10497 assert(isa<ConstantSDNode>(N->getScale()) &&
10498 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10499 "Scale should be a constant power of 2");
10500
10501 CSEMap.InsertNode(N, IP);
10502 InsertNode(N);
10503 SDValue V(N, 0);
10504 NewSDValueDbgMsg(V, "Creating new node: ", this);
10505 return V;
10506}
10507
10510 SDValue PassThru, EVT MemVT,
10511 MachineMemOperand *MMO,
10513 ISD::LoadExtType ExtTy, bool isExpanding) {
10514 bool Indexed = AM != ISD::UNINDEXED;
10515 assert((Indexed || Offset.isUndef()) &&
10516 "Unindexed masked load with an offset!");
10517 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
10518 : getVTList(VT, MVT::Other);
10519 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
10522 ID.AddInteger(MemVT.getRawBits());
10523 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
10524 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
10525 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10526 ID.AddInteger(MMO->getFlags());
10527 void *IP = nullptr;
10528 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10529 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
10530 return SDValue(E, 0);
10531 }
10532 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
10533 AM, ExtTy, isExpanding, MemVT, MMO);
10534 createOperands(N, Ops);
10535
10536 CSEMap.InsertNode(N, IP);
10537 InsertNode(N);
10538 SDValue V(N, 0);
10539 NewSDValueDbgMsg(V, "Creating new node: ", this);
10540 return V;
10541}
10542
10547 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
10548 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
10549 Offset, LD->getMask(), LD->getPassThru(),
10550 LD->getMemoryVT(), LD->getMemOperand(), AM,
10551 LD->getExtensionType(), LD->isExpandingLoad());
10552}
10553
10556 SDValue Mask, EVT MemVT,
10557 MachineMemOperand *MMO,
10558 ISD::MemIndexedMode AM, bool IsTruncating,
10559 bool IsCompressing) {
10560 assert(Chain.getValueType() == MVT::Other &&
10561 "Invalid chain type");
10562 bool Indexed = AM != ISD::UNINDEXED;
10563 assert((Indexed || Offset.isUndef()) &&
10564 "Unindexed masked store with an offset!");
10565 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
10566 : getVTList(MVT::Other);
10567 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
10570 ID.AddInteger(MemVT.getRawBits());
10571 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
10572 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
10573 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10574 ID.AddInteger(MMO->getFlags());
10575 void *IP = nullptr;
10576 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10577 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
10578 return SDValue(E, 0);
10579 }
10580 auto *N =
10581 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10582 IsTruncating, IsCompressing, MemVT, MMO);
10583 createOperands(N, Ops);
10584
10585 CSEMap.InsertNode(N, IP);
10586 InsertNode(N);
10587 SDValue V(N, 0);
10588 NewSDValueDbgMsg(V, "Creating new node: ", this);
10589 return V;
10590}
10591
10596 assert(ST->getOffset().isUndef() &&
10597 "Masked store is already a indexed store!");
10598 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10599 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
10600 AM, ST->isTruncatingStore(), ST->isCompressingStore());
10601}
10602
10605 MachineMemOperand *MMO,
10606 ISD::MemIndexType IndexType,
10607 ISD::LoadExtType ExtTy) {
10608 assert(Ops.size() == 6 && "Incompatible number of operands");
10609
10612 ID.AddInteger(MemVT.getRawBits());
10613 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
10614 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
10615 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10616 ID.AddInteger(MMO->getFlags());
10617 void *IP = nullptr;
10618 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10619 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
10620 return SDValue(E, 0);
10621 }
10622
10623 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
10624 VTs, MemVT, MMO, IndexType, ExtTy);
10625 createOperands(N, Ops);
10626
10627 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
10628 "Incompatible type of the PassThru value in MaskedGatherSDNode");
10629 assert(N->getMask().getValueType().getVectorElementCount() ==
10630 N->getValueType(0).getVectorElementCount() &&
10631 "Vector width mismatch between mask and data");
10632 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10633 N->getValueType(0).getVectorElementCount().isScalable() &&
10634 "Scalable flags of index and data do not match");
10636 N->getIndex().getValueType().getVectorElementCount(),
10637 N->getValueType(0).getVectorElementCount()) &&
10638 "Vector width mismatch between index and data");
10639 assert(isa<ConstantSDNode>(N->getScale()) &&
10640 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10641 "Scale should be a constant power of 2");
10642
10643 CSEMap.InsertNode(N, IP);
10644 InsertNode(N);
10645 SDValue V(N, 0);
10646 NewSDValueDbgMsg(V, "Creating new node: ", this);
10647 return V;
10648}
10649
10652 MachineMemOperand *MMO,
10653 ISD::MemIndexType IndexType,
10654 bool IsTrunc) {
10655 assert(Ops.size() == 6 && "Incompatible number of operands");
10656
10659 ID.AddInteger(MemVT.getRawBits());
10660 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
10661 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
10662 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10663 ID.AddInteger(MMO->getFlags());
10664 void *IP = nullptr;
10665 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10666 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
10667 return SDValue(E, 0);
10668 }
10669
10670 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
10671 VTs, MemVT, MMO, IndexType, IsTrunc);
10672 createOperands(N, Ops);
10673
10674 assert(N->getMask().getValueType().getVectorElementCount() ==
10675 N->getValue().getValueType().getVectorElementCount() &&
10676 "Vector width mismatch between mask and data");
10677 assert(
10678 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
10679 N->getValue().getValueType().getVectorElementCount().isScalable() &&
10680 "Scalable flags of index and data do not match");
10682 N->getIndex().getValueType().getVectorElementCount(),
10683 N->getValue().getValueType().getVectorElementCount()) &&
10684 "Vector width mismatch between index and data");
10685 assert(isa<ConstantSDNode>(N->getScale()) &&
10686 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10687 "Scale should be a constant power of 2");
10688
10689 CSEMap.InsertNode(N, IP);
10690 InsertNode(N);
10691 SDValue V(N, 0);
10692 NewSDValueDbgMsg(V, "Creating new node: ", this);
10693 return V;
10694}
10695
10697 const SDLoc &dl, ArrayRef<SDValue> Ops,
10698 MachineMemOperand *MMO,
10699 ISD::MemIndexType IndexType) {
10700 assert(Ops.size() == 7 && "Incompatible number of operands");
10701
10704 ID.AddInteger(MemVT.getRawBits());
10705 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
10706 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
10707 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10708 ID.AddInteger(MMO->getFlags());
10709 void *IP = nullptr;
10710 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10711 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
10712 return SDValue(E, 0);
10713 }
10714
10715 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
10716 VTs, MemVT, MMO, IndexType);
10717 createOperands(N, Ops);
10718
10719 assert(N->getMask().getValueType().getVectorElementCount() ==
10720 N->getIndex().getValueType().getVectorElementCount() &&
10721 "Vector width mismatch between mask and data");
10722 assert(isa<ConstantSDNode>(N->getScale()) &&
10723 N->getScale()->getAsAPIntVal().isPowerOf2() &&
10724 "Scale should be a constant power of 2");
10725 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
10726
10727 CSEMap.InsertNode(N, IP);
10728 InsertNode(N);
10729 SDValue V(N, 0);
10730 NewSDValueDbgMsg(V, "Creating new node: ", this);
10731 return V;
10732}
10733
10735 SDValue Ptr, SDValue Mask, SDValue EVL,
10736 MachineMemOperand *MMO) {
10737 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
10738 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
10740 AddNodeIDNode(ID, ISD::VP_LOAD_FF, VTs, Ops);
10741 ID.AddInteger(VT.getRawBits());
10742 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
10743 VTs, VT, MMO));
10744 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10745 ID.AddInteger(MMO->getFlags());
10746 void *IP = nullptr;
10747 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10748 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
10749 return SDValue(E, 0);
10750 }
10751 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
10752 VT, MMO);
10753 createOperands(N, Ops);
10754
10755 CSEMap.InsertNode(N, IP);
10756 InsertNode(N);
10757 SDValue V(N, 0);
10758 NewSDValueDbgMsg(V, "Creating new node: ", this);
10759 return V;
10760}
10761
10763 EVT MemVT, MachineMemOperand *MMO) {
10764 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10765 SDVTList VTs = getVTList(MVT::Other);
10766 SDValue Ops[] = {Chain, Ptr};
10769 ID.AddInteger(MemVT.getRawBits());
10770 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
10771 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
10772 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10773 ID.AddInteger(MMO->getFlags());
10774 void *IP = nullptr;
10775 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10776 return SDValue(E, 0);
10777
10778 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
10779 dl.getDebugLoc(), VTs, MemVT, MMO);
10780 createOperands(N, Ops);
10781
10782 CSEMap.InsertNode(N, IP);
10783 InsertNode(N);
10784 SDValue V(N, 0);
10785 NewSDValueDbgMsg(V, "Creating new node: ", this);
10786 return V;
10787}
10788
10790 EVT MemVT, MachineMemOperand *MMO) {
10791 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10792 SDVTList VTs = getVTList(MVT::Other);
10793 SDValue Ops[] = {Chain, Ptr};
10796 ID.AddInteger(MemVT.getRawBits());
10797 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
10798 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
10799 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10800 ID.AddInteger(MMO->getFlags());
10801 void *IP = nullptr;
10802 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10803 return SDValue(E, 0);
10804
10805 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
10806 dl.getDebugLoc(), VTs, MemVT, MMO);
10807 createOperands(N, Ops);
10808
10809 CSEMap.InsertNode(N, IP);
10810 InsertNode(N);
10811 SDValue V(N, 0);
10812 NewSDValueDbgMsg(V, "Creating new node: ", this);
10813 return V;
10814}
10815
10817 // select undef, T, F --> T (if T is a constant), otherwise F
10818 // select, ?, undef, F --> F
10819 // select, ?, T, undef --> T
10820 if (Cond.isUndef())
10821 return isConstantValueOfAnyType(T) ? T : F;
10822 if (T.isUndef())
10823 return F;
10824 if (F.isUndef())
10825 return T;
10826
10827 // select true, T, F --> T
10828 // select false, T, F --> F
10829 if (auto C = isBoolConstant(Cond))
10830 return *C ? T : F;
10831
10832 // select ?, T, T --> T
10833 if (T == F)
10834 return T;
10835
10836 return SDValue();
10837}
10838
10840 // shift undef, Y --> 0 (can always assume that the undef value is 0)
10841 if (X.isUndef())
10842 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
10843 // shift X, undef --> undef (because it may shift by the bitwidth)
10844 if (Y.isUndef())
10845 return getUNDEF(X.getValueType());
10846
10847 // shift 0, Y --> 0
10848 // shift X, 0 --> X
10850 return X;
10851
10852 // shift X, C >= bitwidth(X) --> undef
10853 // All vector elements must be too big (or undef) to avoid partial undefs.
10854 auto isShiftTooBig = [X](ConstantSDNode *Val) {
10855 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
10856 };
10857 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
10858 return getUNDEF(X.getValueType());
10859
10860 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
10861 if (X.getValueType().getScalarType() == MVT::i1)
10862 return X;
10863
10864 return SDValue();
10865}
10866
10868 SDNodeFlags Flags) {
10869 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
10870 // (an undef operand can be chosen to be Nan/Inf), then the result of this
10871 // operation is poison. That result can be relaxed to undef.
10872 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
10873 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
10874 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
10875 (YC && YC->getValueAPF().isNaN());
10876 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
10877 (YC && YC->getValueAPF().isInfinity());
10878
10879 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
10880 return getUNDEF(X.getValueType());
10881
10882 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
10883 return getUNDEF(X.getValueType());
10884
10885 if (!YC)
10886 return SDValue();
10887
10888 // X + -0.0 --> X
10889 if (Opcode == ISD::FADD)
10890 if (YC->getValueAPF().isNegZero())
10891 return X;
10892
10893 // X - +0.0 --> X
10894 if (Opcode == ISD::FSUB)
10895 if (YC->getValueAPF().isPosZero())
10896 return X;
10897
10898 // X * 1.0 --> X
10899 // X / 1.0 --> X
10900 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
10901 if (YC->getValueAPF().isExactlyValue(1.0))
10902 return X;
10903
10904 // X * 0.0 --> 0.0
10905 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
10906 if (YC->getValueAPF().isZero())
10907 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
10908
10909 return SDValue();
10910}
10911
10913 SDValue Ptr, SDValue SV, unsigned Align) {
10914 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
10915 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
10916}
10917
10918SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
10920 switch (Ops.size()) {
10921 case 0: return getNode(Opcode, DL, VT);
10922 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
10923 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
10924 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
10925 default: break;
10926 }
10927
10928 // Copy from an SDUse array into an SDValue array for use with
10929 // the regular getNode logic.
10931 return getNode(Opcode, DL, VT, NewOps);
10932}
10933
10934SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
10936 SDNodeFlags Flags;
10937 if (Inserter)
10938 Flags = Inserter->getFlags();
10939 return getNode(Opcode, DL, VT, Ops, Flags);
10940}
10941
10942SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
10943 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
10944 unsigned NumOps = Ops.size();
10945 switch (NumOps) {
10946 case 0: return getNode(Opcode, DL, VT);
10947 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
10948 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
10949 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
10950 default: break;
10951 }
10952
10953#ifndef NDEBUG
10954 for (const auto &Op : Ops)
10955 assert(Op.getOpcode() != ISD::DELETED_NODE &&
10956 "Operand is DELETED_NODE!");
10957#endif
10958
10959 switch (Opcode) {
10960 default: break;
10961 case ISD::BUILD_VECTOR:
10962 // Attempt to simplify BUILD_VECTOR.
10963 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
10964 return V;
10965 break;
10967 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
10968 return V;
10969 break;
10970 case ISD::SELECT_CC:
10971 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
10972 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
10973 "LHS and RHS of condition must have same type!");
10974 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
10975 "True and False arms of SelectCC must have same type!");
10976 assert(Ops[2].getValueType() == VT &&
10977 "select_cc node must be of same type as true and false value!");
10978 assert((!Ops[0].getValueType().isVector() ||
10979 Ops[0].getValueType().getVectorElementCount() ==
10980 VT.getVectorElementCount()) &&
10981 "Expected select_cc with vector result to have the same sized "
10982 "comparison type!");
10983 break;
10984 case ISD::BR_CC:
10985 assert(NumOps == 5 && "BR_CC takes 5 operands!");
10986 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
10987 "LHS/RHS of comparison should match types!");
10988 break;
10989 case ISD::VP_ADD:
10990 case ISD::VP_SUB:
10991 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
10992 if (VT.getScalarType() == MVT::i1)
10993 Opcode = ISD::VP_XOR;
10994 break;
10995 case ISD::VP_MUL:
10996 // If it is VP_MUL mask operation then turn it to VP_AND
10997 if (VT.getScalarType() == MVT::i1)
10998 Opcode = ISD::VP_AND;
10999 break;
11000 case ISD::VP_REDUCE_MUL:
11001 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
11002 if (VT == MVT::i1)
11003 Opcode = ISD::VP_REDUCE_AND;
11004 break;
11005 case ISD::VP_REDUCE_ADD:
11006 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
11007 if (VT == MVT::i1)
11008 Opcode = ISD::VP_REDUCE_XOR;
11009 break;
11010 case ISD::VP_REDUCE_SMAX:
11011 case ISD::VP_REDUCE_UMIN:
11012 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
11013 // VP_REDUCE_AND.
11014 if (VT == MVT::i1)
11015 Opcode = ISD::VP_REDUCE_AND;
11016 break;
11017 case ISD::VP_REDUCE_SMIN:
11018 case ISD::VP_REDUCE_UMAX:
11019 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
11020 // VP_REDUCE_OR.
11021 if (VT == MVT::i1)
11022 Opcode = ISD::VP_REDUCE_OR;
11023 break;
11024 }
11025
11026 // Memoize nodes.
11027 SDNode *N;
11028 SDVTList VTs = getVTList(VT);
11029
11030 if (VT != MVT::Glue) {
11032 AddNodeIDNode(ID, Opcode, VTs, Ops);
11033 void *IP = nullptr;
11034
11035 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11036 E->intersectFlagsWith(Flags);
11037 return SDValue(E, 0);
11038 }
11039
11040 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11041 createOperands(N, Ops);
11042
11043 CSEMap.InsertNode(N, IP);
11044 } else {
11045 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11046 createOperands(N, Ops);
11047 }
11048
11049 N->setFlags(Flags);
11050 InsertNode(N);
11051 SDValue V(N, 0);
11052 NewSDValueDbgMsg(V, "Creating new node: ", this);
11053 return V;
11054}
11055
11056SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11057 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
11058 SDNodeFlags Flags;
11059 if (Inserter)
11060 Flags = Inserter->getFlags();
11061 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11062}
11063
11064SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11066 const SDNodeFlags Flags) {
11067 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
11068}
11069
11070SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11072 SDNodeFlags Flags;
11073 if (Inserter)
11074 Flags = Inserter->getFlags();
11075 return getNode(Opcode, DL, VTList, Ops, Flags);
11076}
11077
11078SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11079 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11080 if (VTList.NumVTs == 1)
11081 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
11082
11083#ifndef NDEBUG
11084 for (const auto &Op : Ops)
11085 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11086 "Operand is DELETED_NODE!");
11087#endif
11088
11089 switch (Opcode) {
11090 case ISD::SADDO:
11091 case ISD::UADDO:
11092 case ISD::SSUBO:
11093 case ISD::USUBO: {
11094 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
11095 "Invalid add/sub overflow op!");
11096 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
11097 Ops[0].getValueType() == Ops[1].getValueType() &&
11098 Ops[0].getValueType() == VTList.VTs[0] &&
11099 "Binary operator types must match!");
11100 SDValue N1 = Ops[0], N2 = Ops[1];
11101 canonicalizeCommutativeBinop(Opcode, N1, N2);
11102
11103 // (X +- 0) -> X with zero-overflow.
11104 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
11105 /*AllowTruncation*/ true);
11106 if (N2CV && N2CV->isZero()) {
11107 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
11108 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
11109 }
11110
11111 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
11112 VTList.VTs[1].getScalarType() == MVT::i1) {
11113 SDValue F1 = getFreeze(N1);
11114 SDValue F2 = getFreeze(N2);
11115 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
11116 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
11117 return getNode(ISD::MERGE_VALUES, DL, VTList,
11118 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
11119 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
11120 Flags);
11121 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
11122 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
11123 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
11124 return getNode(ISD::MERGE_VALUES, DL, VTList,
11125 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
11126 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
11127 Flags);
11128 }
11129 }
11130 break;
11131 }
11132 case ISD::SADDO_CARRY:
11133 case ISD::UADDO_CARRY:
11134 case ISD::SSUBO_CARRY:
11135 case ISD::USUBO_CARRY:
11136 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
11137 "Invalid add/sub overflow op!");
11138 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
11139 Ops[0].getValueType() == Ops[1].getValueType() &&
11140 Ops[0].getValueType() == VTList.VTs[0] &&
11141 Ops[2].getValueType() == VTList.VTs[1] &&
11142 "Binary operator types must match!");
11143 break;
11144 case ISD::SMUL_LOHI:
11145 case ISD::UMUL_LOHI: {
11146 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
11147 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
11148 VTList.VTs[0] == Ops[0].getValueType() &&
11149 VTList.VTs[0] == Ops[1].getValueType() &&
11150 "Binary operator types must match!");
11151 // Constant fold.
11154 if (LHS && RHS) {
11155 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
11156 unsigned OutWidth = Width * 2;
11157 APInt Val = LHS->getAPIntValue();
11158 APInt Mul = RHS->getAPIntValue();
11159 if (Opcode == ISD::SMUL_LOHI) {
11160 Val = Val.sext(OutWidth);
11161 Mul = Mul.sext(OutWidth);
11162 } else {
11163 Val = Val.zext(OutWidth);
11164 Mul = Mul.zext(OutWidth);
11165 }
11166 Val *= Mul;
11167
11168 SDValue Hi =
11169 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
11170 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
11171 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
11172 }
11173 break;
11174 }
11175 case ISD::FFREXP: {
11176 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
11177 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
11178 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
11179
11181 int FrexpExp;
11182 APFloat FrexpMant =
11183 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
11184 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
11185 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
11186 DL, VTList.VTs[1]);
11187 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
11188 }
11189
11190 break;
11191 }
11193 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
11194 "Invalid STRICT_FP_EXTEND!");
11195 assert(VTList.VTs[0].isFloatingPoint() &&
11196 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
11197 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
11198 "STRICT_FP_EXTEND result type should be vector iff the operand "
11199 "type is vector!");
11200 assert((!VTList.VTs[0].isVector() ||
11201 VTList.VTs[0].getVectorElementCount() ==
11202 Ops[1].getValueType().getVectorElementCount()) &&
11203 "Vector element count mismatch!");
11204 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
11205 "Invalid fpext node, dst <= src!");
11206 break;
11208 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
11209 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
11210 "STRICT_FP_ROUND result type should be vector iff the operand "
11211 "type is vector!");
11212 assert((!VTList.VTs[0].isVector() ||
11213 VTList.VTs[0].getVectorElementCount() ==
11214 Ops[1].getValueType().getVectorElementCount()) &&
11215 "Vector element count mismatch!");
11216 assert(VTList.VTs[0].isFloatingPoint() &&
11217 Ops[1].getValueType().isFloatingPoint() &&
11218 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
11219 Ops[2].getOpcode() == ISD::TargetConstant &&
11220 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
11221 "Invalid STRICT_FP_ROUND!");
11222 break;
11223 }
11224
11225 // Memoize the node unless it returns a glue result.
11226 SDNode *N;
11227 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
11229 AddNodeIDNode(ID, Opcode, VTList, Ops);
11230 void *IP = nullptr;
11231 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11232 E->intersectFlagsWith(Flags);
11233 return SDValue(E, 0);
11234 }
11235
11236 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
11237 createOperands(N, Ops);
11238 CSEMap.InsertNode(N, IP);
11239 } else {
11240 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
11241 createOperands(N, Ops);
11242 }
11243
11244 N->setFlags(Flags);
11245 InsertNode(N);
11246 SDValue V(N, 0);
11247 NewSDValueDbgMsg(V, "Creating new node: ", this);
11248 return V;
11249}
11250
11251SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11252 SDVTList VTList) {
11253 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
11254}
11255
11256SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11257 SDValue N1) {
11258 SDValue Ops[] = { N1 };
11259 return getNode(Opcode, DL, VTList, Ops);
11260}
11261
11262SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11263 SDValue N1, SDValue N2) {
11264 SDValue Ops[] = { N1, N2 };
11265 return getNode(Opcode, DL, VTList, Ops);
11266}
11267
11268SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11269 SDValue N1, SDValue N2, SDValue N3) {
11270 SDValue Ops[] = { N1, N2, N3 };
11271 return getNode(Opcode, DL, VTList, Ops);
11272}
11273
11274SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11275 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
11276 SDValue Ops[] = { N1, N2, N3, N4 };
11277 return getNode(Opcode, DL, VTList, Ops);
11278}
11279
11280SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
11281 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
11282 SDValue N5) {
11283 SDValue Ops[] = { N1, N2, N3, N4, N5 };
11284 return getNode(Opcode, DL, VTList, Ops);
11285}
11286
11288 if (!VT.isExtended())
11289 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
11290
11291 return makeVTList(&(*EVTs.insert(VT).first), 1);
11292}
11293
11296 ID.AddInteger(2U);
11297 ID.AddInteger(VT1.getRawBits());
11298 ID.AddInteger(VT2.getRawBits());
11299
11300 void *IP = nullptr;
11301 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11302 if (!Result) {
11303 EVT *Array = Allocator.Allocate<EVT>(2);
11304 Array[0] = VT1;
11305 Array[1] = VT2;
11306 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
11307 VTListMap.InsertNode(Result, IP);
11308 }
11309 return Result->getSDVTList();
11310}
11311
11314 ID.AddInteger(3U);
11315 ID.AddInteger(VT1.getRawBits());
11316 ID.AddInteger(VT2.getRawBits());
11317 ID.AddInteger(VT3.getRawBits());
11318
11319 void *IP = nullptr;
11320 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11321 if (!Result) {
11322 EVT *Array = Allocator.Allocate<EVT>(3);
11323 Array[0] = VT1;
11324 Array[1] = VT2;
11325 Array[2] = VT3;
11326 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
11327 VTListMap.InsertNode(Result, IP);
11328 }
11329 return Result->getSDVTList();
11330}
11331
11334 ID.AddInteger(4U);
11335 ID.AddInteger(VT1.getRawBits());
11336 ID.AddInteger(VT2.getRawBits());
11337 ID.AddInteger(VT3.getRawBits());
11338 ID.AddInteger(VT4.getRawBits());
11339
11340 void *IP = nullptr;
11341 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11342 if (!Result) {
11343 EVT *Array = Allocator.Allocate<EVT>(4);
11344 Array[0] = VT1;
11345 Array[1] = VT2;
11346 Array[2] = VT3;
11347 Array[3] = VT4;
11348 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
11349 VTListMap.InsertNode(Result, IP);
11350 }
11351 return Result->getSDVTList();
11352}
11353
11355 unsigned NumVTs = VTs.size();
11357 ID.AddInteger(NumVTs);
11358 for (unsigned index = 0; index < NumVTs; index++) {
11359 ID.AddInteger(VTs[index].getRawBits());
11360 }
11361
11362 void *IP = nullptr;
11363 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
11364 if (!Result) {
11365 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
11366 llvm::copy(VTs, Array);
11367 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
11368 VTListMap.InsertNode(Result, IP);
11369 }
11370 return Result->getSDVTList();
11371}
11372
11373
11374/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
11375/// specified operands. If the resultant node already exists in the DAG,
11376/// this does not modify the specified node, instead it returns the node that
11377/// already exists. If the resultant node does not exist in the DAG, the
11378/// input node is returned. As a degenerate case, if you specify the same
11379/// input operands as the node already has, the input node is returned.
11381 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
11382
11383 // Check to see if there is no change.
11384 if (Op == N->getOperand(0)) return N;
11385
11386 // See if the modified node already exists.
11387 void *InsertPos = nullptr;
11388 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
11389 return Existing;
11390
11391 // Nope it doesn't. Remove the node from its current place in the maps.
11392 if (InsertPos)
11393 if (!RemoveNodeFromCSEMaps(N))
11394 InsertPos = nullptr;
11395
11396 // Now we update the operands.
11397 N->OperandList[0].set(Op);
11398
11400 // If this gets put into a CSE map, add it.
11401 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
11402 return N;
11403}
11404
11406 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
11407
11408 // Check to see if there is no change.
11409 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
11410 return N; // No operands changed, just return the input node.
11411
11412 // See if the modified node already exists.
11413 void *InsertPos = nullptr;
11414 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
11415 return Existing;
11416
11417 // Nope it doesn't. Remove the node from its current place in the maps.
11418 if (InsertPos)
11419 if (!RemoveNodeFromCSEMaps(N))
11420 InsertPos = nullptr;
11421
11422 // Now we update the operands.
11423 if (N->OperandList[0] != Op1)
11424 N->OperandList[0].set(Op1);
11425 if (N->OperandList[1] != Op2)
11426 N->OperandList[1].set(Op2);
11427
11429 // If this gets put into a CSE map, add it.
11430 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
11431 return N;
11432}
11433
11436 SDValue Ops[] = { Op1, Op2, Op3 };
11437 return UpdateNodeOperands(N, Ops);
11438}
11439
11442 SDValue Op3, SDValue Op4) {
11443 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
11444 return UpdateNodeOperands(N, Ops);
11445}
11446
11449 SDValue Op3, SDValue Op4, SDValue Op5) {
11450 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
11451 return UpdateNodeOperands(N, Ops);
11452}
11453
11456 unsigned NumOps = Ops.size();
11457 assert(N->getNumOperands() == NumOps &&
11458 "Update with wrong number of operands");
11459
11460 // If no operands changed just return the input node.
11461 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
11462 return N;
11463
11464 // See if the modified node already exists.
11465 void *InsertPos = nullptr;
11466 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
11467 return Existing;
11468
11469 // Nope it doesn't. Remove the node from its current place in the maps.
11470 if (InsertPos)
11471 if (!RemoveNodeFromCSEMaps(N))
11472 InsertPos = nullptr;
11473
11474 // Now we update the operands.
11475 for (unsigned i = 0; i != NumOps; ++i)
11476 if (N->OperandList[i] != Ops[i])
11477 N->OperandList[i].set(Ops[i]);
11478
11480 // If this gets put into a CSE map, add it.
11481 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
11482 return N;
11483}
11484
11485/// DropOperands - Release the operands and set this node to have
11486/// zero operands.
11488 // Unlike the code in MorphNodeTo that does this, we don't need to
11489 // watch for dead nodes here.
11490 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
11491 SDUse &Use = *I++;
11492 Use.set(SDValue());
11493 }
11494}
11495
11497 ArrayRef<MachineMemOperand *> NewMemRefs) {
11498 if (NewMemRefs.empty()) {
11499 N->clearMemRefs();
11500 return;
11501 }
11502
11503 // Check if we can avoid allocating by storing a single reference directly.
11504 if (NewMemRefs.size() == 1) {
11505 N->MemRefs = NewMemRefs[0];
11506 N->NumMemRefs = 1;
11507 return;
11508 }
11509
11510 MachineMemOperand **MemRefsBuffer =
11511 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
11512 llvm::copy(NewMemRefs, MemRefsBuffer);
11513 N->MemRefs = MemRefsBuffer;
11514 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
11515}
11516
11517/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
11518/// machine opcode.
11519///
11521 EVT VT) {
11522 SDVTList VTs = getVTList(VT);
11523 return SelectNodeTo(N, MachineOpc, VTs, {});
11524}
11525
11527 EVT VT, SDValue Op1) {
11528 SDVTList VTs = getVTList(VT);
11529 SDValue Ops[] = { Op1 };
11530 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11531}
11532
11534 EVT VT, SDValue Op1,
11535 SDValue Op2) {
11536 SDVTList VTs = getVTList(VT);
11537 SDValue Ops[] = { Op1, Op2 };
11538 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11539}
11540
11542 EVT VT, SDValue Op1,
11543 SDValue Op2, SDValue Op3) {
11544 SDVTList VTs = getVTList(VT);
11545 SDValue Ops[] = { Op1, Op2, Op3 };
11546 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11547}
11548
11551 SDVTList VTs = getVTList(VT);
11552 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11553}
11554
11556 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
11557 SDVTList VTs = getVTList(VT1, VT2);
11558 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11559}
11560
11562 EVT VT1, EVT VT2) {
11563 SDVTList VTs = getVTList(VT1, VT2);
11564 return SelectNodeTo(N, MachineOpc, VTs, {});
11565}
11566
11568 EVT VT1, EVT VT2, EVT VT3,
11570 SDVTList VTs = getVTList(VT1, VT2, VT3);
11571 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11572}
11573
11575 EVT VT1, EVT VT2,
11576 SDValue Op1, SDValue Op2) {
11577 SDVTList VTs = getVTList(VT1, VT2);
11578 SDValue Ops[] = { Op1, Op2 };
11579 return SelectNodeTo(N, MachineOpc, VTs, Ops);
11580}
11581
11584 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
11585 // Reset the NodeID to -1.
11586 New->setNodeId(-1);
11587 if (New != N) {
11588 ReplaceAllUsesWith(N, New);
11590 }
11591 return New;
11592}
11593
11594/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
11595/// the line number information on the merged node since it is not possible to
11596/// preserve the information that operation is associated with multiple lines.
11597/// This will make the debugger working better at -O0, were there is a higher
11598/// probability having other instructions associated with that line.
11599///
11600/// For IROrder, we keep the smaller of the two
11601SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
11602 DebugLoc NLoc = N->getDebugLoc();
11603 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
11604 N->setDebugLoc(DebugLoc());
11605 }
11606 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
11607 N->setIROrder(Order);
11608 return N;
11609}
11610
11611/// MorphNodeTo - This *mutates* the specified node to have the specified
11612/// return type, opcode, and operands.
11613///
11614/// Note that MorphNodeTo returns the resultant node. If there is already a
11615/// node of the specified opcode and operands, it returns that node instead of
11616/// the current one. Note that the SDLoc need not be the same.
11617///
11618/// Using MorphNodeTo is faster than creating a new node and swapping it in
11619/// with ReplaceAllUsesWith both because it often avoids allocating a new
11620/// node, and because it doesn't require CSE recalculation for any of
11621/// the node's users.
11622///
11623/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
11624/// As a consequence it isn't appropriate to use from within the DAG combiner or
11625/// the legalizer which maintain worklists that would need to be updated when
11626/// deleting things.
11629 // If an identical node already exists, use it.
11630 void *IP = nullptr;
11631 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
11633 AddNodeIDNode(ID, Opc, VTs, Ops);
11634 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
11635 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
11636 }
11637
11638 if (!RemoveNodeFromCSEMaps(N))
11639 IP = nullptr;
11640
11641 // Start the morphing.
11642 N->NodeType = Opc;
11643 N->ValueList = VTs.VTs;
11644 N->NumValues = VTs.NumVTs;
11645
11646 // Clear the operands list, updating used nodes to remove this from their
11647 // use list. Keep track of any operands that become dead as a result.
11648 SmallPtrSet<SDNode*, 16> DeadNodeSet;
11649 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
11650 SDUse &Use = *I++;
11651 SDNode *Used = Use.getNode();
11652 Use.set(SDValue());
11653 if (Used->use_empty())
11654 DeadNodeSet.insert(Used);
11655 }
11656
11657 // For MachineNode, initialize the memory references information.
11659 MN->clearMemRefs();
11660
11661 // Swap for an appropriately sized array from the recycler.
11662 removeOperands(N);
11663 createOperands(N, Ops);
11664
11665 // Delete any nodes that are still dead after adding the uses for the
11666 // new operands.
11667 if (!DeadNodeSet.empty()) {
11668 SmallVector<SDNode *, 16> DeadNodes;
11669 for (SDNode *N : DeadNodeSet)
11670 if (N->use_empty())
11671 DeadNodes.push_back(N);
11672 RemoveDeadNodes(DeadNodes);
11673 }
11674
11675 if (IP)
11676 CSEMap.InsertNode(N, IP); // Memoize the new node.
11677 return N;
11678}
11679
11681 unsigned OrigOpc = Node->getOpcode();
11682 unsigned NewOpc;
11683 switch (OrigOpc) {
11684 default:
11685 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
11686#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
11687 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
11688#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
11689 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
11690#include "llvm/IR/ConstrainedOps.def"
11691 }
11692
11693 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
11694
11695 // We're taking this node out of the chain, so we need to re-link things.
11696 SDValue InputChain = Node->getOperand(0);
11697 SDValue OutputChain = SDValue(Node, 1);
11698 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
11699
11701 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
11702 Ops.push_back(Node->getOperand(i));
11703
11704 SDVTList VTs = getVTList(Node->getValueType(0));
11705 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
11706
11707 // MorphNodeTo can operate in two ways: if an existing node with the
11708 // specified operands exists, it can just return it. Otherwise, it
11709 // updates the node in place to have the requested operands.
11710 if (Res == Node) {
11711 // If we updated the node in place, reset the node ID. To the isel,
11712 // this should be just like a newly allocated machine node.
11713 Res->setNodeId(-1);
11714 } else {
11717 }
11718
11719 return Res;
11720}
11721
11722/// getMachineNode - These are used for target selectors to create a new node
11723/// with specified return type(s), MachineInstr opcode, and operands.
11724///
11725/// Note that getMachineNode returns the resultant node. If there is already a
11726/// node of the specified opcode and operands, it returns that node instead of
11727/// the current one.
11729 EVT VT) {
11730 SDVTList VTs = getVTList(VT);
11731 return getMachineNode(Opcode, dl, VTs, {});
11732}
11733
11735 EVT VT, SDValue Op1) {
11736 SDVTList VTs = getVTList(VT);
11737 SDValue Ops[] = { Op1 };
11738 return getMachineNode(Opcode, dl, VTs, Ops);
11739}
11740
11742 EVT VT, SDValue Op1, SDValue Op2) {
11743 SDVTList VTs = getVTList(VT);
11744 SDValue Ops[] = { Op1, Op2 };
11745 return getMachineNode(Opcode, dl, VTs, Ops);
11746}
11747
11749 EVT VT, SDValue Op1, SDValue Op2,
11750 SDValue Op3) {
11751 SDVTList VTs = getVTList(VT);
11752 SDValue Ops[] = { Op1, Op2, Op3 };
11753 return getMachineNode(Opcode, dl, VTs, Ops);
11754}
11755
11758 SDVTList VTs = getVTList(VT);
11759 return getMachineNode(Opcode, dl, VTs, Ops);
11760}
11761
11763 EVT VT1, EVT VT2, SDValue Op1,
11764 SDValue Op2) {
11765 SDVTList VTs = getVTList(VT1, VT2);
11766 SDValue Ops[] = { Op1, Op2 };
11767 return getMachineNode(Opcode, dl, VTs, Ops);
11768}
11769
11771 EVT VT1, EVT VT2, SDValue Op1,
11772 SDValue Op2, SDValue Op3) {
11773 SDVTList VTs = getVTList(VT1, VT2);
11774 SDValue Ops[] = { Op1, Op2, Op3 };
11775 return getMachineNode(Opcode, dl, VTs, Ops);
11776}
11777
11779 EVT VT1, EVT VT2,
11781 SDVTList VTs = getVTList(VT1, VT2);
11782 return getMachineNode(Opcode, dl, VTs, Ops);
11783}
11784
11786 EVT VT1, EVT VT2, EVT VT3,
11787 SDValue Op1, SDValue Op2) {
11788 SDVTList VTs = getVTList(VT1, VT2, VT3);
11789 SDValue Ops[] = { Op1, Op2 };
11790 return getMachineNode(Opcode, dl, VTs, Ops);
11791}
11792
11794 EVT VT1, EVT VT2, EVT VT3,
11795 SDValue Op1, SDValue Op2,
11796 SDValue Op3) {
11797 SDVTList VTs = getVTList(VT1, VT2, VT3);
11798 SDValue Ops[] = { Op1, Op2, Op3 };
11799 return getMachineNode(Opcode, dl, VTs, Ops);
11800}
11801
11803 EVT VT1, EVT VT2, EVT VT3,
11805 SDVTList VTs = getVTList(VT1, VT2, VT3);
11806 return getMachineNode(Opcode, dl, VTs, Ops);
11807}
11808
11810 ArrayRef<EVT> ResultTys,
11812 SDVTList VTs = getVTList(ResultTys);
11813 return getMachineNode(Opcode, dl, VTs, Ops);
11814}
11815
11817 SDVTList VTs,
11819 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
11821 void *IP = nullptr;
11822
11823 if (DoCSE) {
11825 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
11826 IP = nullptr;
11827 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11828 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
11829 }
11830 }
11831
11832 // Allocate a new MachineSDNode.
11833 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11834 createOperands(N, Ops);
11835
11836 if (DoCSE)
11837 CSEMap.InsertNode(N, IP);
11838
11839 InsertNode(N);
11840 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
11841 return N;
11842}
11843
11844/// getTargetExtractSubreg - A convenience function for creating
11845/// TargetOpcode::EXTRACT_SUBREG nodes.
11847 SDValue Operand) {
11848 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
11849 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
11850 VT, Operand, SRIdxVal);
11851 return SDValue(Subreg, 0);
11852}
11853
11854/// getTargetInsertSubreg - A convenience function for creating
11855/// TargetOpcode::INSERT_SUBREG nodes.
11857 SDValue Operand, SDValue Subreg) {
11858 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
11859 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
11860 VT, Operand, Subreg, SRIdxVal);
11861 return SDValue(Result, 0);
11862}
11863
11864/// getNodeIfExists - Get the specified node if it's already available, or
11865/// else return NULL.
11868 bool AllowCommute) {
11869 SDNodeFlags Flags;
11870 if (Inserter)
11871 Flags = Inserter->getFlags();
11872 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
11873}
11874
11877 const SDNodeFlags Flags,
11878 bool AllowCommute) {
11879 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
11880 return nullptr;
11881
11882 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
11884 AddNodeIDNode(ID, Opcode, VTList, LookupOps);
11885 void *IP = nullptr;
11886 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) {
11887 E->intersectFlagsWith(Flags);
11888 return E;
11889 }
11890 return nullptr;
11891 };
11892
11893 if (SDNode *Existing = Lookup(Ops))
11894 return Existing;
11895
11896 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
11897 return Lookup({Ops[1], Ops[0]});
11898
11899 return nullptr;
11900}
11901
11902/// doesNodeExist - Check if a node exists without modifying its flags.
11903bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
11905 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
11907 AddNodeIDNode(ID, Opcode, VTList, Ops);
11908 void *IP = nullptr;
11909 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
11910 return true;
11911 }
11912 return false;
11913}
11914
11915/// getDbgValue - Creates a SDDbgValue node.
11916///
11917/// SDNode
11919 SDNode *N, unsigned R, bool IsIndirect,
11920 const DebugLoc &DL, unsigned O) {
11921 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11922 "Expected inlined-at fields to agree");
11923 return new (DbgInfo->getAlloc())
11924 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
11925 {}, IsIndirect, DL, O,
11926 /*IsVariadic=*/false);
11927}
11928
11929/// Constant
11931 DIExpression *Expr,
11932 const Value *C,
11933 const DebugLoc &DL, unsigned O) {
11934 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11935 "Expected inlined-at fields to agree");
11936 return new (DbgInfo->getAlloc())
11937 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
11938 /*IsIndirect=*/false, DL, O,
11939 /*IsVariadic=*/false);
11940}
11941
11942/// FrameIndex
11944 DIExpression *Expr, unsigned FI,
11945 bool IsIndirect,
11946 const DebugLoc &DL,
11947 unsigned O) {
11948 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11949 "Expected inlined-at fields to agree");
11950 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
11951}
11952
11953/// FrameIndex with dependencies
11955 DIExpression *Expr, unsigned FI,
11956 ArrayRef<SDNode *> Dependencies,
11957 bool IsIndirect,
11958 const DebugLoc &DL,
11959 unsigned O) {
11960 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11961 "Expected inlined-at fields to agree");
11962 return new (DbgInfo->getAlloc())
11963 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
11964 Dependencies, IsIndirect, DL, O,
11965 /*IsVariadic=*/false);
11966}
11967
11968/// VReg
11970 Register VReg, bool IsIndirect,
11971 const DebugLoc &DL, unsigned O) {
11972 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11973 "Expected inlined-at fields to agree");
11974 return new (DbgInfo->getAlloc())
11975 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
11976 {}, IsIndirect, DL, O,
11977 /*IsVariadic=*/false);
11978}
11979
11982 ArrayRef<SDNode *> Dependencies,
11983 bool IsIndirect, const DebugLoc &DL,
11984 unsigned O, bool IsVariadic) {
11985 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
11986 "Expected inlined-at fields to agree");
11987 return new (DbgInfo->getAlloc())
11988 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
11989 DL, O, IsVariadic);
11990}
11991
11993 unsigned OffsetInBits, unsigned SizeInBits,
11994 bool InvalidateDbg) {
11995 SDNode *FromNode = From.getNode();
11996 SDNode *ToNode = To.getNode();
11997 assert(FromNode && ToNode && "Can't modify dbg values");
11998
11999 // PR35338
12000 // TODO: assert(From != To && "Redundant dbg value transfer");
12001 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
12002 if (From == To || FromNode == ToNode)
12003 return;
12004
12005 if (!FromNode->getHasDebugValue())
12006 return;
12007
12008 SDDbgOperand FromLocOp =
12009 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
12011
12013 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
12014 if (Dbg->isInvalidated())
12015 continue;
12016
12017 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
12018
12019 // Create a new location ops vector that is equal to the old vector, but
12020 // with each instance of FromLocOp replaced with ToLocOp.
12021 bool Changed = false;
12022 auto NewLocOps = Dbg->copyLocationOps();
12023 std::replace_if(
12024 NewLocOps.begin(), NewLocOps.end(),
12025 [&Changed, FromLocOp](const SDDbgOperand &Op) {
12026 bool Match = Op == FromLocOp;
12027 Changed |= Match;
12028 return Match;
12029 },
12030 ToLocOp);
12031 // Ignore this SDDbgValue if we didn't find a matching location.
12032 if (!Changed)
12033 continue;
12034
12035 DIVariable *Var = Dbg->getVariable();
12036 auto *Expr = Dbg->getExpression();
12037 // If a fragment is requested, update the expression.
12038 if (SizeInBits) {
12039 // When splitting a larger (e.g., sign-extended) value whose
12040 // lower bits are described with an SDDbgValue, do not attempt
12041 // to transfer the SDDbgValue to the upper bits.
12042 if (auto FI = Expr->getFragmentInfo())
12043 if (OffsetInBits + SizeInBits > FI->SizeInBits)
12044 continue;
12045 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
12046 SizeInBits);
12047 if (!Fragment)
12048 continue;
12049 Expr = *Fragment;
12050 }
12051
12052 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
12053 // Clone the SDDbgValue and move it to To.
12054 SDDbgValue *Clone = getDbgValueList(
12055 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
12056 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
12057 Dbg->isVariadic());
12058 ClonedDVs.push_back(Clone);
12059
12060 if (InvalidateDbg) {
12061 // Invalidate value and indicate the SDDbgValue should not be emitted.
12062 Dbg->setIsInvalidated();
12063 Dbg->setIsEmitted();
12064 }
12065 }
12066
12067 for (SDDbgValue *Dbg : ClonedDVs) {
12068 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
12069 "Transferred DbgValues should depend on the new SDNode");
12070 AddDbgValue(Dbg, false);
12071 }
12072}
12073
12075 if (!N.getHasDebugValue())
12076 return;
12077
12078 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
12079 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
12080 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
12081 return SDDbgOperand::fromNode(Node, ResNo);
12082 };
12083
12085 for (auto *DV : GetDbgValues(&N)) {
12086 if (DV->isInvalidated())
12087 continue;
12088 switch (N.getOpcode()) {
12089 default:
12090 break;
12091 case ISD::ADD: {
12092 SDValue N0 = N.getOperand(0);
12093 SDValue N1 = N.getOperand(1);
12094 if (!isa<ConstantSDNode>(N0)) {
12095 bool RHSConstant = isa<ConstantSDNode>(N1);
12097 if (RHSConstant)
12098 Offset = N.getConstantOperandVal(1);
12099 // We are not allowed to turn indirect debug values variadic, so
12100 // don't salvage those.
12101 if (!RHSConstant && DV->isIndirect())
12102 continue;
12103
12104 // Rewrite an ADD constant node into a DIExpression. Since we are
12105 // performing arithmetic to compute the variable's *value* in the
12106 // DIExpression, we need to mark the expression with a
12107 // DW_OP_stack_value.
12108 auto *DIExpr = DV->getExpression();
12109 auto NewLocOps = DV->copyLocationOps();
12110 bool Changed = false;
12111 size_t OrigLocOpsSize = NewLocOps.size();
12112 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
12113 // We're not given a ResNo to compare against because the whole
12114 // node is going away. We know that any ISD::ADD only has one
12115 // result, so we can assume any node match is using the result.
12116 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
12117 NewLocOps[i].getSDNode() != &N)
12118 continue;
12119 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
12120 if (RHSConstant) {
12123 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
12124 } else {
12125 // Convert to a variadic expression (if not already).
12126 // convertToVariadicExpression() returns a const pointer, so we use
12127 // a temporary const variable here.
12128 const auto *TmpDIExpr =
12132 ExprOps.push_back(NewLocOps.size());
12133 ExprOps.push_back(dwarf::DW_OP_plus);
12134 SDDbgOperand RHS =
12136 NewLocOps.push_back(RHS);
12137 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
12138 }
12139 Changed = true;
12140 }
12141 (void)Changed;
12142 assert(Changed && "Salvage target doesn't use N");
12143
12144 bool IsVariadic =
12145 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
12146
12147 auto AdditionalDependencies = DV->getAdditionalDependencies();
12148 SDDbgValue *Clone = getDbgValueList(
12149 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
12150 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
12151 ClonedDVs.push_back(Clone);
12152 DV->setIsInvalidated();
12153 DV->setIsEmitted();
12154 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
12155 N0.getNode()->dumprFull(this);
12156 dbgs() << " into " << *DIExpr << '\n');
12157 }
12158 break;
12159 }
12160 case ISD::TRUNCATE: {
12161 SDValue N0 = N.getOperand(0);
12162 TypeSize FromSize = N0.getValueSizeInBits();
12163 TypeSize ToSize = N.getValueSizeInBits(0);
12164
12165 DIExpression *DbgExpression = DV->getExpression();
12166 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
12167 auto NewLocOps = DV->copyLocationOps();
12168 bool Changed = false;
12169 for (size_t i = 0; i < NewLocOps.size(); ++i) {
12170 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
12171 NewLocOps[i].getSDNode() != &N)
12172 continue;
12173
12174 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
12175 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
12176 Changed = true;
12177 }
12178 assert(Changed && "Salvage target doesn't use N");
12179 (void)Changed;
12180
12181 SDDbgValue *Clone =
12182 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
12183 DV->getAdditionalDependencies(), DV->isIndirect(),
12184 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
12185
12186 ClonedDVs.push_back(Clone);
12187 DV->setIsInvalidated();
12188 DV->setIsEmitted();
12189 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
12190 dbgs() << " into " << *DbgExpression << '\n');
12191 break;
12192 }
12193 }
12194 }
12195
12196 for (SDDbgValue *Dbg : ClonedDVs) {
12197 assert((!Dbg->getSDNodes().empty() ||
12198 llvm::any_of(Dbg->getLocationOps(),
12199 [&](const SDDbgOperand &Op) {
12200 return Op.getKind() == SDDbgOperand::FRAMEIX;
12201 })) &&
12202 "Salvaged DbgValue should depend on a new SDNode");
12203 AddDbgValue(Dbg, false);
12204 }
12205}
12206
12207/// Creates a SDDbgLabel node.
12209 const DebugLoc &DL, unsigned O) {
12210 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
12211 "Expected inlined-at fields to agree");
12212 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
12213}
12214
12215namespace {
12216
12217/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
12218/// pointed to by a use iterator is deleted, increment the use iterator
12219/// so that it doesn't dangle.
12220///
12221class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
12224
12225 void NodeDeleted(SDNode *N, SDNode *E) override {
12226 // Increment the iterator as needed.
12227 while (UI != UE && N == UI->getUser())
12228 ++UI;
12229 }
12230
12231public:
12232 RAUWUpdateListener(SelectionDAG &d,
12235 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
12236};
12237
12238} // end anonymous namespace
12239
12240/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
12241/// This can cause recursive merging of nodes in the DAG.
12242///
12243/// This version assumes From has a single result value.
12244///
12246 SDNode *From = FromN.getNode();
12247 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
12248 "Cannot replace with this method!");
12249 assert(From != To.getNode() && "Cannot replace uses of with self");
12250
12251 // Preserve Debug Values
12252 transferDbgValues(FromN, To);
12253 // Preserve extra info.
12254 copyExtraInfo(From, To.getNode());
12255
12256 // Iterate over all the existing uses of From. New uses will be added
12257 // to the beginning of the use list, which we avoid visiting.
12258 // This specifically avoids visiting uses of From that arise while the
12259 // replacement is happening, because any such uses would be the result
12260 // of CSE: If an existing node looks like From after one of its operands
12261 // is replaced by To, we don't want to replace of all its users with To
12262 // too. See PR3018 for more info.
12263 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
12264 RAUWUpdateListener Listener(*this, UI, UE);
12265 while (UI != UE) {
12266 SDNode *User = UI->getUser();
12267
12268 // This node is about to morph, remove its old self from the CSE maps.
12269 RemoveNodeFromCSEMaps(User);
12270
12271 // A user can appear in a use list multiple times, and when this
12272 // happens the uses are usually next to each other in the list.
12273 // To help reduce the number of CSE recomputations, process all
12274 // the uses of this user that we can find this way.
12275 do {
12276 SDUse &Use = *UI;
12277 ++UI;
12278 Use.set(To);
12279 if (To->isDivergent() != From->isDivergent())
12281 } while (UI != UE && UI->getUser() == User);
12282 // Now that we have modified User, add it back to the CSE maps. If it
12283 // already exists there, recursively merge the results together.
12284 AddModifiedNodeToCSEMaps(User);
12285 }
12286
12287 // If we just RAUW'd the root, take note.
12288 if (FromN == getRoot())
12289 setRoot(To);
12290}
12291
12292/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
12293/// This can cause recursive merging of nodes in the DAG.
12294///
12295/// This version assumes that for each value of From, there is a
12296/// corresponding value in To in the same position with the same type.
12297///
12299#ifndef NDEBUG
12300 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
12301 assert((!From->hasAnyUseOfValue(i) ||
12302 From->getValueType(i) == To->getValueType(i)) &&
12303 "Cannot use this version of ReplaceAllUsesWith!");
12304#endif
12305
12306 // Handle the trivial case.
12307 if (From == To)
12308 return;
12309
12310 // Preserve Debug Info. Only do this if there's a use.
12311 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
12312 if (From->hasAnyUseOfValue(i)) {
12313 assert((i < To->getNumValues()) && "Invalid To location");
12314 transferDbgValues(SDValue(From, i), SDValue(To, i));
12315 }
12316 // Preserve extra info.
12317 copyExtraInfo(From, To);
12318
12319 // Iterate over just the existing users of From. See the comments in
12320 // the ReplaceAllUsesWith above.
12321 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
12322 RAUWUpdateListener Listener(*this, UI, UE);
12323 while (UI != UE) {
12324 SDNode *User = UI->getUser();
12325
12326 // This node is about to morph, remove its old self from the CSE maps.
12327 RemoveNodeFromCSEMaps(User);
12328
12329 // A user can appear in a use list multiple times, and when this
12330 // happens the uses are usually next to each other in the list.
12331 // To help reduce the number of CSE recomputations, process all
12332 // the uses of this user that we can find this way.
12333 do {
12334 SDUse &Use = *UI;
12335 ++UI;
12336 Use.setNode(To);
12337 if (To->isDivergent() != From->isDivergent())
12339 } while (UI != UE && UI->getUser() == User);
12340
12341 // Now that we have modified User, add it back to the CSE maps. If it
12342 // already exists there, recursively merge the results together.
12343 AddModifiedNodeToCSEMaps(User);
12344 }
12345
12346 // If we just RAUW'd the root, take note.
12347 if (From == getRoot().getNode())
12348 setRoot(SDValue(To, getRoot().getResNo()));
12349}
12350
12351/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
12352/// This can cause recursive merging of nodes in the DAG.
12353///
12354/// This version can replace From with any result values. To must match the
12355/// number and types of values returned by From.
12357 if (From->getNumValues() == 1) // Handle the simple case efficiently.
12358 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
12359
12360 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
12361 // Preserve Debug Info.
12362 transferDbgValues(SDValue(From, i), To[i]);
12363 // Preserve extra info.
12364 copyExtraInfo(From, To[i].getNode());
12365 }
12366
12367 // Iterate over just the existing users of From. See the comments in
12368 // the ReplaceAllUsesWith above.
12369 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
12370 RAUWUpdateListener Listener(*this, UI, UE);
12371 while (UI != UE) {
12372 SDNode *User = UI->getUser();
12373
12374 // This node is about to morph, remove its old self from the CSE maps.
12375 RemoveNodeFromCSEMaps(User);
12376
12377 // A user can appear in a use list multiple times, and when this happens the
12378 // uses are usually next to each other in the list. To help reduce the
12379 // number of CSE and divergence recomputations, process all the uses of this
12380 // user that we can find this way.
12381 bool To_IsDivergent = false;
12382 do {
12383 SDUse &Use = *UI;
12384 const SDValue &ToOp = To[Use.getResNo()];
12385 ++UI;
12386 Use.set(ToOp);
12387 if (ToOp.getValueType() != MVT::Other)
12388 To_IsDivergent |= ToOp->isDivergent();
12389 } while (UI != UE && UI->getUser() == User);
12390
12391 if (To_IsDivergent != From->isDivergent())
12393
12394 // Now that we have modified User, add it back to the CSE maps. If it
12395 // already exists there, recursively merge the results together.
12396 AddModifiedNodeToCSEMaps(User);
12397 }
12398
12399 // If we just RAUW'd the root, take note.
12400 if (From == getRoot().getNode())
12401 setRoot(SDValue(To[getRoot().getResNo()]));
12402}
12403
12404/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
12405/// uses of other values produced by From.getNode() alone. The Deleted
12406/// vector is handled the same way as for ReplaceAllUsesWith.
12408 // Handle the really simple, really trivial case efficiently.
12409 if (From == To) return;
12410
12411 // Handle the simple, trivial, case efficiently.
12412 if (From.getNode()->getNumValues() == 1) {
12413 ReplaceAllUsesWith(From, To);
12414 return;
12415 }
12416
12417 // Preserve Debug Info.
12418 transferDbgValues(From, To);
12419 copyExtraInfo(From.getNode(), To.getNode());
12420
12421 // Iterate over just the existing users of From. See the comments in
12422 // the ReplaceAllUsesWith above.
12423 SDNode::use_iterator UI = From.getNode()->use_begin(),
12424 UE = From.getNode()->use_end();
12425 RAUWUpdateListener Listener(*this, UI, UE);
12426 while (UI != UE) {
12427 SDNode *User = UI->getUser();
12428 bool UserRemovedFromCSEMaps = false;
12429
12430 // A user can appear in a use list multiple times, and when this
12431 // happens the uses are usually next to each other in the list.
12432 // To help reduce the number of CSE recomputations, process all
12433 // the uses of this user that we can find this way.
12434 do {
12435 SDUse &Use = *UI;
12436
12437 // Skip uses of different values from the same node.
12438 if (Use.getResNo() != From.getResNo()) {
12439 ++UI;
12440 continue;
12441 }
12442
12443 // If this node hasn't been modified yet, it's still in the CSE maps,
12444 // so remove its old self from the CSE maps.
12445 if (!UserRemovedFromCSEMaps) {
12446 RemoveNodeFromCSEMaps(User);
12447 UserRemovedFromCSEMaps = true;
12448 }
12449
12450 ++UI;
12451 Use.set(To);
12452 if (To->isDivergent() != From->isDivergent())
12454 } while (UI != UE && UI->getUser() == User);
12455 // We are iterating over all uses of the From node, so if a use
12456 // doesn't use the specific value, no changes are made.
12457 if (!UserRemovedFromCSEMaps)
12458 continue;
12459
12460 // Now that we have modified User, add it back to the CSE maps. If it
12461 // already exists there, recursively merge the results together.
12462 AddModifiedNodeToCSEMaps(User);
12463 }
12464
12465 // If we just RAUW'd the root, take note.
12466 if (From == getRoot())
12467 setRoot(To);
12468}
12469
12470namespace {
12471
12472/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
12473/// to record information about a use.
12474struct UseMemo {
12475 SDNode *User;
12476 unsigned Index;
12477 SDUse *Use;
12478};
12479
12480/// operator< - Sort Memos by User.
12481bool operator<(const UseMemo &L, const UseMemo &R) {
12482 return (intptr_t)L.User < (intptr_t)R.User;
12483}
12484
12485/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
12486/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
12487/// the node already has been taken care of recursively.
12488class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
12489 SmallVectorImpl<UseMemo> &Uses;
12490
12491 void NodeDeleted(SDNode *N, SDNode *E) override {
12492 for (UseMemo &Memo : Uses)
12493 if (Memo.User == N)
12494 Memo.User = nullptr;
12495 }
12496
12497public:
12498 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
12499 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
12500};
12501
12502} // end anonymous namespace
12503
12504/// Return true if a glue output should propagate divergence information.
12506 switch (Node->getOpcode()) {
12507 case ISD::CopyFromReg:
12508 case ISD::CopyToReg:
12509 return false;
12510 default:
12511 return true;
12512 }
12513
12514 llvm_unreachable("covered opcode switch");
12515}
12516
12518 if (TLI->isSDNodeAlwaysUniform(N)) {
12519 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
12520 "Conflicting divergence information!");
12521 return false;
12522 }
12523 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
12524 return true;
12525 for (const auto &Op : N->ops()) {
12526 EVT VT = Op.getValueType();
12527
12528 // Skip Chain. It does not carry divergence.
12529 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
12530 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
12531 return true;
12532 }
12533 return false;
12534}
12535
12537 SmallVector<SDNode *, 16> Worklist(1, N);
12538 do {
12539 N = Worklist.pop_back_val();
12540 bool IsDivergent = calculateDivergence(N);
12541 if (N->SDNodeBits.IsDivergent != IsDivergent) {
12542 N->SDNodeBits.IsDivergent = IsDivergent;
12543 llvm::append_range(Worklist, N->users());
12544 }
12545 } while (!Worklist.empty());
12546}
12547
12548void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
12550 Order.reserve(AllNodes.size());
12551 for (auto &N : allnodes()) {
12552 unsigned NOps = N.getNumOperands();
12553 Degree[&N] = NOps;
12554 if (0 == NOps)
12555 Order.push_back(&N);
12556 }
12557 for (size_t I = 0; I != Order.size(); ++I) {
12558 SDNode *N = Order[I];
12559 for (auto *U : N->users()) {
12560 unsigned &UnsortedOps = Degree[U];
12561 if (0 == --UnsortedOps)
12562 Order.push_back(U);
12563 }
12564 }
12565}
12566
12567#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
12568void SelectionDAG::VerifyDAGDivergence() {
12569 std::vector<SDNode *> TopoOrder;
12570 CreateTopologicalOrder(TopoOrder);
12571 for (auto *N : TopoOrder) {
12572 assert(calculateDivergence(N) == N->isDivergent() &&
12573 "Divergence bit inconsistency detected");
12574 }
12575}
12576#endif
12577
12578/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
12579/// uses of other values produced by From.getNode() alone. The same value
12580/// may appear in both the From and To list. The Deleted vector is
12581/// handled the same way as for ReplaceAllUsesWith.
12583 const SDValue *To,
12584 unsigned Num){
12585 // Handle the simple, trivial case efficiently.
12586 if (Num == 1)
12587 return ReplaceAllUsesOfValueWith(*From, *To);
12588
12589 transferDbgValues(*From, *To);
12590 copyExtraInfo(From->getNode(), To->getNode());
12591
12592 // Read up all the uses and make records of them. This helps
12593 // processing new uses that are introduced during the
12594 // replacement process.
12596 for (unsigned i = 0; i != Num; ++i) {
12597 unsigned FromResNo = From[i].getResNo();
12598 SDNode *FromNode = From[i].getNode();
12599 for (SDUse &Use : FromNode->uses()) {
12600 if (Use.getResNo() == FromResNo) {
12601 UseMemo Memo = {Use.getUser(), i, &Use};
12602 Uses.push_back(Memo);
12603 }
12604 }
12605 }
12606
12607 // Sort the uses, so that all the uses from a given User are together.
12609 RAUOVWUpdateListener Listener(*this, Uses);
12610
12611 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
12612 UseIndex != UseIndexEnd; ) {
12613 // We know that this user uses some value of From. If it is the right
12614 // value, update it.
12615 SDNode *User = Uses[UseIndex].User;
12616 // If the node has been deleted by recursive CSE updates when updating
12617 // another node, then just skip this entry.
12618 if (User == nullptr) {
12619 ++UseIndex;
12620 continue;
12621 }
12622
12623 // This node is about to morph, remove its old self from the CSE maps.
12624 RemoveNodeFromCSEMaps(User);
12625
12626 // The Uses array is sorted, so all the uses for a given User
12627 // are next to each other in the list.
12628 // To help reduce the number of CSE recomputations, process all
12629 // the uses of this user that we can find this way.
12630 do {
12631 unsigned i = Uses[UseIndex].Index;
12632 SDUse &Use = *Uses[UseIndex].Use;
12633 ++UseIndex;
12634
12635 Use.set(To[i]);
12636 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
12637
12638 // Now that we have modified User, add it back to the CSE maps. If it
12639 // already exists there, recursively merge the results together.
12640 AddModifiedNodeToCSEMaps(User);
12641 }
12642}
12643
12644/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
12645/// based on their topological order. It returns the maximum id and a vector
12646/// of the SDNodes* in assigned order by reference.
12648 unsigned DAGSize = 0;
12649
12650 // SortedPos tracks the progress of the algorithm. Nodes before it are
12651 // sorted, nodes after it are unsorted. When the algorithm completes
12652 // it is at the end of the list.
12653 allnodes_iterator SortedPos = allnodes_begin();
12654
12655 // Visit all the nodes. Move nodes with no operands to the front of
12656 // the list immediately. Annotate nodes that do have operands with their
12657 // operand count. Before we do this, the Node Id fields of the nodes
12658 // may contain arbitrary values. After, the Node Id fields for nodes
12659 // before SortedPos will contain the topological sort index, and the
12660 // Node Id fields for nodes At SortedPos and after will contain the
12661 // count of outstanding operands.
12663 checkForCycles(&N, this);
12664 unsigned Degree = N.getNumOperands();
12665 if (Degree == 0) {
12666 // A node with no uses, add it to the result array immediately.
12667 N.setNodeId(DAGSize++);
12668 allnodes_iterator Q(&N);
12669 if (Q != SortedPos)
12670 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
12671 assert(SortedPos != AllNodes.end() && "Overran node list");
12672 ++SortedPos;
12673 } else {
12674 // Temporarily use the Node Id as scratch space for the degree count.
12675 N.setNodeId(Degree);
12676 }
12677 }
12678
12679 // Visit all the nodes. As we iterate, move nodes into sorted order,
12680 // such that by the time the end is reached all nodes will be sorted.
12681 for (SDNode &Node : allnodes()) {
12682 SDNode *N = &Node;
12683 checkForCycles(N, this);
12684 // N is in sorted position, so all its uses have one less operand
12685 // that needs to be sorted.
12686 for (SDNode *P : N->users()) {
12687 unsigned Degree = P->getNodeId();
12688 assert(Degree != 0 && "Invalid node degree");
12689 --Degree;
12690 if (Degree == 0) {
12691 // All of P's operands are sorted, so P may sorted now.
12692 P->setNodeId(DAGSize++);
12693 if (P->getIterator() != SortedPos)
12694 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
12695 assert(SortedPos != AllNodes.end() && "Overran node list");
12696 ++SortedPos;
12697 } else {
12698 // Update P's outstanding operand count.
12699 P->setNodeId(Degree);
12700 }
12701 }
12702 if (Node.getIterator() == SortedPos) {
12703#ifndef NDEBUG
12705 SDNode *S = &*++I;
12706 dbgs() << "Overran sorted position:\n";
12707 S->dumprFull(this); dbgs() << "\n";
12708 dbgs() << "Checking if this is due to cycles\n";
12709 checkForCycles(this, true);
12710#endif
12711 llvm_unreachable(nullptr);
12712 }
12713 }
12714
12715 assert(SortedPos == AllNodes.end() &&
12716 "Topological sort incomplete!");
12717 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
12718 "First node in topological sort is not the entry token!");
12719 assert(AllNodes.front().getNodeId() == 0 &&
12720 "First node in topological sort has non-zero id!");
12721 assert(AllNodes.front().getNumOperands() == 0 &&
12722 "First node in topological sort has operands!");
12723 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
12724 "Last node in topologic sort has unexpected id!");
12725 assert(AllNodes.back().use_empty() &&
12726 "Last node in topologic sort has users!");
12727 assert(DAGSize == allnodes_size() && "Node count mismatch!");
12728 return DAGSize;
12729}
12730
12732 SmallVectorImpl<const SDNode *> &SortedNodes) const {
12733 SortedNodes.clear();
12734 // Node -> remaining number of outstanding operands.
12735 DenseMap<const SDNode *, unsigned> RemainingOperands;
12736
12737 // Put nodes without any operands into SortedNodes first.
12738 for (const SDNode &N : allnodes()) {
12739 checkForCycles(&N, this);
12740 unsigned NumOperands = N.getNumOperands();
12741 if (NumOperands == 0)
12742 SortedNodes.push_back(&N);
12743 else
12744 // Record their total number of outstanding operands.
12745 RemainingOperands[&N] = NumOperands;
12746 }
12747
12748 // A node is pushed into SortedNodes when all of its operands (predecessors in
12749 // the graph) are also in SortedNodes.
12750 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
12751 const SDNode *N = SortedNodes[i];
12752 for (const SDNode *U : N->users()) {
12753 // HandleSDNode is never part of a DAG and therefore has no entry in
12754 // RemainingOperands.
12755 if (U->getOpcode() == ISD::HANDLENODE)
12756 continue;
12757 unsigned &NumRemOperands = RemainingOperands[U];
12758 assert(NumRemOperands && "Invalid number of remaining operands");
12759 --NumRemOperands;
12760 if (!NumRemOperands)
12761 SortedNodes.push_back(U);
12762 }
12763 }
12764
12765 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
12766 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
12767 "First node in topological sort is not the entry token");
12768 assert(SortedNodes.front()->getNumOperands() == 0 &&
12769 "First node in topological sort has operands");
12770}
12771
12772/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
12773/// value is produced by SD.
12774void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
12775 for (SDNode *SD : DB->getSDNodes()) {
12776 if (!SD)
12777 continue;
12778 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
12779 SD->setHasDebugValue(true);
12780 }
12781 DbgInfo->add(DB, isParameter);
12782}
12783
12784void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
12785
12787 SDValue NewMemOpChain) {
12788 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
12789 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
12790 // The new memory operation must have the same position as the old load in
12791 // terms of memory dependency. Create a TokenFactor for the old load and new
12792 // memory operation and update uses of the old load's output chain to use that
12793 // TokenFactor.
12794 if (OldChain == NewMemOpChain || OldChain.use_empty())
12795 return NewMemOpChain;
12796
12797 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
12798 OldChain, NewMemOpChain);
12799 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
12800 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
12801 return TokenFactor;
12802}
12803
12805 SDValue NewMemOp) {
12806 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
12807 SDValue OldChain = SDValue(OldLoad, 1);
12808 SDValue NewMemOpChain = NewMemOp.getValue(1);
12809 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
12810}
12811
12813 Function **OutFunction) {
12814 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
12815
12816 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12817 auto *Module = MF->getFunction().getParent();
12818 auto *Function = Module->getFunction(Symbol);
12819
12820 if (OutFunction != nullptr)
12821 *OutFunction = Function;
12822
12823 if (Function != nullptr) {
12824 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
12825 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
12826 }
12827
12828 std::string ErrorStr;
12829 raw_string_ostream ErrorFormatter(ErrorStr);
12830 ErrorFormatter << "Undefined external symbol ";
12831 ErrorFormatter << '"' << Symbol << '"';
12832 report_fatal_error(Twine(ErrorStr));
12833}
12834
12835//===----------------------------------------------------------------------===//
12836// SDNode Class
12837//===----------------------------------------------------------------------===//
12838
12841 return Const != nullptr && Const->isZero();
12842}
12843
12845 return V.isUndef() || isNullConstant(V);
12846}
12847
12850 return Const != nullptr && Const->isZero() && !Const->isNegative();
12851}
12852
12855 return Const != nullptr && Const->isAllOnes();
12856}
12857
12860 return Const != nullptr && Const->isOne();
12861}
12862
12865 return Const != nullptr && Const->isMinSignedValue();
12866}
12867
12868bool llvm::isNeutralConstant(unsigned Opcode, SDNodeFlags Flags, SDValue V,
12869 unsigned OperandNo) {
12870 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
12871 // TODO: Target-specific opcodes could be added.
12872 if (auto *ConstV = isConstOrConstSplat(V, /*AllowUndefs*/ false,
12873 /*AllowTruncation*/ true)) {
12874 APInt Const = ConstV->getAPIntValue().trunc(V.getScalarValueSizeInBits());
12875 switch (Opcode) {
12876 case ISD::ADD:
12877 case ISD::OR:
12878 case ISD::XOR:
12879 case ISD::UMAX:
12880 return Const.isZero();
12881 case ISD::MUL:
12882 return Const.isOne();
12883 case ISD::AND:
12884 case ISD::UMIN:
12885 return Const.isAllOnes();
12886 case ISD::SMAX:
12887 return Const.isMinSignedValue();
12888 case ISD::SMIN:
12889 return Const.isMaxSignedValue();
12890 case ISD::SUB:
12891 case ISD::SHL:
12892 case ISD::SRA:
12893 case ISD::SRL:
12894 return OperandNo == 1 && Const.isZero();
12895 case ISD::UDIV:
12896 case ISD::SDIV:
12897 return OperandNo == 1 && Const.isOne();
12898 }
12899 } else if (auto *ConstFP = isConstOrConstSplatFP(V)) {
12900 switch (Opcode) {
12901 case ISD::FADD:
12902 return ConstFP->isZero() &&
12903 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
12904 case ISD::FSUB:
12905 return OperandNo == 1 && ConstFP->isZero() &&
12906 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
12907 case ISD::FMUL:
12908 return ConstFP->isExactlyValue(1.0);
12909 case ISD::FDIV:
12910 return OperandNo == 1 && ConstFP->isExactlyValue(1.0);
12911 case ISD::FMINNUM:
12912 case ISD::FMAXNUM: {
12913 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
12914 EVT VT = V.getValueType();
12915 const fltSemantics &Semantics = VT.getFltSemantics();
12916 APFloat NeutralAF = !Flags.hasNoNaNs()
12917 ? APFloat::getQNaN(Semantics)
12918 : !Flags.hasNoInfs()
12919 ? APFloat::getInf(Semantics)
12920 : APFloat::getLargest(Semantics);
12921 if (Opcode == ISD::FMAXNUM)
12922 NeutralAF.changeSign();
12923
12924 return ConstFP->isExactlyValue(NeutralAF);
12925 }
12926 }
12927 }
12928 return false;
12929}
12930
12932 while (V.getOpcode() == ISD::BITCAST)
12933 V = V.getOperand(0);
12934 return V;
12935}
12936
12938 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
12939 V = V.getOperand(0);
12940 return V;
12941}
12942
12944 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12945 V = V.getOperand(0);
12946 return V;
12947}
12948
12950 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12951 SDValue InVec = V.getOperand(0);
12952 SDValue EltNo = V.getOperand(2);
12953 EVT VT = InVec.getValueType();
12954 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
12955 if (IndexC && VT.isFixedLengthVector() &&
12956 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
12957 !DemandedElts[IndexC->getZExtValue()]) {
12958 V = InVec;
12959 continue;
12960 }
12961 break;
12962 }
12963 return V;
12964}
12965
12967 while (V.getOpcode() == ISD::TRUNCATE)
12968 V = V.getOperand(0);
12969 return V;
12970}
12971
12972bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
12973 if (V.getOpcode() != ISD::XOR)
12974 return false;
12975 V = peekThroughBitcasts(V.getOperand(1));
12976 unsigned NumBits = V.getScalarValueSizeInBits();
12977 ConstantSDNode *C =
12978 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
12979 return C && (C->getAPIntValue().countr_one() >= NumBits);
12980}
12981
12983 bool AllowTruncation) {
12984 EVT VT = N.getValueType();
12985 APInt DemandedElts = VT.isFixedLengthVector()
12987 : APInt(1, 1);
12988 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
12989}
12990
12992 bool AllowUndefs,
12993 bool AllowTruncation) {
12995 return CN;
12996
12997 // SplatVectors can truncate their operands. Ignore that case here unless
12998 // AllowTruncation is set.
12999 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
13000 EVT VecEltVT = N->getValueType(0).getVectorElementType();
13001 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13002 EVT CVT = CN->getValueType(0);
13003 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
13004 if (AllowTruncation || CVT == VecEltVT)
13005 return CN;
13006 }
13007 }
13008
13010 BitVector UndefElements;
13011 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
13012
13013 // BuildVectors can truncate their operands. Ignore that case here unless
13014 // AllowTruncation is set.
13015 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13016 if (CN && (UndefElements.none() || AllowUndefs)) {
13017 EVT CVT = CN->getValueType(0);
13018 EVT NSVT = N.getValueType().getScalarType();
13019 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
13020 if (AllowTruncation || (CVT == NSVT))
13021 return CN;
13022 }
13023 }
13024
13025 return nullptr;
13026}
13027
13029 EVT VT = N.getValueType();
13030 APInt DemandedElts = VT.isFixedLengthVector()
13032 : APInt(1, 1);
13033 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
13034}
13035
13037 const APInt &DemandedElts,
13038 bool AllowUndefs) {
13040 return CN;
13041
13043 BitVector UndefElements;
13044 ConstantFPSDNode *CN =
13045 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
13046 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13047 if (CN && (UndefElements.none() || AllowUndefs))
13048 return CN;
13049 }
13050
13051 if (N.getOpcode() == ISD::SPLAT_VECTOR)
13052 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
13053 return CN;
13054
13055 return nullptr;
13056}
13057
13058bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
13059 // TODO: may want to use peekThroughBitcast() here.
13060 ConstantSDNode *C =
13061 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13062 return C && C->isZero();
13063}
13064
13065bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
13066 ConstantSDNode *C =
13067 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
13068 return C && C->isOne();
13069}
13070
13071bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
13072 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13073 return C && C->isExactlyValue(1.0);
13074}
13075
13076bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
13078 unsigned BitWidth = N.getScalarValueSizeInBits();
13079 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
13080 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
13081}
13082
13083bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
13084 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
13085 return C && APInt::isSameValue(C->getAPIntValue(),
13086 APInt(C->getAPIntValue().getBitWidth(), 1));
13087}
13088
13089bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
13091 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
13092 return C && C->isZero();
13093}
13094
13095bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
13096 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13097 return C && C->isZero();
13098}
13099
13103
13104MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
13105 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
13106 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
13107 MemSDNodeBits.IsVolatile = MMO->isVolatile();
13108 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
13109 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
13110 MemSDNodeBits.IsInvariant = MMO->isInvariant();
13111
13112 // We check here that the size of the memory operand fits within the size of
13113 // the MMO. This is because the MMO might indicate only a possible address
13114 // range instead of specifying the affected memory addresses precisely.
13115 assert(
13116 (!MMO->getType().isValid() ||
13117 TypeSize::isKnownLE(memvt.getStoreSize(), MMO->getSize().getValue())) &&
13118 "Size mismatch!");
13119}
13120
13121/// Profile - Gather unique data for the node.
13122///
13124 AddNodeIDNode(ID, this);
13125}
13126
13127namespace {
13128
13129 struct EVTArray {
13130 std::vector<EVT> VTs;
13131
13132 EVTArray() {
13133 VTs.reserve(MVT::VALUETYPE_SIZE);
13134 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
13135 VTs.push_back(MVT((MVT::SimpleValueType)i));
13136 }
13137 };
13138
13139} // end anonymous namespace
13140
13141/// getValueTypeList - Return a pointer to the specified value type.
13142///
13143const EVT *SDNode::getValueTypeList(MVT VT) {
13144 static EVTArray SimpleVTArray;
13145
13146 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
13147 return &SimpleVTArray.VTs[VT.SimpleTy];
13148}
13149
13150/// hasAnyUseOfValue - Return true if there are any use of the indicated
13151/// value. This method ignores uses of other values defined by this operation.
13152bool SDNode::hasAnyUseOfValue(unsigned Value) const {
13153 assert(Value < getNumValues() && "Bad value!");
13154
13155 for (SDUse &U : uses())
13156 if (U.getResNo() == Value)
13157 return true;
13158
13159 return false;
13160}
13161
13162/// isOnlyUserOf - Return true if this node is the only use of N.
13163bool SDNode::isOnlyUserOf(const SDNode *N) const {
13164 bool Seen = false;
13165 for (const SDNode *User : N->users()) {
13166 if (User == this)
13167 Seen = true;
13168 else
13169 return false;
13170 }
13171
13172 return Seen;
13173}
13174
13175/// Return true if the only users of N are contained in Nodes.
13177 bool Seen = false;
13178 for (const SDNode *User : N->users()) {
13179 if (llvm::is_contained(Nodes, User))
13180 Seen = true;
13181 else
13182 return false;
13183 }
13184
13185 return Seen;
13186}
13187
13188/// Return true if the referenced return value is an operand of N.
13189bool SDValue::isOperandOf(const SDNode *N) const {
13190 return is_contained(N->op_values(), *this);
13191}
13192
13193bool SDNode::isOperandOf(const SDNode *N) const {
13194 return any_of(N->op_values(),
13195 [this](SDValue Op) { return this == Op.getNode(); });
13196}
13197
13198/// reachesChainWithoutSideEffects - Return true if this operand (which must
13199/// be a chain) reaches the specified operand without crossing any
13200/// side-effecting instructions on any chain path. In practice, this looks
13201/// through token factors and non-volatile loads. In order to remain efficient,
13202/// this only looks a couple of nodes in, it does not do an exhaustive search.
13203///
13204/// Note that we only need to examine chains when we're searching for
13205/// side-effects; SelectionDAG requires that all side-effects are represented
13206/// by chains, even if another operand would force a specific ordering. This
13207/// constraint is necessary to allow transformations like splitting loads.
13209 unsigned Depth) const {
13210 if (*this == Dest) return true;
13211
13212 // Don't search too deeply, we just want to be able to see through
13213 // TokenFactor's etc.
13214 if (Depth == 0) return false;
13215
13216 // If this is a token factor, all inputs to the TF happen in parallel.
13217 if (getOpcode() == ISD::TokenFactor) {
13218 // First, try a shallow search.
13219 if (is_contained((*this)->ops(), Dest)) {
13220 // We found the chain we want as an operand of this TokenFactor.
13221 // Essentially, we reach the chain without side-effects if we could
13222 // serialize the TokenFactor into a simple chain of operations with
13223 // Dest as the last operation. This is automatically true if the
13224 // chain has one use: there are no other ordering constraints.
13225 // If the chain has more than one use, we give up: some other
13226 // use of Dest might force a side-effect between Dest and the current
13227 // node.
13228 if (Dest.hasOneUse())
13229 return true;
13230 }
13231 // Next, try a deep search: check whether every operand of the TokenFactor
13232 // reaches Dest.
13233 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
13234 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
13235 });
13236 }
13237
13238 // Loads don't have side effects, look through them.
13239 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
13240 if (Ld->isUnordered())
13241 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
13242 }
13243 return false;
13244}
13245
13246bool SDNode::hasPredecessor(const SDNode *N) const {
13249 Worklist.push_back(this);
13250 return hasPredecessorHelper(N, Visited, Worklist);
13251}
13252
13254 this->Flags &= Flags;
13255}
13256
13257SDValue
13259 ArrayRef<ISD::NodeType> CandidateBinOps,
13260 bool AllowPartials) {
13261 // The pattern must end in an extract from index 0.
13262 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13263 !isNullConstant(Extract->getOperand(1)))
13264 return SDValue();
13265
13266 // Match against one of the candidate binary ops.
13267 SDValue Op = Extract->getOperand(0);
13268 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
13269 return Op.getOpcode() == unsigned(BinOp);
13270 }))
13271 return SDValue();
13272
13273 // Floating-point reductions may require relaxed constraints on the final step
13274 // of the reduction because they may reorder intermediate operations.
13275 unsigned CandidateBinOp = Op.getOpcode();
13276 if (Op.getValueType().isFloatingPoint()) {
13277 SDNodeFlags Flags = Op->getFlags();
13278 switch (CandidateBinOp) {
13279 case ISD::FADD:
13280 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
13281 return SDValue();
13282 break;
13283 default:
13284 llvm_unreachable("Unhandled FP opcode for binop reduction");
13285 }
13286 }
13287
13288 // Matching failed - attempt to see if we did enough stages that a partial
13289 // reduction from a subvector is possible.
13290 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
13291 if (!AllowPartials || !Op)
13292 return SDValue();
13293 EVT OpVT = Op.getValueType();
13294 EVT OpSVT = OpVT.getScalarType();
13295 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
13296 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
13297 return SDValue();
13298 BinOp = (ISD::NodeType)CandidateBinOp;
13299 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
13300 };
13301
13302 // At each stage, we're looking for something that looks like:
13303 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
13304 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
13305 // i32 undef, i32 undef, i32 undef, i32 undef>
13306 // %a = binop <8 x i32> %op, %s
13307 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
13308 // we expect something like:
13309 // <4,5,6,7,u,u,u,u>
13310 // <2,3,u,u,u,u,u,u>
13311 // <1,u,u,u,u,u,u,u>
13312 // While a partial reduction match would be:
13313 // <2,3,u,u,u,u,u,u>
13314 // <1,u,u,u,u,u,u,u>
13315 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
13316 SDValue PrevOp;
13317 for (unsigned i = 0; i < Stages; ++i) {
13318 unsigned MaskEnd = (1 << i);
13319
13320 if (Op.getOpcode() != CandidateBinOp)
13321 return PartialReduction(PrevOp, MaskEnd);
13322
13323 SDValue Op0 = Op.getOperand(0);
13324 SDValue Op1 = Op.getOperand(1);
13325
13327 if (Shuffle) {
13328 Op = Op1;
13329 } else {
13330 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
13331 Op = Op0;
13332 }
13333
13334 // The first operand of the shuffle should be the same as the other operand
13335 // of the binop.
13336 if (!Shuffle || Shuffle->getOperand(0) != Op)
13337 return PartialReduction(PrevOp, MaskEnd);
13338
13339 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
13340 for (int Index = 0; Index < (int)MaskEnd; ++Index)
13341 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
13342 return PartialReduction(PrevOp, MaskEnd);
13343
13344 PrevOp = Op;
13345 }
13346
13347 // Handle subvector reductions, which tend to appear after the shuffle
13348 // reduction stages.
13349 while (Op.getOpcode() == CandidateBinOp) {
13350 unsigned NumElts = Op.getValueType().getVectorNumElements();
13351 SDValue Op0 = Op.getOperand(0);
13352 SDValue Op1 = Op.getOperand(1);
13353 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13355 Op0.getOperand(0) != Op1.getOperand(0))
13356 break;
13357 SDValue Src = Op0.getOperand(0);
13358 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
13359 if (NumSrcElts != (2 * NumElts))
13360 break;
13361 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
13362 Op1.getConstantOperandAPInt(1) == NumElts) &&
13363 !(Op1.getConstantOperandAPInt(1) == 0 &&
13364 Op0.getConstantOperandAPInt(1) == NumElts))
13365 break;
13366 Op = Src;
13367 }
13368
13369 BinOp = (ISD::NodeType)CandidateBinOp;
13370 return Op;
13371}
13372
13374 EVT VT = N->getValueType(0);
13375 EVT EltVT = VT.getVectorElementType();
13376 unsigned NE = VT.getVectorNumElements();
13377
13378 SDLoc dl(N);
13379
13380 // If ResNE is 0, fully unroll the vector op.
13381 if (ResNE == 0)
13382 ResNE = NE;
13383 else if (NE > ResNE)
13384 NE = ResNE;
13385
13386 if (N->getNumValues() == 2) {
13387 SmallVector<SDValue, 8> Scalars0, Scalars1;
13388 SmallVector<SDValue, 4> Operands(N->getNumOperands());
13389 EVT VT1 = N->getValueType(1);
13390 EVT EltVT1 = VT1.getVectorElementType();
13391
13392 unsigned i;
13393 for (i = 0; i != NE; ++i) {
13394 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
13395 SDValue Operand = N->getOperand(j);
13396 EVT OperandVT = Operand.getValueType();
13397
13398 // A vector operand; extract a single element.
13399 EVT OperandEltVT = OperandVT.getVectorElementType();
13400 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
13401 }
13402
13403 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
13404 Scalars0.push_back(EltOp);
13405 Scalars1.push_back(EltOp.getValue(1));
13406 }
13407
13408 for (; i < ResNE; ++i) {
13409 Scalars0.push_back(getUNDEF(EltVT));
13410 Scalars1.push_back(getUNDEF(EltVT1));
13411 }
13412
13413 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
13414 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResNE);
13415 SDValue Vec0 = getBuildVector(VecVT, dl, Scalars0);
13416 SDValue Vec1 = getBuildVector(VecVT1, dl, Scalars1);
13417 return getMergeValues({Vec0, Vec1}, dl);
13418 }
13419
13420 assert(N->getNumValues() == 1 &&
13421 "Can't unroll a vector with multiple results!");
13422
13424 SmallVector<SDValue, 4> Operands(N->getNumOperands());
13425
13426 unsigned i;
13427 for (i= 0; i != NE; ++i) {
13428 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
13429 SDValue Operand = N->getOperand(j);
13430 EVT OperandVT = Operand.getValueType();
13431 if (OperandVT.isVector()) {
13432 // A vector operand; extract a single element.
13433 EVT OperandEltVT = OperandVT.getVectorElementType();
13434 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
13435 } else {
13436 // A scalar operand; just use it as is.
13437 Operands[j] = Operand;
13438 }
13439 }
13440
13441 switch (N->getOpcode()) {
13442 default: {
13443 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
13444 N->getFlags()));
13445 break;
13446 }
13447 case ISD::VSELECT:
13448 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
13449 break;
13450 case ISD::SHL:
13451 case ISD::SRA:
13452 case ISD::SRL:
13453 case ISD::ROTL:
13454 case ISD::ROTR:
13455 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
13456 getShiftAmountOperand(Operands[0].getValueType(),
13457 Operands[1])));
13458 break;
13460 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
13461 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
13462 Operands[0],
13463 getValueType(ExtVT)));
13464 break;
13465 }
13466 case ISD::ADDRSPACECAST: {
13467 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
13468 Scalars.push_back(getAddrSpaceCast(dl, EltVT, Operands[0],
13469 ASC->getSrcAddressSpace(),
13470 ASC->getDestAddressSpace()));
13471 break;
13472 }
13473 }
13474 }
13475
13476 for (; i < ResNE; ++i)
13477 Scalars.push_back(getUNDEF(EltVT));
13478
13479 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
13480 return getBuildVector(VecVT, dl, Scalars);
13481}
13482
13483std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
13484 SDNode *N, unsigned ResNE) {
13485 unsigned Opcode = N->getOpcode();
13486 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
13487 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
13488 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
13489 "Expected an overflow opcode");
13490
13491 EVT ResVT = N->getValueType(0);
13492 EVT OvVT = N->getValueType(1);
13493 EVT ResEltVT = ResVT.getVectorElementType();
13494 EVT OvEltVT = OvVT.getVectorElementType();
13495 SDLoc dl(N);
13496
13497 // If ResNE is 0, fully unroll the vector op.
13498 unsigned NE = ResVT.getVectorNumElements();
13499 if (ResNE == 0)
13500 ResNE = NE;
13501 else if (NE > ResNE)
13502 NE = ResNE;
13503
13504 SmallVector<SDValue, 8> LHSScalars;
13505 SmallVector<SDValue, 8> RHSScalars;
13506 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
13507 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
13508
13509 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
13510 SDVTList VTs = getVTList(ResEltVT, SVT);
13511 SmallVector<SDValue, 8> ResScalars;
13512 SmallVector<SDValue, 8> OvScalars;
13513 for (unsigned i = 0; i < NE; ++i) {
13514 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
13515 SDValue Ov =
13516 getSelect(dl, OvEltVT, Res.getValue(1),
13517 getBoolConstant(true, dl, OvEltVT, ResVT),
13518 getConstant(0, dl, OvEltVT));
13519
13520 ResScalars.push_back(Res);
13521 OvScalars.push_back(Ov);
13522 }
13523
13524 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
13525 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
13526
13527 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
13528 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
13529 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
13530 getBuildVector(NewOvVT, dl, OvScalars));
13531}
13532
13535 unsigned Bytes,
13536 int Dist) const {
13537 if (LD->isVolatile() || Base->isVolatile())
13538 return false;
13539 // TODO: probably too restrictive for atomics, revisit
13540 if (!LD->isSimple())
13541 return false;
13542 if (LD->isIndexed() || Base->isIndexed())
13543 return false;
13544 if (LD->getChain() != Base->getChain())
13545 return false;
13546 EVT VT = LD->getMemoryVT();
13547 if (VT.getSizeInBits() / 8 != Bytes)
13548 return false;
13549
13550 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
13551 auto LocDecomp = BaseIndexOffset::match(LD, *this);
13552
13553 int64_t Offset = 0;
13554 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
13555 return (Dist * (int64_t)Bytes == Offset);
13556 return false;
13557}
13558
13559/// InferPtrAlignment - Infer alignment of a load / store address. Return
13560/// std::nullopt if it cannot be inferred.
13562 // If this is a GlobalAddress + cst, return the alignment.
13563 const GlobalValue *GV = nullptr;
13564 int64_t GVOffset = 0;
13565 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
13566 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
13567 KnownBits Known(PtrWidth);
13569 unsigned AlignBits = Known.countMinTrailingZeros();
13570 if (AlignBits)
13571 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
13572 }
13573
13574 // If this is a direct reference to a stack slot, use information about the
13575 // stack slot's alignment.
13576 int FrameIdx = INT_MIN;
13577 int64_t FrameOffset = 0;
13579 FrameIdx = FI->getIndex();
13580 } else if (isBaseWithConstantOffset(Ptr) &&
13582 // Handle FI+Cst
13583 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
13584 FrameOffset = Ptr.getConstantOperandVal(1);
13585 }
13586
13587 if (FrameIdx != INT_MIN) {
13589 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
13590 }
13591
13592 return std::nullopt;
13593}
13594
13595/// Split the scalar node with EXTRACT_ELEMENT using the provided
13596/// VTs and return the low/high part.
13597std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
13598 const SDLoc &DL,
13599 const EVT &LoVT,
13600 const EVT &HiVT) {
13601 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
13602 "Split node must be a scalar type");
13603 SDValue Lo =
13605 SDValue Hi =
13607 return std::make_pair(Lo, Hi);
13608}
13609
13610/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
13611/// which is split (or expanded) into two not necessarily identical pieces.
13612std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
13613 // Currently all types are split in half.
13614 EVT LoVT, HiVT;
13615 if (!VT.isVector())
13616 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
13617 else
13618 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
13619
13620 return std::make_pair(LoVT, HiVT);
13621}
13622
13623/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
13624/// type, dependent on an enveloping VT that has been split into two identical
13625/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
13626std::pair<EVT, EVT>
13628 bool *HiIsEmpty) const {
13629 EVT EltTp = VT.getVectorElementType();
13630 // Examples:
13631 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
13632 // custom VL=9 with enveloping VL=8/8 yields 8/1
13633 // custom VL=10 with enveloping VL=8/8 yields 8/2
13634 // etc.
13635 ElementCount VTNumElts = VT.getVectorElementCount();
13636 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
13637 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
13638 "Mixing fixed width and scalable vectors when enveloping a type");
13639 EVT LoVT, HiVT;
13640 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
13641 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
13642 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
13643 *HiIsEmpty = false;
13644 } else {
13645 // Flag that hi type has zero storage size, but return split envelop type
13646 // (this would be easier if vector types with zero elements were allowed).
13647 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
13648 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
13649 *HiIsEmpty = true;
13650 }
13651 return std::make_pair(LoVT, HiVT);
13652}
13653
13654/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
13655/// low/high part.
13656std::pair<SDValue, SDValue>
13657SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
13658 const EVT &HiVT) {
13659 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
13660 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
13661 "Splitting vector with an invalid mixture of fixed and scalable "
13662 "vector types");
13664 N.getValueType().getVectorMinNumElements() &&
13665 "More vector elements requested than available!");
13666 SDValue Lo, Hi;
13667 Lo = getExtractSubvector(DL, LoVT, N, 0);
13668 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
13669 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
13670 // IDX with the runtime scaling factor of the result vector type. For
13671 // fixed-width result vectors, that runtime scaling factor is 1.
13674 return std::make_pair(Lo, Hi);
13675}
13676
13677std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
13678 const SDLoc &DL) {
13679 // Split the vector length parameter.
13680 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
13681 EVT VT = N.getValueType();
13683 "Expecting the mask to be an evenly-sized vector");
13684 SDValue HalfNumElts = getElementCount(
13686 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
13687 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
13688 return std::make_pair(Lo, Hi);
13689}
13690
13691/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
13693 EVT VT = N.getValueType();
13696 return getInsertSubvector(DL, getUNDEF(WideVT), N, 0);
13697}
13698
13701 unsigned Start, unsigned Count,
13702 EVT EltVT) {
13703 EVT VT = Op.getValueType();
13704 if (Count == 0)
13706 if (EltVT == EVT())
13707 EltVT = VT.getVectorElementType();
13708 SDLoc SL(Op);
13709 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
13710 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
13711 }
13712}
13713
13714// getAddressSpace - Return the address space this GlobalAddress belongs to.
13716 return getGlobal()->getType()->getAddressSpace();
13717}
13718
13721 return Val.MachineCPVal->getType();
13722 return Val.ConstVal->getType();
13723}
13724
13725bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
13726 unsigned &SplatBitSize,
13727 bool &HasAnyUndefs,
13728 unsigned MinSplatBits,
13729 bool IsBigEndian) const {
13730 EVT VT = getValueType(0);
13731 assert(VT.isVector() && "Expected a vector type");
13732 unsigned VecWidth = VT.getSizeInBits();
13733 if (MinSplatBits > VecWidth)
13734 return false;
13735
13736 // FIXME: The widths are based on this node's type, but build vectors can
13737 // truncate their operands.
13738 SplatValue = APInt(VecWidth, 0);
13739 SplatUndef = APInt(VecWidth, 0);
13740
13741 // Get the bits. Bits with undefined values (when the corresponding element
13742 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
13743 // in SplatValue. If any of the values are not constant, give up and return
13744 // false.
13745 unsigned int NumOps = getNumOperands();
13746 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
13747 unsigned EltWidth = VT.getScalarSizeInBits();
13748
13749 for (unsigned j = 0; j < NumOps; ++j) {
13750 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
13751 SDValue OpVal = getOperand(i);
13752 unsigned BitPos = j * EltWidth;
13753
13754 if (OpVal.isUndef())
13755 SplatUndef.setBits(BitPos, BitPos + EltWidth);
13756 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
13757 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
13758 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
13759 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
13760 else
13761 return false;
13762 }
13763
13764 // The build_vector is all constants or undefs. Find the smallest element
13765 // size that splats the vector.
13766 HasAnyUndefs = (SplatUndef != 0);
13767
13768 // FIXME: This does not work for vectors with elements less than 8 bits.
13769 while (VecWidth > 8) {
13770 // If we can't split in half, stop here.
13771 if (VecWidth & 1)
13772 break;
13773
13774 unsigned HalfSize = VecWidth / 2;
13775 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
13776 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
13777 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
13778 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
13779
13780 // If the two halves do not match (ignoring undef bits), stop here.
13781 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
13782 MinSplatBits > HalfSize)
13783 break;
13784
13785 SplatValue = HighValue | LowValue;
13786 SplatUndef = HighUndef & LowUndef;
13787
13788 VecWidth = HalfSize;
13789 }
13790
13791 // FIXME: The loop above only tries to split in halves. But if the input
13792 // vector for example is <3 x i16> it wouldn't be able to detect a
13793 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
13794 // optimizations. I guess that back in the days when this helper was created
13795 // vectors normally was power-of-2 sized.
13796
13797 SplatBitSize = VecWidth;
13798 return true;
13799}
13800
13802 BitVector *UndefElements) const {
13803 unsigned NumOps = getNumOperands();
13804 if (UndefElements) {
13805 UndefElements->clear();
13806 UndefElements->resize(NumOps);
13807 }
13808 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
13809 if (!DemandedElts)
13810 return SDValue();
13811 SDValue Splatted;
13812 for (unsigned i = 0; i != NumOps; ++i) {
13813 if (!DemandedElts[i])
13814 continue;
13815 SDValue Op = getOperand(i);
13816 if (Op.isUndef()) {
13817 if (UndefElements)
13818 (*UndefElements)[i] = true;
13819 } else if (!Splatted) {
13820 Splatted = Op;
13821 } else if (Splatted != Op) {
13822 return SDValue();
13823 }
13824 }
13825
13826 if (!Splatted) {
13827 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
13828 assert(getOperand(FirstDemandedIdx).isUndef() &&
13829 "Can only have a splat without a constant for all undefs.");
13830 return getOperand(FirstDemandedIdx);
13831 }
13832
13833 return Splatted;
13834}
13835
13837 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
13838 return getSplatValue(DemandedElts, UndefElements);
13839}
13840
13842 SmallVectorImpl<SDValue> &Sequence,
13843 BitVector *UndefElements) const {
13844 unsigned NumOps = getNumOperands();
13845 Sequence.clear();
13846 if (UndefElements) {
13847 UndefElements->clear();
13848 UndefElements->resize(NumOps);
13849 }
13850 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
13851 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
13852 return false;
13853
13854 // Set the undefs even if we don't find a sequence (like getSplatValue).
13855 if (UndefElements)
13856 for (unsigned I = 0; I != NumOps; ++I)
13857 if (DemandedElts[I] && getOperand(I).isUndef())
13858 (*UndefElements)[I] = true;
13859
13860 // Iteratively widen the sequence length looking for repetitions.
13861 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
13862 Sequence.append(SeqLen, SDValue());
13863 for (unsigned I = 0; I != NumOps; ++I) {
13864 if (!DemandedElts[I])
13865 continue;
13866 SDValue &SeqOp = Sequence[I % SeqLen];
13868 if (Op.isUndef()) {
13869 if (!SeqOp)
13870 SeqOp = Op;
13871 continue;
13872 }
13873 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
13874 Sequence.clear();
13875 break;
13876 }
13877 SeqOp = Op;
13878 }
13879 if (!Sequence.empty())
13880 return true;
13881 }
13882
13883 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
13884 return false;
13885}
13886
13888 BitVector *UndefElements) const {
13889 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
13890 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
13891}
13892
13895 BitVector *UndefElements) const {
13897 getSplatValue(DemandedElts, UndefElements));
13898}
13899
13902 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
13903}
13904
13907 BitVector *UndefElements) const {
13909 getSplatValue(DemandedElts, UndefElements));
13910}
13911
13916
13917int32_t
13919 uint32_t BitWidth) const {
13920 if (ConstantFPSDNode *CN =
13922 bool IsExact;
13923 APSInt IntVal(BitWidth);
13924 const APFloat &APF = CN->getValueAPF();
13925 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
13926 APFloat::opOK ||
13927 !IsExact)
13928 return -1;
13929
13930 return IntVal.exactLogBase2();
13931 }
13932 return -1;
13933}
13934
13936 bool IsLittleEndian, unsigned DstEltSizeInBits,
13937 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
13938 // Early-out if this contains anything but Undef/Constant/ConstantFP.
13939 if (!isConstant())
13940 return false;
13941
13942 unsigned NumSrcOps = getNumOperands();
13943 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
13944 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
13945 "Invalid bitcast scale");
13946
13947 // Extract raw src bits.
13948 SmallVector<APInt> SrcBitElements(NumSrcOps,
13949 APInt::getZero(SrcEltSizeInBits));
13950 BitVector SrcUndeElements(NumSrcOps, false);
13951
13952 for (unsigned I = 0; I != NumSrcOps; ++I) {
13954 if (Op.isUndef()) {
13955 SrcUndeElements.set(I);
13956 continue;
13957 }
13958 auto *CInt = dyn_cast<ConstantSDNode>(Op);
13959 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
13960 assert((CInt || CFP) && "Unknown constant");
13961 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
13962 : CFP->getValueAPF().bitcastToAPInt();
13963 }
13964
13965 // Recast to dst width.
13966 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
13967 SrcBitElements, UndefElements, SrcUndeElements);
13968 return true;
13969}
13970
13971void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
13972 unsigned DstEltSizeInBits,
13973 SmallVectorImpl<APInt> &DstBitElements,
13974 ArrayRef<APInt> SrcBitElements,
13975 BitVector &DstUndefElements,
13976 const BitVector &SrcUndefElements) {
13977 unsigned NumSrcOps = SrcBitElements.size();
13978 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
13979 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
13980 "Invalid bitcast scale");
13981 assert(NumSrcOps == SrcUndefElements.size() &&
13982 "Vector size mismatch");
13983
13984 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
13985 DstUndefElements.clear();
13986 DstUndefElements.resize(NumDstOps, false);
13987 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
13988
13989 // Concatenate src elements constant bits together into dst element.
13990 if (SrcEltSizeInBits <= DstEltSizeInBits) {
13991 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
13992 for (unsigned I = 0; I != NumDstOps; ++I) {
13993 DstUndefElements.set(I);
13994 APInt &DstBits = DstBitElements[I];
13995 for (unsigned J = 0; J != Scale; ++J) {
13996 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
13997 if (SrcUndefElements[Idx])
13998 continue;
13999 DstUndefElements.reset(I);
14000 const APInt &SrcBits = SrcBitElements[Idx];
14001 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
14002 "Illegal constant bitwidths");
14003 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
14004 }
14005 }
14006 return;
14007 }
14008
14009 // Split src element constant bits into dst elements.
14010 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
14011 for (unsigned I = 0; I != NumSrcOps; ++I) {
14012 if (SrcUndefElements[I]) {
14013 DstUndefElements.set(I * Scale, (I + 1) * Scale);
14014 continue;
14015 }
14016 const APInt &SrcBits = SrcBitElements[I];
14017 for (unsigned J = 0; J != Scale; ++J) {
14018 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14019 APInt &DstBits = DstBitElements[Idx];
14020 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
14021 }
14022 }
14023}
14024
14026 for (const SDValue &Op : op_values()) {
14027 unsigned Opc = Op.getOpcode();
14028 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
14029 return false;
14030 }
14031 return true;
14032}
14033
14034std::optional<std::pair<APInt, APInt>>
14036 unsigned NumOps = getNumOperands();
14037 if (NumOps < 2)
14038 return std::nullopt;
14039
14042 return std::nullopt;
14043
14044 unsigned EltSize = getValueType(0).getScalarSizeInBits();
14045 APInt Start = getConstantOperandAPInt(0).trunc(EltSize);
14046 APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start;
14047
14048 if (Stride.isZero())
14049 return std::nullopt;
14050
14051 for (unsigned i = 2; i < NumOps; ++i) {
14053 return std::nullopt;
14054
14055 APInt Val = getConstantOperandAPInt(i).trunc(EltSize);
14056 if (Val != (Start + (Stride * i)))
14057 return std::nullopt;
14058 }
14059
14060 return std::make_pair(Start, Stride);
14061}
14062
14064 // Find the first non-undef value in the shuffle mask.
14065 unsigned i, e;
14066 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
14067 /* search */;
14068
14069 // If all elements are undefined, this shuffle can be considered a splat
14070 // (although it should eventually get simplified away completely).
14071 if (i == e)
14072 return true;
14073
14074 // Make sure all remaining elements are either undef or the same as the first
14075 // non-undef value.
14076 for (int Idx = Mask[i]; i != e; ++i)
14077 if (Mask[i] >= 0 && Mask[i] != Idx)
14078 return false;
14079 return true;
14080}
14081
14082// Returns true if it is a constant integer BuildVector or constant integer,
14083// possibly hidden by a bitcast.
14085 SDValue N, bool AllowOpaques) const {
14087
14088 if (auto *C = dyn_cast<ConstantSDNode>(N))
14089 return AllowOpaques || !C->isOpaque();
14090
14092 return true;
14093
14094 // Treat a GlobalAddress supporting constant offset folding as a
14095 // constant integer.
14096 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
14097 if (GA->getOpcode() == ISD::GlobalAddress &&
14098 TLI->isOffsetFoldingLegal(GA))
14099 return true;
14100
14101 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
14102 isa<ConstantSDNode>(N.getOperand(0)))
14103 return true;
14104 return false;
14105}
14106
14107// Returns true if it is a constant float BuildVector or constant float.
14110 return true;
14111
14113 return true;
14114
14115 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
14116 isa<ConstantFPSDNode>(N.getOperand(0)))
14117 return true;
14118
14119 return false;
14120}
14121
14122std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
14123 ConstantSDNode *Const =
14124 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
14125 if (!Const)
14126 return std::nullopt;
14127
14128 EVT VT = N->getValueType(0);
14129 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
14130 switch (TLI->getBooleanContents(N.getValueType())) {
14132 if (CVal.isOne())
14133 return true;
14134 if (CVal.isZero())
14135 return false;
14136 return std::nullopt;
14138 if (CVal.isAllOnes())
14139 return true;
14140 if (CVal.isZero())
14141 return false;
14142 return std::nullopt;
14144 return CVal[0];
14145 }
14146 llvm_unreachable("Unknown BooleanContent enum");
14147}
14148
14149void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
14150 assert(!Node->OperandList && "Node already has operands");
14152 "too many operands to fit into SDNode");
14153 SDUse *Ops = OperandRecycler.allocate(
14154 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
14155
14156 bool IsDivergent = false;
14157 for (unsigned I = 0; I != Vals.size(); ++I) {
14158 Ops[I].setUser(Node);
14159 Ops[I].setInitial(Vals[I]);
14160 EVT VT = Ops[I].getValueType();
14161
14162 // Skip Chain. It does not carry divergence.
14163 if (VT != MVT::Other &&
14164 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
14165 Ops[I].getNode()->isDivergent()) {
14166 IsDivergent = true;
14167 }
14168 }
14169 Node->NumOperands = Vals.size();
14170 Node->OperandList = Ops;
14171 if (!TLI->isSDNodeAlwaysUniform(Node)) {
14172 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
14173 Node->SDNodeBits.IsDivergent = IsDivergent;
14174 }
14175 checkForCycles(Node);
14176}
14177
14180 size_t Limit = SDNode::getMaxNumOperands();
14181 while (Vals.size() > Limit) {
14182 unsigned SliceIdx = Vals.size() - Limit;
14183 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
14184 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
14185 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
14186 Vals.emplace_back(NewTF);
14187 }
14188 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
14189}
14190
14192 EVT VT, SDNodeFlags Flags) {
14193 switch (Opcode) {
14194 default:
14195 return SDValue();
14196 case ISD::ADD:
14197 case ISD::OR:
14198 case ISD::XOR:
14199 case ISD::UMAX:
14200 return getConstant(0, DL, VT);
14201 case ISD::MUL:
14202 return getConstant(1, DL, VT);
14203 case ISD::AND:
14204 case ISD::UMIN:
14205 return getAllOnesConstant(DL, VT);
14206 case ISD::SMAX:
14208 case ISD::SMIN:
14210 case ISD::FADD:
14211 // If flags allow, prefer positive zero since it's generally cheaper
14212 // to materialize on most targets.
14213 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
14214 case ISD::FMUL:
14215 return getConstantFP(1.0, DL, VT);
14216 case ISD::FMINNUM:
14217 case ISD::FMAXNUM: {
14218 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
14219 const fltSemantics &Semantics = VT.getFltSemantics();
14220 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
14221 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
14222 APFloat::getLargest(Semantics);
14223 if (Opcode == ISD::FMAXNUM)
14224 NeutralAF.changeSign();
14225
14226 return getConstantFP(NeutralAF, DL, VT);
14227 }
14228 case ISD::FMINIMUM:
14229 case ISD::FMAXIMUM: {
14230 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
14231 const fltSemantics &Semantics = VT.getFltSemantics();
14232 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
14233 : APFloat::getLargest(Semantics);
14234 if (Opcode == ISD::FMAXIMUM)
14235 NeutralAF.changeSign();
14236
14237 return getConstantFP(NeutralAF, DL, VT);
14238 }
14239
14240 }
14241}
14242
14243/// Helper used to make a call to a library function that has one argument of
14244/// pointer type.
14245///
14246/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
14247/// used to get or set floating-point state. They have one argument of pointer
14248/// type, which points to the memory region containing bits of the
14249/// floating-point state. The value returned by such function is ignored in the
14250/// created call.
14251///
14252/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
14253/// \param Ptr Pointer used to save/load state.
14254/// \param InChain Ingoing token chain.
14255/// \returns Outgoing chain token.
14257 SDValue InChain,
14258 const SDLoc &DLoc) {
14259 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
14261 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
14262 RTLIB::LibcallImpl LibcallImpl =
14263 TLI->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
14264 if (LibcallImpl == RTLIB::Unsupported)
14265 reportFatalUsageError("emitting call to unsupported libcall");
14266
14267 SDValue Callee =
14268 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
14270 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
14271 TLI->getLibcallImplCallingConv(LibcallImpl),
14272 Type::getVoidTy(*getContext()), Callee, std::move(Args));
14273 return TLI->LowerCallTo(CLI).second;
14274}
14275
14277 assert(From && To && "Invalid SDNode; empty source SDValue?");
14278 auto I = SDEI.find(From);
14279 if (I == SDEI.end())
14280 return;
14281
14282 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
14283 // the iterator, hence the need to make a copy to prevent a use-after-free.
14284 NodeExtraInfo NEI = I->second;
14285 if (LLVM_LIKELY(!NEI.PCSections)) {
14286 // No deep copy required for the types of extra info set.
14287 //
14288 // FIXME: Investigate if other types of extra info also need deep copy. This
14289 // depends on the types of nodes they can be attached to: if some extra info
14290 // is only ever attached to nodes where a replacement To node is always the
14291 // node where later use and propagation of the extra info has the intended
14292 // semantics, no deep copy is required.
14293 SDEI[To] = std::move(NEI);
14294 return;
14295 }
14296
14297 const SDNode *EntrySDN = getEntryNode().getNode();
14298
14299 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
14300 // through the replacement of From with To. Otherwise, replacements of a node
14301 // (From) with more complex nodes (To and its operands) may result in lost
14302 // extra info where the root node (To) is insignificant in further propagating
14303 // and using extra info when further lowering to MIR.
14304 //
14305 // In the first step pre-populate the visited set with the nodes reachable
14306 // from the old From node. This avoids copying NodeExtraInfo to parts of the
14307 // DAG that is not new and should be left untouched.
14308 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
14309 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
14310 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
14311 if (MaxDepth == 0) {
14312 // Remember this node in case we need to increase MaxDepth and continue
14313 // populating FromReach from this node.
14314 Leafs.emplace_back(N);
14315 return;
14316 }
14317 if (!FromReach.insert(N).second)
14318 return;
14319 for (const SDValue &Op : N->op_values())
14320 Self(Self, Op.getNode(), MaxDepth - 1);
14321 };
14322
14323 // Copy extra info to To and all its transitive operands (that are new).
14325 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
14326 if (FromReach.contains(N))
14327 return true;
14328 if (!Visited.insert(N).second)
14329 return true;
14330 if (EntrySDN == N)
14331 return false;
14332 for (const SDValue &Op : N->op_values()) {
14333 if (N == To && Op.getNode() == EntrySDN) {
14334 // Special case: New node's operand is the entry node; just need to
14335 // copy extra info to new node.
14336 break;
14337 }
14338 if (!Self(Self, Op.getNode()))
14339 return false;
14340 }
14341 // Copy only if entry node was not reached.
14342 SDEI[N] = NEI;
14343 return true;
14344 };
14345
14346 // We first try with a lower MaxDepth, assuming that the path to common
14347 // operands between From and To is relatively short. This significantly
14348 // improves performance in the common case. The initial MaxDepth is big
14349 // enough to avoid retry in the common case; the last MaxDepth is large
14350 // enough to avoid having to use the fallback below (and protects from
14351 // potential stack exhaustion from recursion).
14352 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
14353 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
14354 // StartFrom is the previous (or initial) set of leafs reachable at the
14355 // previous maximum depth.
14357 std::swap(StartFrom, Leafs);
14358 for (const SDNode *N : StartFrom)
14359 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
14360 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
14361 return;
14362 // This should happen very rarely (reached the entry node).
14363 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
14364 assert(!Leafs.empty());
14365 }
14366
14367 // This should not happen - but if it did, that means the subgraph reachable
14368 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
14369 // could not visit all reachable common operands. Consequently, we were able
14370 // to reach the entry node.
14371 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
14372 assert(false && "From subgraph too complex - increase max. MaxDepth?");
14373 // Best-effort fallback if assertions disabled.
14374 SDEI[To] = std::move(NEI);
14375}
14376
14377#ifndef NDEBUG
14378static void checkForCyclesHelper(const SDNode *N,
14381 const llvm::SelectionDAG *DAG) {
14382 // If this node has already been checked, don't check it again.
14383 if (Checked.count(N))
14384 return;
14385
14386 // If a node has already been visited on this depth-first walk, reject it as
14387 // a cycle.
14388 if (!Visited.insert(N).second) {
14389 errs() << "Detected cycle in SelectionDAG\n";
14390 dbgs() << "Offending node:\n";
14391 N->dumprFull(DAG); dbgs() << "\n";
14392 abort();
14393 }
14394
14395 for (const SDValue &Op : N->op_values())
14396 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
14397
14398 Checked.insert(N);
14399 Visited.erase(N);
14400}
14401#endif
14402
14404 const llvm::SelectionDAG *DAG,
14405 bool force) {
14406#ifndef NDEBUG
14407 bool check = force;
14408#ifdef EXPENSIVE_CHECKS
14409 check = true;
14410#endif // EXPENSIVE_CHECKS
14411 if (check) {
14412 assert(N && "Checking nonexistent SDNode");
14415 checkForCyclesHelper(N, visited, checked, DAG);
14416 }
14417#endif // !NDEBUG
14418}
14419
14420void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
14421 checkForCycles(DAG->getRoot().getNode(), DAG, force);
14422}
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:904
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:282
const APFloat & getValue() const
Definition Constants.h:326
This is the shared class of boolean and integer constants.
Definition Constants.h:87
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
LLVM_ABI Type * getType() const
This class represents a range of values.
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.
virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID)=0
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
A description of a memory reference used in the backend.
const MDNode * getRanges() const
Return the range tag for the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
This class contains meta information specific to a module.
An SDNode that represents everything that will be needed to construct a MachineInstr.
This class is used to represent an MGATHER node.
This class is used to represent an MLOAD node.
This class is used to represent an MSCATTER node.
This class is used to represent an MSTORE node.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
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 clmulr(const APInt &LHS, const APInt &RHS)
Perform a reversed carry-less multiply.
Definition APInt.cpp:3201
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
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3191
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
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3206
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:813
@ 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:847
@ 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:874
@ 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:741
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:904
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
Definition ISDOpcodes.h:997
@ 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:987
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:249
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:768
@ 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:838
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:709
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:659
@ 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:821
@ 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:685
@ 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:790
@ 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:666
@ 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.
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:786
@ 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:698
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:759
@ 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:844
@ 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:805
@ 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
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, IMM) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by IMM elements and retu...
Definition ISDOpcodes.h:648
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:893
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:882
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:721
@ 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:972
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:799
@ 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:920
@ 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:733
@ 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:729
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:704
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, IMM) - Shifts CONCAT_VECTORS(VEC1, VEC2) right by IMM elements and re...
Definition ISDOpcodes.h:651
@ 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:675
@ 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
@ 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:953
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:693
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:915
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
Definition ISDOpcodes.h:991
@ 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:939
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:850
@ 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:827
@ 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:716
@ 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.
Definition Types.h:26
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:237
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h: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:539
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h: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:719
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
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
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h: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)