xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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 
13 #include "llvm/CodeGen/SelectionDAG.h"
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"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Analysis/VectorUtils.h"
30 #include "llvm/CodeGen/Analysis.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineValueType.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetFrameLowering.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/ConstantRange.h"
50 #include "llvm/IR/Constants.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DebugInfoMetadata.h"
53 #include "llvm/IR/DebugLoc.h"
54 #include "llvm/IR/DerivedTypes.h"
55 #include "llvm/IR/Function.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/Metadata.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/KnownBits.h"
65 #include "llvm/Support/MathExtras.h"
66 #include "llvm/Support/Mutex.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Target/TargetMachine.h"
69 #include "llvm/Target/TargetOptions.h"
70 #include "llvm/TargetParser/Triple.h"
71 #include "llvm/Transforms/Utils/SizeOpts.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <cstdlib>
76 #include <limits>
77 #include <set>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 /// makeVTList - Return an instance of the SDVTList struct initialized with the
85 /// specified members.
86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
87   SDVTList Res = {VTs, NumVTs};
88   return Res;
89 }
90 
91 // Default null implementations of the callbacks.
92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
95 
96 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
97 void SelectionDAG::DAGNodeInsertedListener::anchor() {}
98 
99 #define DEBUG_TYPE "selectiondag"
100 
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102        cl::Hidden, cl::init(true),
103        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
104 
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106        cl::desc("Number limit for gluing ld/st of memcpy."),
107        cl::Hidden, cl::init(0));
108 
109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
111 }
112 
113 //===----------------------------------------------------------------------===//
114 //                              ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
116 
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122   return getValueAPF().bitwiseIsEqual(V);
123 }
124 
125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126                                            const APFloat& Val) {
127   assert(VT.isFloatingPoint() && "Can only convert between FP types");
128 
129   // convert modifies in place, so make a copy.
130   APFloat Val2 = APFloat(Val);
131   bool losesInfo;
132   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133                       APFloat::rmNearestTiesToEven,
134                       &losesInfo);
135   return !losesInfo;
136 }
137 
138 //===----------------------------------------------------------------------===//
139 //                              ISD Namespace
140 //===----------------------------------------------------------------------===//
141 
142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144     unsigned EltSize =
145         N->getValueType(0).getVectorElementType().getSizeInBits();
146     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getAPIntValue().trunc(EltSize);
148       return true;
149     }
150     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
151       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
152       return true;
153     }
154   }
155 
156   auto *BV = dyn_cast<BuildVectorSDNode>(N);
157   if (!BV)
158     return false;
159 
160   APInt SplatUndef;
161   unsigned SplatBitSize;
162   bool HasUndefs;
163   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
164   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
165                              EltSize) &&
166          EltSize == SplatBitSize;
167 }
168 
169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
170 // specializations of the more general isConstantSplatVector()?
171 
172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
173   // Look through a bit convert.
174   while (N->getOpcode() == ISD::BITCAST)
175     N = N->getOperand(0).getNode();
176 
177   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
178     APInt SplatVal;
179     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
180   }
181 
182   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
183 
184   unsigned i = 0, e = N->getNumOperands();
185 
186   // Skip over all of the undef values.
187   while (i != e && N->getOperand(i).isUndef())
188     ++i;
189 
190   // Do not accept an all-undef vector.
191   if (i == e) return false;
192 
193   // Do not accept build_vectors that aren't all constants or which have non-~0
194   // elements. We have to be a bit careful here, as the type of the constant
195   // may not be the same as the type of the vector elements due to type
196   // legalization (the elements are promoted to a legal type for the target and
197   // a vector of a type may be legal when the base element type is not).
198   // We only want to check enough bits to cover the vector elements, because
199   // we care if the resultant vector is all ones, not whether the individual
200   // constants are.
201   SDValue NotZero = N->getOperand(i);
202   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
204     if (CN->getAPIntValue().countr_one() < EltSize)
205       return false;
206   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
207     if (CFPN->getValueAPF().bitcastToAPInt().countr_one() < EltSize)
208       return false;
209   } else
210     return false;
211 
212   // Okay, we have at least one ~0 value, check to see if the rest match or are
213   // undefs. Even with the above element type twiddling, this should be OK, as
214   // the same type legalization should have applied to all the elements.
215   for (++i; i != e; ++i)
216     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
217       return false;
218   return true;
219 }
220 
221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
222   // Look through a bit convert.
223   while (N->getOpcode() == ISD::BITCAST)
224     N = N->getOperand(0).getNode();
225 
226   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
227     APInt SplatVal;
228     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
229   }
230 
231   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
232 
233   bool IsAllUndef = true;
234   for (const SDValue &Op : N->op_values()) {
235     if (Op.isUndef())
236       continue;
237     IsAllUndef = false;
238     // Do not accept build_vectors that aren't all constants or which have non-0
239     // elements. We have to be a bit careful here, as the type of the constant
240     // may not be the same as the type of the vector elements due to type
241     // legalization (the elements are promoted to a legal type for the target
242     // and a vector of a type may be legal when the base element type is not).
243     // We only want to check enough bits to cover the vector elements, because
244     // we care if the resultant vector is all zeros, not whether the individual
245     // constants are.
246     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
247     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
248       if (CN->getAPIntValue().countr_zero() < EltSize)
249         return false;
250     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
251       if (CFPN->getValueAPF().bitcastToAPInt().countr_zero() < EltSize)
252         return false;
253     } else
254       return false;
255   }
256 
257   // Do not accept an all-undef vector.
258   if (IsAllUndef)
259     return false;
260   return true;
261 }
262 
263 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
264   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
268   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
269 }
270 
271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
272   if (N->getOpcode() != ISD::BUILD_VECTOR)
273     return false;
274 
275   for (const SDValue &Op : N->op_values()) {
276     if (Op.isUndef())
277       continue;
278     if (!isa<ConstantSDNode>(Op))
279       return false;
280   }
281   return true;
282 }
283 
284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
285   if (N->getOpcode() != ISD::BUILD_VECTOR)
286     return false;
287 
288   for (const SDValue &Op : N->op_values()) {
289     if (Op.isUndef())
290       continue;
291     if (!isa<ConstantFPSDNode>(Op))
292       return false;
293   }
294   return true;
295 }
296 
297 bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
298                              bool Signed) {
299   assert(N->getValueType(0).isVector() && "Expected a vector!");
300 
301   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
302   if (EltSize <= NewEltSize)
303     return false;
304 
305   if (N->getOpcode() == ISD::ZERO_EXTEND) {
306     return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
307             NewEltSize) &&
308            !Signed;
309   }
310   if (N->getOpcode() == ISD::SIGN_EXTEND) {
311     return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
312             NewEltSize) &&
313            Signed;
314   }
315   if (N->getOpcode() != ISD::BUILD_VECTOR)
316     return false;
317 
318   for (const SDValue &Op : N->op_values()) {
319     if (Op.isUndef())
320       continue;
321     if (!isa<ConstantSDNode>(Op))
322       return false;
323 
324     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().trunc(EltSize);
325     if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
326       return false;
327     if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
328       return false;
329   }
330 
331   return true;
332 }
333 
334 bool ISD::allOperandsUndef(const SDNode *N) {
335   // Return false if the node has no operands.
336   // This is "logically inconsistent" with the definition of "all" but
337   // is probably the desired behavior.
338   if (N->getNumOperands() == 0)
339     return false;
340   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
341 }
342 
343 bool ISD::isFreezeUndef(const SDNode *N) {
344   return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
345 }
346 
347 bool ISD::matchUnaryPredicate(SDValue Op,
348                               std::function<bool(ConstantSDNode *)> Match,
349                               bool AllowUndefs) {
350   // FIXME: Add support for scalar UNDEF cases?
351   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
352     return Match(Cst);
353 
354   // FIXME: Add support for vector UNDEF cases?
355   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
356       ISD::SPLAT_VECTOR != Op.getOpcode())
357     return false;
358 
359   EVT SVT = Op.getValueType().getScalarType();
360   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
361     if (AllowUndefs && Op.getOperand(i).isUndef()) {
362       if (!Match(nullptr))
363         return false;
364       continue;
365     }
366 
367     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
368     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
369       return false;
370   }
371   return true;
372 }
373 
374 bool ISD::matchBinaryPredicate(
375     SDValue LHS, SDValue RHS,
376     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
377     bool AllowUndefs, bool AllowTypeMismatch) {
378   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
379     return false;
380 
381   // TODO: Add support for scalar UNDEF cases?
382   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
383     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
384       return Match(LHSCst, RHSCst);
385 
386   // TODO: Add support for vector UNDEF cases?
387   if (LHS.getOpcode() != RHS.getOpcode() ||
388       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
389        LHS.getOpcode() != ISD::SPLAT_VECTOR))
390     return false;
391 
392   EVT SVT = LHS.getValueType().getScalarType();
393   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
394     SDValue LHSOp = LHS.getOperand(i);
395     SDValue RHSOp = RHS.getOperand(i);
396     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
397     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
398     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
399     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
400     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
401       return false;
402     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
403                                LHSOp.getValueType() != RHSOp.getValueType()))
404       return false;
405     if (!Match(LHSCst, RHSCst))
406       return false;
407   }
408   return true;
409 }
410 
411 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
412   switch (VecReduceOpcode) {
413   default:
414     llvm_unreachable("Expected VECREDUCE opcode");
415   case ISD::VECREDUCE_FADD:
416   case ISD::VECREDUCE_SEQ_FADD:
417   case ISD::VP_REDUCE_FADD:
418   case ISD::VP_REDUCE_SEQ_FADD:
419     return ISD::FADD;
420   case ISD::VECREDUCE_FMUL:
421   case ISD::VECREDUCE_SEQ_FMUL:
422   case ISD::VP_REDUCE_FMUL:
423   case ISD::VP_REDUCE_SEQ_FMUL:
424     return ISD::FMUL;
425   case ISD::VECREDUCE_ADD:
426   case ISD::VP_REDUCE_ADD:
427     return ISD::ADD;
428   case ISD::VECREDUCE_MUL:
429   case ISD::VP_REDUCE_MUL:
430     return ISD::MUL;
431   case ISD::VECREDUCE_AND:
432   case ISD::VP_REDUCE_AND:
433     return ISD::AND;
434   case ISD::VECREDUCE_OR:
435   case ISD::VP_REDUCE_OR:
436     return ISD::OR;
437   case ISD::VECREDUCE_XOR:
438   case ISD::VP_REDUCE_XOR:
439     return ISD::XOR;
440   case ISD::VECREDUCE_SMAX:
441   case ISD::VP_REDUCE_SMAX:
442     return ISD::SMAX;
443   case ISD::VECREDUCE_SMIN:
444   case ISD::VP_REDUCE_SMIN:
445     return ISD::SMIN;
446   case ISD::VECREDUCE_UMAX:
447   case ISD::VP_REDUCE_UMAX:
448     return ISD::UMAX;
449   case ISD::VECREDUCE_UMIN:
450   case ISD::VP_REDUCE_UMIN:
451     return ISD::UMIN;
452   case ISD::VECREDUCE_FMAX:
453   case ISD::VP_REDUCE_FMAX:
454     return ISD::FMAXNUM;
455   case ISD::VECREDUCE_FMIN:
456   case ISD::VP_REDUCE_FMIN:
457     return ISD::FMINNUM;
458   case ISD::VECREDUCE_FMAXIMUM:
459     return ISD::FMAXIMUM;
460   case ISD::VECREDUCE_FMINIMUM:
461     return ISD::FMINIMUM;
462   }
463 }
464 
465 bool ISD::isVPOpcode(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return false;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
470   case ISD::VPSD:                                                              \
471     return true;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 bool ISD::isVPBinaryOp(unsigned Opcode) {
477   switch (Opcode) {
478   default:
479     break;
480 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
481 #define VP_PROPERTY_BINARYOP return true;
482 #define END_REGISTER_VP_SDNODE(VPSD) break;
483 #include "llvm/IR/VPIntrinsics.def"
484   }
485   return false;
486 }
487 
488 bool ISD::isVPReduction(unsigned Opcode) {
489   switch (Opcode) {
490   default:
491     break;
492 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
493 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
494 #define END_REGISTER_VP_SDNODE(VPSD) break;
495 #include "llvm/IR/VPIntrinsics.def"
496   }
497   return false;
498 }
499 
500 /// The operand position of the vector mask.
501 std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
502   switch (Opcode) {
503   default:
504     return std::nullopt;
505 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
506   case ISD::VPSD:                                                              \
507     return MASKPOS;
508 #include "llvm/IR/VPIntrinsics.def"
509   }
510 }
511 
512 /// The operand position of the explicit vector length parameter.
513 std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
514   switch (Opcode) {
515   default:
516     return std::nullopt;
517 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
518   case ISD::VPSD:                                                              \
519     return EVLPOS;
520 #include "llvm/IR/VPIntrinsics.def"
521   }
522 }
523 
524 std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
525                                                 bool hasFPExcept) {
526   // FIXME: Return strict opcodes in case of fp exceptions.
527   switch (VPOpcode) {
528   default:
529     return std::nullopt;
530 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
531 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
532 #define END_REGISTER_VP_SDNODE(VPOPC) break;
533 #include "llvm/IR/VPIntrinsics.def"
534   }
535   return std::nullopt;
536 }
537 
538 unsigned ISD::getVPForBaseOpcode(unsigned Opcode) {
539   switch (Opcode) {
540   default:
541     llvm_unreachable("can not translate this Opcode to VP.");
542 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
543 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
544 #define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
545 #include "llvm/IR/VPIntrinsics.def"
546   }
547 }
548 
549 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
550   switch (ExtType) {
551   case ISD::EXTLOAD:
552     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
553   case ISD::SEXTLOAD:
554     return ISD::SIGN_EXTEND;
555   case ISD::ZEXTLOAD:
556     return ISD::ZERO_EXTEND;
557   default:
558     break;
559   }
560 
561   llvm_unreachable("Invalid LoadExtType");
562 }
563 
564 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
565   // To perform this operation, we just need to swap the L and G bits of the
566   // operation.
567   unsigned OldL = (Operation >> 2) & 1;
568   unsigned OldG = (Operation >> 1) & 1;
569   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
570                        (OldL << 1) |       // New G bit
571                        (OldG << 2));       // New L bit.
572 }
573 
574 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
575   unsigned Operation = Op;
576   if (isIntegerLike)
577     Operation ^= 7;   // Flip L, G, E bits, but not U.
578   else
579     Operation ^= 15;  // Flip all of the condition bits.
580 
581   if (Operation > ISD::SETTRUE2)
582     Operation &= ~8;  // Don't let N and U bits get set.
583 
584   return ISD::CondCode(Operation);
585 }
586 
587 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
588   return getSetCCInverseImpl(Op, Type.isInteger());
589 }
590 
591 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
592                                                bool isIntegerLike) {
593   return getSetCCInverseImpl(Op, isIntegerLike);
594 }
595 
596 /// For an integer comparison, return 1 if the comparison is a signed operation
597 /// and 2 if the result is an unsigned comparison. Return zero if the operation
598 /// does not depend on the sign of the input (setne and seteq).
599 static int isSignedOp(ISD::CondCode Opcode) {
600   switch (Opcode) {
601   default: llvm_unreachable("Illegal integer setcc operation!");
602   case ISD::SETEQ:
603   case ISD::SETNE: return 0;
604   case ISD::SETLT:
605   case ISD::SETLE:
606   case ISD::SETGT:
607   case ISD::SETGE: return 1;
608   case ISD::SETULT:
609   case ISD::SETULE:
610   case ISD::SETUGT:
611   case ISD::SETUGE: return 2;
612   }
613 }
614 
615 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
616                                        EVT Type) {
617   bool IsInteger = Type.isInteger();
618   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
619     // Cannot fold a signed integer setcc with an unsigned integer setcc.
620     return ISD::SETCC_INVALID;
621 
622   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
623 
624   // If the N and U bits get set, then the resultant comparison DOES suddenly
625   // care about orderedness, and it is true when ordered.
626   if (Op > ISD::SETTRUE2)
627     Op &= ~16;     // Clear the U bit if the N bit is set.
628 
629   // Canonicalize illegal integer setcc's.
630   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
631     Op = ISD::SETNE;
632 
633   return ISD::CondCode(Op);
634 }
635 
636 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
637                                         EVT Type) {
638   bool IsInteger = Type.isInteger();
639   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
640     // Cannot fold a signed setcc with an unsigned setcc.
641     return ISD::SETCC_INVALID;
642 
643   // Combine all of the condition bits.
644   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
645 
646   // Canonicalize illegal integer setcc's.
647   if (IsInteger) {
648     switch (Result) {
649     default: break;
650     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
651     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
652     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
653     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
654     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
655     }
656   }
657 
658   return Result;
659 }
660 
661 //===----------------------------------------------------------------------===//
662 //                           SDNode Profile Support
663 //===----------------------------------------------------------------------===//
664 
665 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
666 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
667   ID.AddInteger(OpC);
668 }
669 
670 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
671 /// solely with their pointer.
672 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
673   ID.AddPointer(VTList.VTs);
674 }
675 
676 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
677 static void AddNodeIDOperands(FoldingSetNodeID &ID,
678                               ArrayRef<SDValue> Ops) {
679   for (const auto &Op : Ops) {
680     ID.AddPointer(Op.getNode());
681     ID.AddInteger(Op.getResNo());
682   }
683 }
684 
685 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
686 static void AddNodeIDOperands(FoldingSetNodeID &ID,
687                               ArrayRef<SDUse> Ops) {
688   for (const auto &Op : Ops) {
689     ID.AddPointer(Op.getNode());
690     ID.AddInteger(Op.getResNo());
691   }
692 }
693 
694 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
695                           SDVTList VTList, ArrayRef<SDValue> OpList) {
696   AddNodeIDOpcode(ID, OpC);
697   AddNodeIDValueTypes(ID, VTList);
698   AddNodeIDOperands(ID, OpList);
699 }
700 
701 /// If this is an SDNode with special info, add this info to the NodeID data.
702 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
703   switch (N->getOpcode()) {
704   case ISD::TargetExternalSymbol:
705   case ISD::ExternalSymbol:
706   case ISD::MCSymbol:
707     llvm_unreachable("Should only be used on nodes with operands");
708   default: break;  // Normal nodes don't need extra info.
709   case ISD::TargetConstant:
710   case ISD::Constant: {
711     const ConstantSDNode *C = cast<ConstantSDNode>(N);
712     ID.AddPointer(C->getConstantIntValue());
713     ID.AddBoolean(C->isOpaque());
714     break;
715   }
716   case ISD::TargetConstantFP:
717   case ISD::ConstantFP:
718     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
719     break;
720   case ISD::TargetGlobalAddress:
721   case ISD::GlobalAddress:
722   case ISD::TargetGlobalTLSAddress:
723   case ISD::GlobalTLSAddress: {
724     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
725     ID.AddPointer(GA->getGlobal());
726     ID.AddInteger(GA->getOffset());
727     ID.AddInteger(GA->getTargetFlags());
728     break;
729   }
730   case ISD::BasicBlock:
731     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
732     break;
733   case ISD::Register:
734     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
735     break;
736   case ISD::RegisterMask:
737     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
738     break;
739   case ISD::SRCVALUE:
740     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
741     break;
742   case ISD::FrameIndex:
743   case ISD::TargetFrameIndex:
744     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
745     break;
746   case ISD::LIFETIME_START:
747   case ISD::LIFETIME_END:
748     if (cast<LifetimeSDNode>(N)->hasOffset()) {
749       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
750       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
751     }
752     break;
753   case ISD::PSEUDO_PROBE:
754     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
755     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
756     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
757     break;
758   case ISD::JumpTable:
759   case ISD::TargetJumpTable:
760     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
761     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
762     break;
763   case ISD::ConstantPool:
764   case ISD::TargetConstantPool: {
765     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
766     ID.AddInteger(CP->getAlign().value());
767     ID.AddInteger(CP->getOffset());
768     if (CP->isMachineConstantPoolEntry())
769       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
770     else
771       ID.AddPointer(CP->getConstVal());
772     ID.AddInteger(CP->getTargetFlags());
773     break;
774   }
775   case ISD::TargetIndex: {
776     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
777     ID.AddInteger(TI->getIndex());
778     ID.AddInteger(TI->getOffset());
779     ID.AddInteger(TI->getTargetFlags());
780     break;
781   }
782   case ISD::LOAD: {
783     const LoadSDNode *LD = cast<LoadSDNode>(N);
784     ID.AddInteger(LD->getMemoryVT().getRawBits());
785     ID.AddInteger(LD->getRawSubclassData());
786     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
787     ID.AddInteger(LD->getMemOperand()->getFlags());
788     break;
789   }
790   case ISD::STORE: {
791     const StoreSDNode *ST = cast<StoreSDNode>(N);
792     ID.AddInteger(ST->getMemoryVT().getRawBits());
793     ID.AddInteger(ST->getRawSubclassData());
794     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
795     ID.AddInteger(ST->getMemOperand()->getFlags());
796     break;
797   }
798   case ISD::VP_LOAD: {
799     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
800     ID.AddInteger(ELD->getMemoryVT().getRawBits());
801     ID.AddInteger(ELD->getRawSubclassData());
802     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
803     ID.AddInteger(ELD->getMemOperand()->getFlags());
804     break;
805   }
806   case ISD::VP_STORE: {
807     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
808     ID.AddInteger(EST->getMemoryVT().getRawBits());
809     ID.AddInteger(EST->getRawSubclassData());
810     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
811     ID.AddInteger(EST->getMemOperand()->getFlags());
812     break;
813   }
814   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
815     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
816     ID.AddInteger(SLD->getMemoryVT().getRawBits());
817     ID.AddInteger(SLD->getRawSubclassData());
818     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
819     break;
820   }
821   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
822     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
823     ID.AddInteger(SST->getMemoryVT().getRawBits());
824     ID.AddInteger(SST->getRawSubclassData());
825     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
826     break;
827   }
828   case ISD::VP_GATHER: {
829     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
830     ID.AddInteger(EG->getMemoryVT().getRawBits());
831     ID.AddInteger(EG->getRawSubclassData());
832     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
833     ID.AddInteger(EG->getMemOperand()->getFlags());
834     break;
835   }
836   case ISD::VP_SCATTER: {
837     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
838     ID.AddInteger(ES->getMemoryVT().getRawBits());
839     ID.AddInteger(ES->getRawSubclassData());
840     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
841     ID.AddInteger(ES->getMemOperand()->getFlags());
842     break;
843   }
844   case ISD::MLOAD: {
845     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
846     ID.AddInteger(MLD->getMemoryVT().getRawBits());
847     ID.AddInteger(MLD->getRawSubclassData());
848     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
849     ID.AddInteger(MLD->getMemOperand()->getFlags());
850     break;
851   }
852   case ISD::MSTORE: {
853     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
854     ID.AddInteger(MST->getMemoryVT().getRawBits());
855     ID.AddInteger(MST->getRawSubclassData());
856     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MST->getMemOperand()->getFlags());
858     break;
859   }
860   case ISD::MGATHER: {
861     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
862     ID.AddInteger(MG->getMemoryVT().getRawBits());
863     ID.AddInteger(MG->getRawSubclassData());
864     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
865     ID.AddInteger(MG->getMemOperand()->getFlags());
866     break;
867   }
868   case ISD::MSCATTER: {
869     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
870     ID.AddInteger(MS->getMemoryVT().getRawBits());
871     ID.AddInteger(MS->getRawSubclassData());
872     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
873     ID.AddInteger(MS->getMemOperand()->getFlags());
874     break;
875   }
876   case ISD::ATOMIC_CMP_SWAP:
877   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
878   case ISD::ATOMIC_SWAP:
879   case ISD::ATOMIC_LOAD_ADD:
880   case ISD::ATOMIC_LOAD_SUB:
881   case ISD::ATOMIC_LOAD_AND:
882   case ISD::ATOMIC_LOAD_CLR:
883   case ISD::ATOMIC_LOAD_OR:
884   case ISD::ATOMIC_LOAD_XOR:
885   case ISD::ATOMIC_LOAD_NAND:
886   case ISD::ATOMIC_LOAD_MIN:
887   case ISD::ATOMIC_LOAD_MAX:
888   case ISD::ATOMIC_LOAD_UMIN:
889   case ISD::ATOMIC_LOAD_UMAX:
890   case ISD::ATOMIC_LOAD:
891   case ISD::ATOMIC_STORE: {
892     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
893     ID.AddInteger(AT->getMemoryVT().getRawBits());
894     ID.AddInteger(AT->getRawSubclassData());
895     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
896     ID.AddInteger(AT->getMemOperand()->getFlags());
897     break;
898   }
899   case ISD::VECTOR_SHUFFLE: {
900     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
901     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
902          i != e; ++i)
903       ID.AddInteger(SVN->getMaskElt(i));
904     break;
905   }
906   case ISD::TargetBlockAddress:
907   case ISD::BlockAddress: {
908     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
909     ID.AddPointer(BA->getBlockAddress());
910     ID.AddInteger(BA->getOffset());
911     ID.AddInteger(BA->getTargetFlags());
912     break;
913   }
914   case ISD::AssertAlign:
915     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
916     break;
917   case ISD::PREFETCH:
918   case ISD::INTRINSIC_VOID:
919   case ISD::INTRINSIC_W_CHAIN:
920     // Handled by MemIntrinsicSDNode check after the switch.
921     break;
922   } // end switch (N->getOpcode())
923 
924   // MemIntrinsic nodes could also have subclass data, address spaces, and flags
925   // to check.
926   if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
927     ID.AddInteger(MN->getRawSubclassData());
928     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
929     ID.AddInteger(MN->getMemOperand()->getFlags());
930     ID.AddInteger(MN->getMemoryVT().getRawBits());
931   }
932 }
933 
934 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
935 /// data.
936 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
937   AddNodeIDOpcode(ID, N->getOpcode());
938   // Add the return value info.
939   AddNodeIDValueTypes(ID, N->getVTList());
940   // Add the operand info.
941   AddNodeIDOperands(ID, N->ops());
942 
943   // Handle SDNode leafs with special info.
944   AddNodeIDCustom(ID, N);
945 }
946 
947 //===----------------------------------------------------------------------===//
948 //                              SelectionDAG Class
949 //===----------------------------------------------------------------------===//
950 
951 /// doNotCSE - Return true if CSE should not be performed for this node.
952 static bool doNotCSE(SDNode *N) {
953   if (N->getValueType(0) == MVT::Glue)
954     return true; // Never CSE anything that produces a flag.
955 
956   switch (N->getOpcode()) {
957   default: break;
958   case ISD::HANDLENODE:
959   case ISD::EH_LABEL:
960     return true;   // Never CSE these nodes.
961   }
962 
963   // Check that remaining values produced are not flags.
964   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
965     if (N->getValueType(i) == MVT::Glue)
966       return true; // Never CSE anything that produces a flag.
967 
968   return false;
969 }
970 
971 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
972 /// SelectionDAG.
973 void SelectionDAG::RemoveDeadNodes() {
974   // Create a dummy node (which is not added to allnodes), that adds a reference
975   // to the root node, preventing it from being deleted.
976   HandleSDNode Dummy(getRoot());
977 
978   SmallVector<SDNode*, 128> DeadNodes;
979 
980   // Add all obviously-dead nodes to the DeadNodes worklist.
981   for (SDNode &Node : allnodes())
982     if (Node.use_empty())
983       DeadNodes.push_back(&Node);
984 
985   RemoveDeadNodes(DeadNodes);
986 
987   // If the root changed (e.g. it was a dead load, update the root).
988   setRoot(Dummy.getValue());
989 }
990 
991 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
992 /// given list, and any nodes that become unreachable as a result.
993 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
994 
995   // Process the worklist, deleting the nodes and adding their uses to the
996   // worklist.
997   while (!DeadNodes.empty()) {
998     SDNode *N = DeadNodes.pop_back_val();
999     // Skip to next node if we've already managed to delete the node. This could
1000     // happen if replacing a node causes a node previously added to the node to
1001     // be deleted.
1002     if (N->getOpcode() == ISD::DELETED_NODE)
1003       continue;
1004 
1005     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1006       DUL->NodeDeleted(N, nullptr);
1007 
1008     // Take the node out of the appropriate CSE map.
1009     RemoveNodeFromCSEMaps(N);
1010 
1011     // Next, brutally remove the operand list.  This is safe to do, as there are
1012     // no cycles in the graph.
1013     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1014       SDUse &Use = *I++;
1015       SDNode *Operand = Use.getNode();
1016       Use.set(SDValue());
1017 
1018       // Now that we removed this operand, see if there are no uses of it left.
1019       if (Operand->use_empty())
1020         DeadNodes.push_back(Operand);
1021     }
1022 
1023     DeallocateNode(N);
1024   }
1025 }
1026 
1027 void SelectionDAG::RemoveDeadNode(SDNode *N){
1028   SmallVector<SDNode*, 16> DeadNodes(1, N);
1029 
1030   // Create a dummy node that adds a reference to the root node, preventing
1031   // it from being deleted.  (This matters if the root is an operand of the
1032   // dead node.)
1033   HandleSDNode Dummy(getRoot());
1034 
1035   RemoveDeadNodes(DeadNodes);
1036 }
1037 
1038 void SelectionDAG::DeleteNode(SDNode *N) {
1039   // First take this out of the appropriate CSE map.
1040   RemoveNodeFromCSEMaps(N);
1041 
1042   // Finally, remove uses due to operands of this node, remove from the
1043   // AllNodes list, and delete the node.
1044   DeleteNodeNotInCSEMaps(N);
1045 }
1046 
1047 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1048   assert(N->getIterator() != AllNodes.begin() &&
1049          "Cannot delete the entry node!");
1050   assert(N->use_empty() && "Cannot delete a node that is not dead!");
1051 
1052   // Drop all of the operands and decrement used node's use counts.
1053   N->DropOperands();
1054 
1055   DeallocateNode(N);
1056 }
1057 
1058 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1059   assert(!(V->isVariadic() && isParameter));
1060   if (isParameter)
1061     ByvalParmDbgValues.push_back(V);
1062   else
1063     DbgValues.push_back(V);
1064   for (const SDNode *Node : V->getSDNodes())
1065     if (Node)
1066       DbgValMap[Node].push_back(V);
1067 }
1068 
1069 void SDDbgInfo::erase(const SDNode *Node) {
1070   DbgValMapType::iterator I = DbgValMap.find(Node);
1071   if (I == DbgValMap.end())
1072     return;
1073   for (auto &Val: I->second)
1074     Val->setIsInvalidated();
1075   DbgValMap.erase(I);
1076 }
1077 
1078 void SelectionDAG::DeallocateNode(SDNode *N) {
1079   // If we have operands, deallocate them.
1080   removeOperands(N);
1081 
1082   NodeAllocator.Deallocate(AllNodes.remove(N));
1083 
1084   // Set the opcode to DELETED_NODE to help catch bugs when node
1085   // memory is reallocated.
1086   // FIXME: There are places in SDag that have grown a dependency on the opcode
1087   // value in the released node.
1088   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1089   N->NodeType = ISD::DELETED_NODE;
1090 
1091   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1092   // them and forget about that node.
1093   DbgInfo->erase(N);
1094 
1095   // Invalidate extra info.
1096   SDEI.erase(N);
1097 }
1098 
1099 #ifndef NDEBUG
1100 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1101 static void VerifySDNode(SDNode *N) {
1102   switch (N->getOpcode()) {
1103   default:
1104     break;
1105   case ISD::BUILD_PAIR: {
1106     EVT VT = N->getValueType(0);
1107     assert(N->getNumValues() == 1 && "Too many results!");
1108     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1109            "Wrong return type!");
1110     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1111     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1112            "Mismatched operand types!");
1113     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1114            "Wrong operand type!");
1115     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1116            "Wrong return type size");
1117     break;
1118   }
1119   case ISD::BUILD_VECTOR: {
1120     assert(N->getNumValues() == 1 && "Too many results!");
1121     assert(N->getValueType(0).isVector() && "Wrong return type!");
1122     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1123            "Wrong number of operands!");
1124     EVT EltVT = N->getValueType(0).getVectorElementType();
1125     for (const SDUse &Op : N->ops()) {
1126       assert((Op.getValueType() == EltVT ||
1127               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1128                EltVT.bitsLE(Op.getValueType()))) &&
1129              "Wrong operand type!");
1130       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1131              "Operands must all have the same type");
1132     }
1133     break;
1134   }
1135   }
1136 }
1137 #endif // NDEBUG
1138 
1139 /// Insert a newly allocated node into the DAG.
1140 ///
1141 /// Handles insertion into the all nodes list and CSE map, as well as
1142 /// verification and other common operations when a new node is allocated.
1143 void SelectionDAG::InsertNode(SDNode *N) {
1144   AllNodes.push_back(N);
1145 #ifndef NDEBUG
1146   N->PersistentId = NextPersistentId++;
1147   VerifySDNode(N);
1148 #endif
1149   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1150     DUL->NodeInserted(N);
1151 }
1152 
1153 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1154 /// correspond to it.  This is useful when we're about to delete or repurpose
1155 /// the node.  We don't want future request for structurally identical nodes
1156 /// to return N anymore.
1157 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1158   bool Erased = false;
1159   switch (N->getOpcode()) {
1160   case ISD::HANDLENODE: return false;  // noop.
1161   case ISD::CONDCODE:
1162     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1163            "Cond code doesn't exist!");
1164     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1165     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1166     break;
1167   case ISD::ExternalSymbol:
1168     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1169     break;
1170   case ISD::TargetExternalSymbol: {
1171     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1172     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1173         ESN->getSymbol(), ESN->getTargetFlags()));
1174     break;
1175   }
1176   case ISD::MCSymbol: {
1177     auto *MCSN = cast<MCSymbolSDNode>(N);
1178     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1179     break;
1180   }
1181   case ISD::VALUETYPE: {
1182     EVT VT = cast<VTSDNode>(N)->getVT();
1183     if (VT.isExtended()) {
1184       Erased = ExtendedValueTypeNodes.erase(VT);
1185     } else {
1186       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1187       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1188     }
1189     break;
1190   }
1191   default:
1192     // Remove it from the CSE Map.
1193     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1194     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1195     Erased = CSEMap.RemoveNode(N);
1196     break;
1197   }
1198 #ifndef NDEBUG
1199   // Verify that the node was actually in one of the CSE maps, unless it has a
1200   // flag result (which cannot be CSE'd) or is one of the special cases that are
1201   // not subject to CSE.
1202   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1203       !N->isMachineOpcode() && !doNotCSE(N)) {
1204     N->dump(this);
1205     dbgs() << "\n";
1206     llvm_unreachable("Node is not in map!");
1207   }
1208 #endif
1209   return Erased;
1210 }
1211 
1212 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1213 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1214 /// node already exists, in which case transfer all its users to the existing
1215 /// node. This transfer can potentially trigger recursive merging.
1216 void
1217 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1218   // For node types that aren't CSE'd, just act as if no identical node
1219   // already exists.
1220   if (!doNotCSE(N)) {
1221     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1222     if (Existing != N) {
1223       // If there was already an existing matching node, use ReplaceAllUsesWith
1224       // to replace the dead one with the existing one.  This can cause
1225       // recursive merging of other unrelated nodes down the line.
1226       ReplaceAllUsesWith(N, Existing);
1227 
1228       // N is now dead. Inform the listeners and delete it.
1229       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1230         DUL->NodeDeleted(N, Existing);
1231       DeleteNodeNotInCSEMaps(N);
1232       return;
1233     }
1234   }
1235 
1236   // If the node doesn't already exist, we updated it.  Inform listeners.
1237   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1238     DUL->NodeUpdated(N);
1239 }
1240 
1241 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1242 /// were replaced with those specified.  If this node is never memoized,
1243 /// return null, otherwise return a pointer to the slot it would take.  If a
1244 /// node already exists with these operands, the slot will be non-null.
1245 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1246                                            void *&InsertPos) {
1247   if (doNotCSE(N))
1248     return nullptr;
1249 
1250   SDValue Ops[] = { Op };
1251   FoldingSetNodeID ID;
1252   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1253   AddNodeIDCustom(ID, N);
1254   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1255   if (Node)
1256     Node->intersectFlagsWith(N->getFlags());
1257   return Node;
1258 }
1259 
1260 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1261 /// were replaced with those specified.  If this node is never memoized,
1262 /// return null, otherwise return a pointer to the slot it would take.  If a
1263 /// node already exists with these operands, the slot will be non-null.
1264 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1265                                            SDValue Op1, SDValue Op2,
1266                                            void *&InsertPos) {
1267   if (doNotCSE(N))
1268     return nullptr;
1269 
1270   SDValue Ops[] = { Op1, Op2 };
1271   FoldingSetNodeID ID;
1272   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1273   AddNodeIDCustom(ID, N);
1274   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1275   if (Node)
1276     Node->intersectFlagsWith(N->getFlags());
1277   return Node;
1278 }
1279 
1280 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1281 /// were replaced with those specified.  If this node is never memoized,
1282 /// return null, otherwise return a pointer to the slot it would take.  If a
1283 /// node already exists with these operands, the slot will be non-null.
1284 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1285                                            void *&InsertPos) {
1286   if (doNotCSE(N))
1287     return nullptr;
1288 
1289   FoldingSetNodeID ID;
1290   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1291   AddNodeIDCustom(ID, N);
1292   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1293   if (Node)
1294     Node->intersectFlagsWith(N->getFlags());
1295   return Node;
1296 }
1297 
1298 Align SelectionDAG::getEVTAlign(EVT VT) const {
1299   Type *Ty = VT == MVT::iPTR ?
1300                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1301                    VT.getTypeForEVT(*getContext());
1302 
1303   return getDataLayout().getABITypeAlign(Ty);
1304 }
1305 
1306 // EntryNode could meaningfully have debug info if we can find it...
1307 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1308     : TM(tm), OptLevel(OL),
1309       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other, MVT::Glue)),
1310       Root(getEntryNode()) {
1311   InsertNode(&EntryNode);
1312   DbgInfo = new SDDbgInfo();
1313 }
1314 
1315 void SelectionDAG::init(MachineFunction &NewMF,
1316                         OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1317                         const TargetLibraryInfo *LibraryInfo,
1318                         UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1319                         BlockFrequencyInfo *BFIin,
1320                         FunctionVarLocs const *VarLocs) {
1321   MF = &NewMF;
1322   SDAGISelPass = PassPtr;
1323   ORE = &NewORE;
1324   TLI = getSubtarget().getTargetLowering();
1325   TSI = getSubtarget().getSelectionDAGInfo();
1326   LibInfo = LibraryInfo;
1327   Context = &MF->getFunction().getContext();
1328   UA = NewUA;
1329   PSI = PSIin;
1330   BFI = BFIin;
1331   FnVarLocs = VarLocs;
1332 }
1333 
1334 SelectionDAG::~SelectionDAG() {
1335   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1336   allnodes_clear();
1337   OperandRecycler.clear(OperandAllocator);
1338   delete DbgInfo;
1339 }
1340 
1341 bool SelectionDAG::shouldOptForSize() const {
1342   return MF->getFunction().hasOptSize() ||
1343       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1344 }
1345 
1346 void SelectionDAG::allnodes_clear() {
1347   assert(&*AllNodes.begin() == &EntryNode);
1348   AllNodes.remove(AllNodes.begin());
1349   while (!AllNodes.empty())
1350     DeallocateNode(&AllNodes.front());
1351 #ifndef NDEBUG
1352   NextPersistentId = 0;
1353 #endif
1354 }
1355 
1356 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1357                                           void *&InsertPos) {
1358   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1359   if (N) {
1360     switch (N->getOpcode()) {
1361     default: break;
1362     case ISD::Constant:
1363     case ISD::ConstantFP:
1364       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1365                        "debug location.  Use another overload.");
1366     }
1367   }
1368   return N;
1369 }
1370 
1371 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1372                                           const SDLoc &DL, void *&InsertPos) {
1373   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1374   if (N) {
1375     switch (N->getOpcode()) {
1376     case ISD::Constant:
1377     case ISD::ConstantFP:
1378       // Erase debug location from the node if the node is used at several
1379       // different places. Do not propagate one location to all uses as it
1380       // will cause a worse single stepping debugging experience.
1381       if (N->getDebugLoc() != DL.getDebugLoc())
1382         N->setDebugLoc(DebugLoc());
1383       break;
1384     default:
1385       // When the node's point of use is located earlier in the instruction
1386       // sequence than its prior point of use, update its debug info to the
1387       // earlier location.
1388       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1389         N->setDebugLoc(DL.getDebugLoc());
1390       break;
1391     }
1392   }
1393   return N;
1394 }
1395 
1396 void SelectionDAG::clear() {
1397   allnodes_clear();
1398   OperandRecycler.clear(OperandAllocator);
1399   OperandAllocator.Reset();
1400   CSEMap.clear();
1401 
1402   ExtendedValueTypeNodes.clear();
1403   ExternalSymbols.clear();
1404   TargetExternalSymbols.clear();
1405   MCSymbols.clear();
1406   SDEI.clear();
1407   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1408             static_cast<CondCodeSDNode*>(nullptr));
1409   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1410             static_cast<SDNode*>(nullptr));
1411 
1412   EntryNode.UseList = nullptr;
1413   InsertNode(&EntryNode);
1414   Root = getEntryNode();
1415   DbgInfo->clear();
1416 }
1417 
1418 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1419   return VT.bitsGT(Op.getValueType())
1420              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1421              : getNode(ISD::FP_ROUND, DL, VT, Op,
1422                        getIntPtrConstant(0, DL, /*isTarget=*/true));
1423 }
1424 
1425 std::pair<SDValue, SDValue>
1426 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1427                                        const SDLoc &DL, EVT VT) {
1428   assert(!VT.bitsEq(Op.getValueType()) &&
1429          "Strict no-op FP extend/round not allowed.");
1430   SDValue Res =
1431       VT.bitsGT(Op.getValueType())
1432           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1433           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1434                     {Chain, Op, getIntPtrConstant(0, DL)});
1435 
1436   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1437 }
1438 
1439 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1440   return VT.bitsGT(Op.getValueType()) ?
1441     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1442     getNode(ISD::TRUNCATE, DL, VT, Op);
1443 }
1444 
1445 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1446   return VT.bitsGT(Op.getValueType()) ?
1447     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1448     getNode(ISD::TRUNCATE, DL, VT, Op);
1449 }
1450 
1451 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1452   return VT.bitsGT(Op.getValueType()) ?
1453     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1454     getNode(ISD::TRUNCATE, DL, VT, Op);
1455 }
1456 
1457 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1458                                         EVT OpVT) {
1459   if (VT.bitsLE(Op.getValueType()))
1460     return getNode(ISD::TRUNCATE, SL, VT, Op);
1461 
1462   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1463   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1464 }
1465 
1466 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1467   EVT OpVT = Op.getValueType();
1468   assert(VT.isInteger() && OpVT.isInteger() &&
1469          "Cannot getZeroExtendInReg FP types");
1470   assert(VT.isVector() == OpVT.isVector() &&
1471          "getZeroExtendInReg type should be vector iff the operand "
1472          "type is vector!");
1473   assert((!VT.isVector() ||
1474           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1475          "Vector element counts must match in getZeroExtendInReg");
1476   assert(VT.bitsLE(OpVT) && "Not extending!");
1477   if (OpVT == VT)
1478     return Op;
1479   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1480                                    VT.getScalarSizeInBits());
1481   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1482 }
1483 
1484 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1485   // Only unsigned pointer semantics are supported right now. In the future this
1486   // might delegate to TLI to check pointer signedness.
1487   return getZExtOrTrunc(Op, DL, VT);
1488 }
1489 
1490 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1491   // Only unsigned pointer semantics are supported right now. In the future this
1492   // might delegate to TLI to check pointer signedness.
1493   return getZeroExtendInReg(Op, DL, VT);
1494 }
1495 
1496 SDValue SelectionDAG::getNegative(SDValue Val, const SDLoc &DL, EVT VT) {
1497   return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1498 }
1499 
1500 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1501 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1502   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1503 }
1504 
1505 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1506   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1507   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1508 }
1509 
1510 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1511                                       SDValue Mask, SDValue EVL, EVT VT) {
1512   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1513   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1514 }
1515 
1516 SDValue SelectionDAG::getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op,
1517                                          SDValue Mask, SDValue EVL) {
1518   return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL);
1519 }
1520 
1521 SDValue SelectionDAG::getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op,
1522                                        SDValue Mask, SDValue EVL) {
1523   if (VT.bitsGT(Op.getValueType()))
1524     return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL);
1525   if (VT.bitsLT(Op.getValueType()))
1526     return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL);
1527   return Op;
1528 }
1529 
1530 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1531                                       EVT OpVT) {
1532   if (!V)
1533     return getConstant(0, DL, VT);
1534 
1535   switch (TLI->getBooleanContents(OpVT)) {
1536   case TargetLowering::ZeroOrOneBooleanContent:
1537   case TargetLowering::UndefinedBooleanContent:
1538     return getConstant(1, DL, VT);
1539   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1540     return getAllOnesConstant(DL, VT);
1541   }
1542   llvm_unreachable("Unexpected boolean content enum!");
1543 }
1544 
1545 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1546                                   bool isT, bool isO) {
1547   EVT EltVT = VT.getScalarType();
1548   assert((EltVT.getSizeInBits() >= 64 ||
1549           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1550          "getConstant with a uint64_t value that doesn't fit in the type!");
1551   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1552 }
1553 
1554 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1555                                   bool isT, bool isO) {
1556   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1557 }
1558 
1559 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1560                                   EVT VT, bool isT, bool isO) {
1561   assert(VT.isInteger() && "Cannot create FP integer constant!");
1562 
1563   EVT EltVT = VT.getScalarType();
1564   const ConstantInt *Elt = &Val;
1565 
1566   // In some cases the vector type is legal but the element type is illegal and
1567   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1568   // inserted value (the type does not need to match the vector element type).
1569   // Any extra bits introduced will be truncated away.
1570   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1571                            TargetLowering::TypePromoteInteger) {
1572     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1573     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1574     Elt = ConstantInt::get(*getContext(), NewVal);
1575   }
1576   // In other cases the element type is illegal and needs to be expanded, for
1577   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1578   // the value into n parts and use a vector type with n-times the elements.
1579   // Then bitcast to the type requested.
1580   // Legalizing constants too early makes the DAGCombiner's job harder so we
1581   // only legalize if the DAG tells us we must produce legal types.
1582   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1583            TLI->getTypeAction(*getContext(), EltVT) ==
1584                TargetLowering::TypeExpandInteger) {
1585     const APInt &NewVal = Elt->getValue();
1586     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1587     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1588 
1589     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1590     if (VT.isScalableVector()) {
1591       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1592              "Can only handle an even split!");
1593       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1594 
1595       SmallVector<SDValue, 2> ScalarParts;
1596       for (unsigned i = 0; i != Parts; ++i)
1597         ScalarParts.push_back(getConstant(
1598             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1599             ViaEltVT, isT, isO));
1600 
1601       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1602     }
1603 
1604     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1605     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1606 
1607     // Check the temporary vector is the correct size. If this fails then
1608     // getTypeToTransformTo() probably returned a type whose size (in bits)
1609     // isn't a power-of-2 factor of the requested type size.
1610     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1611 
1612     SmallVector<SDValue, 2> EltParts;
1613     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1614       EltParts.push_back(getConstant(
1615           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1616           ViaEltVT, isT, isO));
1617 
1618     // EltParts is currently in little endian order. If we actually want
1619     // big-endian order then reverse it now.
1620     if (getDataLayout().isBigEndian())
1621       std::reverse(EltParts.begin(), EltParts.end());
1622 
1623     // The elements must be reversed when the element order is different
1624     // to the endianness of the elements (because the BITCAST is itself a
1625     // vector shuffle in this situation). However, we do not need any code to
1626     // perform this reversal because getConstant() is producing a vector
1627     // splat.
1628     // This situation occurs in MIPS MSA.
1629 
1630     SmallVector<SDValue, 8> Ops;
1631     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1632       llvm::append_range(Ops, EltParts);
1633 
1634     SDValue V =
1635         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1636     return V;
1637   }
1638 
1639   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1640          "APInt size does not match type size!");
1641   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1642   FoldingSetNodeID ID;
1643   AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt);
1644   ID.AddPointer(Elt);
1645   ID.AddBoolean(isO);
1646   void *IP = nullptr;
1647   SDNode *N = nullptr;
1648   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1649     if (!VT.isVector())
1650       return SDValue(N, 0);
1651 
1652   if (!N) {
1653     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1654     CSEMap.InsertNode(N, IP);
1655     InsertNode(N);
1656     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1657   }
1658 
1659   SDValue Result(N, 0);
1660   if (VT.isVector())
1661     Result = getSplat(VT, DL, Result);
1662   return Result;
1663 }
1664 
1665 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1666                                         bool isTarget) {
1667   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1668 }
1669 
1670 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1671                                              const SDLoc &DL, bool LegalTypes) {
1672   assert(VT.isInteger() && "Shift amount is not an integer type!");
1673   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1674   return getConstant(Val, DL, ShiftVT);
1675 }
1676 
1677 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1678                                            bool isTarget) {
1679   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1680 }
1681 
1682 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1683                                     bool isTarget) {
1684   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1685 }
1686 
1687 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1688                                     EVT VT, bool isTarget) {
1689   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1690 
1691   EVT EltVT = VT.getScalarType();
1692 
1693   // Do the map lookup using the actual bit pattern for the floating point
1694   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1695   // we don't have issues with SNANs.
1696   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1697   FoldingSetNodeID ID;
1698   AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt);
1699   ID.AddPointer(&V);
1700   void *IP = nullptr;
1701   SDNode *N = nullptr;
1702   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1703     if (!VT.isVector())
1704       return SDValue(N, 0);
1705 
1706   if (!N) {
1707     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1708     CSEMap.InsertNode(N, IP);
1709     InsertNode(N);
1710   }
1711 
1712   SDValue Result(N, 0);
1713   if (VT.isVector())
1714     Result = getSplat(VT, DL, Result);
1715   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1716   return Result;
1717 }
1718 
1719 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1720                                     bool isTarget) {
1721   EVT EltVT = VT.getScalarType();
1722   if (EltVT == MVT::f32)
1723     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1724   if (EltVT == MVT::f64)
1725     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1726   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1727       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1728     bool Ignored;
1729     APFloat APF = APFloat(Val);
1730     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1731                 &Ignored);
1732     return getConstantFP(APF, DL, VT, isTarget);
1733   }
1734   llvm_unreachable("Unsupported type in getConstantFP");
1735 }
1736 
1737 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1738                                        EVT VT, int64_t Offset, bool isTargetGA,
1739                                        unsigned TargetFlags) {
1740   assert((TargetFlags == 0 || isTargetGA) &&
1741          "Cannot set target flags on target-independent globals");
1742 
1743   // Truncate (with sign-extension) the offset value to the pointer size.
1744   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1745   if (BitWidth < 64)
1746     Offset = SignExtend64(Offset, BitWidth);
1747 
1748   unsigned Opc;
1749   if (GV->isThreadLocal())
1750     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1751   else
1752     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1753 
1754   FoldingSetNodeID ID;
1755   AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
1756   ID.AddPointer(GV);
1757   ID.AddInteger(Offset);
1758   ID.AddInteger(TargetFlags);
1759   void *IP = nullptr;
1760   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1761     return SDValue(E, 0);
1762 
1763   auto *N = newSDNode<GlobalAddressSDNode>(
1764       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1765   CSEMap.InsertNode(N, IP);
1766     InsertNode(N);
1767   return SDValue(N, 0);
1768 }
1769 
1770 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1771   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1772   FoldingSetNodeID ID;
1773   AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
1774   ID.AddInteger(FI);
1775   void *IP = nullptr;
1776   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1777     return SDValue(E, 0);
1778 
1779   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1780   CSEMap.InsertNode(N, IP);
1781   InsertNode(N);
1782   return SDValue(N, 0);
1783 }
1784 
1785 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1786                                    unsigned TargetFlags) {
1787   assert((TargetFlags == 0 || isTarget) &&
1788          "Cannot set target flags on target-independent jump tables");
1789   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1790   FoldingSetNodeID ID;
1791   AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
1792   ID.AddInteger(JTI);
1793   ID.AddInteger(TargetFlags);
1794   void *IP = nullptr;
1795   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1796     return SDValue(E, 0);
1797 
1798   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1799   CSEMap.InsertNode(N, IP);
1800   InsertNode(N);
1801   return SDValue(N, 0);
1802 }
1803 
1804 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1805                                       MaybeAlign Alignment, int Offset,
1806                                       bool isTarget, unsigned TargetFlags) {
1807   assert((TargetFlags == 0 || isTarget) &&
1808          "Cannot set target flags on target-independent globals");
1809   if (!Alignment)
1810     Alignment = shouldOptForSize()
1811                     ? getDataLayout().getABITypeAlign(C->getType())
1812                     : getDataLayout().getPrefTypeAlign(C->getType());
1813   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1814   FoldingSetNodeID ID;
1815   AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
1816   ID.AddInteger(Alignment->value());
1817   ID.AddInteger(Offset);
1818   ID.AddPointer(C);
1819   ID.AddInteger(TargetFlags);
1820   void *IP = nullptr;
1821   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1822     return SDValue(E, 0);
1823 
1824   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1825                                           TargetFlags);
1826   CSEMap.InsertNode(N, IP);
1827   InsertNode(N);
1828   SDValue V = SDValue(N, 0);
1829   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1830   return V;
1831 }
1832 
1833 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1834                                       MaybeAlign Alignment, int Offset,
1835                                       bool isTarget, unsigned TargetFlags) {
1836   assert((TargetFlags == 0 || isTarget) &&
1837          "Cannot set target flags on target-independent globals");
1838   if (!Alignment)
1839     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1840   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1841   FoldingSetNodeID ID;
1842   AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
1843   ID.AddInteger(Alignment->value());
1844   ID.AddInteger(Offset);
1845   C->addSelectionDAGCSEId(ID);
1846   ID.AddInteger(TargetFlags);
1847   void *IP = nullptr;
1848   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1849     return SDValue(E, 0);
1850 
1851   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1852                                           TargetFlags);
1853   CSEMap.InsertNode(N, IP);
1854   InsertNode(N);
1855   return SDValue(N, 0);
1856 }
1857 
1858 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1859                                      unsigned TargetFlags) {
1860   FoldingSetNodeID ID;
1861   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), std::nullopt);
1862   ID.AddInteger(Index);
1863   ID.AddInteger(Offset);
1864   ID.AddInteger(TargetFlags);
1865   void *IP = nullptr;
1866   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1867     return SDValue(E, 0);
1868 
1869   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1870   CSEMap.InsertNode(N, IP);
1871   InsertNode(N);
1872   return SDValue(N, 0);
1873 }
1874 
1875 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1876   FoldingSetNodeID ID;
1877   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), std::nullopt);
1878   ID.AddPointer(MBB);
1879   void *IP = nullptr;
1880   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1881     return SDValue(E, 0);
1882 
1883   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1884   CSEMap.InsertNode(N, IP);
1885   InsertNode(N);
1886   return SDValue(N, 0);
1887 }
1888 
1889 SDValue SelectionDAG::getValueType(EVT VT) {
1890   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1891       ValueTypeNodes.size())
1892     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1893 
1894   SDNode *&N = VT.isExtended() ?
1895     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1896 
1897   if (N) return SDValue(N, 0);
1898   N = newSDNode<VTSDNode>(VT);
1899   InsertNode(N);
1900   return SDValue(N, 0);
1901 }
1902 
1903 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1904   SDNode *&N = ExternalSymbols[Sym];
1905   if (N) return SDValue(N, 0);
1906   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1907   InsertNode(N);
1908   return SDValue(N, 0);
1909 }
1910 
1911 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1912   SDNode *&N = MCSymbols[Sym];
1913   if (N)
1914     return SDValue(N, 0);
1915   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1916   InsertNode(N);
1917   return SDValue(N, 0);
1918 }
1919 
1920 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1921                                               unsigned TargetFlags) {
1922   SDNode *&N =
1923       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1924   if (N) return SDValue(N, 0);
1925   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1926   InsertNode(N);
1927   return SDValue(N, 0);
1928 }
1929 
1930 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1931   if ((unsigned)Cond >= CondCodeNodes.size())
1932     CondCodeNodes.resize(Cond+1);
1933 
1934   if (!CondCodeNodes[Cond]) {
1935     auto *N = newSDNode<CondCodeSDNode>(Cond);
1936     CondCodeNodes[Cond] = N;
1937     InsertNode(N);
1938   }
1939 
1940   return SDValue(CondCodeNodes[Cond], 0);
1941 }
1942 
1943 SDValue SelectionDAG::getVScale(const SDLoc &DL, EVT VT, APInt MulImm,
1944                                 bool ConstantFold) {
1945   assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
1946          "APInt size does not match type size!");
1947 
1948   if (ConstantFold) {
1949     const MachineFunction &MF = getMachineFunction();
1950     auto Attr = MF.getFunction().getFnAttribute(Attribute::VScaleRange);
1951     if (Attr.isValid()) {
1952       unsigned VScaleMin = Attr.getVScaleRangeMin();
1953       if (std::optional<unsigned> VScaleMax = Attr.getVScaleRangeMax())
1954         if (*VScaleMax == VScaleMin)
1955           return getConstant(MulImm * VScaleMin, DL, VT);
1956     }
1957   }
1958 
1959   return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
1960 }
1961 
1962 SDValue SelectionDAG::getElementCount(const SDLoc &DL, EVT VT, ElementCount EC,
1963                                       bool ConstantFold) {
1964   if (EC.isScalable())
1965     return getVScale(DL, VT,
1966                      APInt(VT.getSizeInBits(), EC.getKnownMinValue()));
1967 
1968   return getConstant(EC.getKnownMinValue(), DL, VT);
1969 }
1970 
1971 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1972   APInt One(ResVT.getScalarSizeInBits(), 1);
1973   return getStepVector(DL, ResVT, One);
1974 }
1975 
1976 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1977   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1978   if (ResVT.isScalableVector())
1979     return getNode(
1980         ISD::STEP_VECTOR, DL, ResVT,
1981         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1982 
1983   SmallVector<SDValue, 16> OpsStepConstants;
1984   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1985     OpsStepConstants.push_back(
1986         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1987   return getBuildVector(ResVT, DL, OpsStepConstants);
1988 }
1989 
1990 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1991 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1992 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1993   std::swap(N1, N2);
1994   ShuffleVectorSDNode::commuteMask(M);
1995 }
1996 
1997 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1998                                        SDValue N2, ArrayRef<int> Mask) {
1999   assert(VT.getVectorNumElements() == Mask.size() &&
2000          "Must have the same number of vector elements as mask elements!");
2001   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2002          "Invalid VECTOR_SHUFFLE");
2003 
2004   // Canonicalize shuffle undef, undef -> undef
2005   if (N1.isUndef() && N2.isUndef())
2006     return getUNDEF(VT);
2007 
2008   // Validate that all indices in Mask are within the range of the elements
2009   // input to the shuffle.
2010   int NElts = Mask.size();
2011   assert(llvm::all_of(Mask,
2012                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2013          "Index out of range");
2014 
2015   // Copy the mask so we can do any needed cleanup.
2016   SmallVector<int, 8> MaskVec(Mask);
2017 
2018   // Canonicalize shuffle v, v -> v, undef
2019   if (N1 == N2) {
2020     N2 = getUNDEF(VT);
2021     for (int i = 0; i != NElts; ++i)
2022       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2023   }
2024 
2025   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
2026   if (N1.isUndef())
2027     commuteShuffle(N1, N2, MaskVec);
2028 
2029   if (TLI->hasVectorBlend()) {
2030     // If shuffling a splat, try to blend the splat instead. We do this here so
2031     // that even when this arises during lowering we don't have to re-handle it.
2032     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2033       BitVector UndefElements;
2034       SDValue Splat = BV->getSplatValue(&UndefElements);
2035       if (!Splat)
2036         return;
2037 
2038       for (int i = 0; i < NElts; ++i) {
2039         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2040           continue;
2041 
2042         // If this input comes from undef, mark it as such.
2043         if (UndefElements[MaskVec[i] - Offset]) {
2044           MaskVec[i] = -1;
2045           continue;
2046         }
2047 
2048         // If we can blend a non-undef lane, use that instead.
2049         if (!UndefElements[i])
2050           MaskVec[i] = i + Offset;
2051       }
2052     };
2053     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2054       BlendSplat(N1BV, 0);
2055     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2056       BlendSplat(N2BV, NElts);
2057   }
2058 
2059   // Canonicalize all index into lhs, -> shuffle lhs, undef
2060   // Canonicalize all index into rhs, -> shuffle rhs, undef
2061   bool AllLHS = true, AllRHS = true;
2062   bool N2Undef = N2.isUndef();
2063   for (int i = 0; i != NElts; ++i) {
2064     if (MaskVec[i] >= NElts) {
2065       if (N2Undef)
2066         MaskVec[i] = -1;
2067       else
2068         AllLHS = false;
2069     } else if (MaskVec[i] >= 0) {
2070       AllRHS = false;
2071     }
2072   }
2073   if (AllLHS && AllRHS)
2074     return getUNDEF(VT);
2075   if (AllLHS && !N2Undef)
2076     N2 = getUNDEF(VT);
2077   if (AllRHS) {
2078     N1 = getUNDEF(VT);
2079     commuteShuffle(N1, N2, MaskVec);
2080   }
2081   // Reset our undef status after accounting for the mask.
2082   N2Undef = N2.isUndef();
2083   // Re-check whether both sides ended up undef.
2084   if (N1.isUndef() && N2Undef)
2085     return getUNDEF(VT);
2086 
2087   // If Identity shuffle return that node.
2088   bool Identity = true, AllSame = true;
2089   for (int i = 0; i != NElts; ++i) {
2090     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2091     if (MaskVec[i] != MaskVec[0]) AllSame = false;
2092   }
2093   if (Identity && NElts)
2094     return N1;
2095 
2096   // Shuffling a constant splat doesn't change the result.
2097   if (N2Undef) {
2098     SDValue V = N1;
2099 
2100     // Look through any bitcasts. We check that these don't change the number
2101     // (and size) of elements and just changes their types.
2102     while (V.getOpcode() == ISD::BITCAST)
2103       V = V->getOperand(0);
2104 
2105     // A splat should always show up as a build vector node.
2106     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2107       BitVector UndefElements;
2108       SDValue Splat = BV->getSplatValue(&UndefElements);
2109       // If this is a splat of an undef, shuffling it is also undef.
2110       if (Splat && Splat.isUndef())
2111         return getUNDEF(VT);
2112 
2113       bool SameNumElts =
2114           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2115 
2116       // We only have a splat which can skip shuffles if there is a splatted
2117       // value and no undef lanes rearranged by the shuffle.
2118       if (Splat && UndefElements.none()) {
2119         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2120         // number of elements match or the value splatted is a zero constant.
2121         if (SameNumElts)
2122           return N1;
2123         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2124           if (C->isZero())
2125             return N1;
2126       }
2127 
2128       // If the shuffle itself creates a splat, build the vector directly.
2129       if (AllSame && SameNumElts) {
2130         EVT BuildVT = BV->getValueType(0);
2131         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2132         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2133 
2134         // We may have jumped through bitcasts, so the type of the
2135         // BUILD_VECTOR may not match the type of the shuffle.
2136         if (BuildVT != VT)
2137           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2138         return NewBV;
2139       }
2140     }
2141   }
2142 
2143   FoldingSetNodeID ID;
2144   SDValue Ops[2] = { N1, N2 };
2145   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2146   for (int i = 0; i != NElts; ++i)
2147     ID.AddInteger(MaskVec[i]);
2148 
2149   void* IP = nullptr;
2150   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2151     return SDValue(E, 0);
2152 
2153   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2154   // SDNode doesn't have access to it.  This memory will be "leaked" when
2155   // the node is deallocated, but recovered when the NodeAllocator is released.
2156   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2157   llvm::copy(MaskVec, MaskAlloc);
2158 
2159   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2160                                            dl.getDebugLoc(), MaskAlloc);
2161   createOperands(N, Ops);
2162 
2163   CSEMap.InsertNode(N, IP);
2164   InsertNode(N);
2165   SDValue V = SDValue(N, 0);
2166   NewSDValueDbgMsg(V, "Creating new node: ", this);
2167   return V;
2168 }
2169 
2170 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2171   EVT VT = SV.getValueType(0);
2172   SmallVector<int, 8> MaskVec(SV.getMask());
2173   ShuffleVectorSDNode::commuteMask(MaskVec);
2174 
2175   SDValue Op0 = SV.getOperand(0);
2176   SDValue Op1 = SV.getOperand(1);
2177   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2178 }
2179 
2180 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2181   FoldingSetNodeID ID;
2182   AddNodeIDNode(ID, ISD::Register, getVTList(VT), std::nullopt);
2183   ID.AddInteger(RegNo);
2184   void *IP = nullptr;
2185   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2186     return SDValue(E, 0);
2187 
2188   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2189   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2190   CSEMap.InsertNode(N, IP);
2191   InsertNode(N);
2192   return SDValue(N, 0);
2193 }
2194 
2195 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2196   FoldingSetNodeID ID;
2197   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), std::nullopt);
2198   ID.AddPointer(RegMask);
2199   void *IP = nullptr;
2200   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2201     return SDValue(E, 0);
2202 
2203   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2204   CSEMap.InsertNode(N, IP);
2205   InsertNode(N);
2206   return SDValue(N, 0);
2207 }
2208 
2209 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2210                                  MCSymbol *Label) {
2211   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2212 }
2213 
2214 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2215                                    SDValue Root, MCSymbol *Label) {
2216   FoldingSetNodeID ID;
2217   SDValue Ops[] = { Root };
2218   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2219   ID.AddPointer(Label);
2220   void *IP = nullptr;
2221   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2222     return SDValue(E, 0);
2223 
2224   auto *N =
2225       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2226   createOperands(N, Ops);
2227 
2228   CSEMap.InsertNode(N, IP);
2229   InsertNode(N);
2230   return SDValue(N, 0);
2231 }
2232 
2233 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2234                                       int64_t Offset, bool isTarget,
2235                                       unsigned TargetFlags) {
2236   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2237 
2238   FoldingSetNodeID ID;
2239   AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
2240   ID.AddPointer(BA);
2241   ID.AddInteger(Offset);
2242   ID.AddInteger(TargetFlags);
2243   void *IP = nullptr;
2244   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2245     return SDValue(E, 0);
2246 
2247   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2248   CSEMap.InsertNode(N, IP);
2249   InsertNode(N);
2250   return SDValue(N, 0);
2251 }
2252 
2253 SDValue SelectionDAG::getSrcValue(const Value *V) {
2254   FoldingSetNodeID ID;
2255   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), std::nullopt);
2256   ID.AddPointer(V);
2257 
2258   void *IP = nullptr;
2259   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2260     return SDValue(E, 0);
2261 
2262   auto *N = newSDNode<SrcValueSDNode>(V);
2263   CSEMap.InsertNode(N, IP);
2264   InsertNode(N);
2265   return SDValue(N, 0);
2266 }
2267 
2268 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2269   FoldingSetNodeID ID;
2270   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), std::nullopt);
2271   ID.AddPointer(MD);
2272 
2273   void *IP = nullptr;
2274   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2275     return SDValue(E, 0);
2276 
2277   auto *N = newSDNode<MDNodeSDNode>(MD);
2278   CSEMap.InsertNode(N, IP);
2279   InsertNode(N);
2280   return SDValue(N, 0);
2281 }
2282 
2283 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2284   if (VT == V.getValueType())
2285     return V;
2286 
2287   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2288 }
2289 
2290 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2291                                        unsigned SrcAS, unsigned DestAS) {
2292   SDValue Ops[] = {Ptr};
2293   FoldingSetNodeID ID;
2294   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2295   ID.AddInteger(SrcAS);
2296   ID.AddInteger(DestAS);
2297 
2298   void *IP = nullptr;
2299   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2300     return SDValue(E, 0);
2301 
2302   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2303                                            VT, SrcAS, DestAS);
2304   createOperands(N, Ops);
2305 
2306   CSEMap.InsertNode(N, IP);
2307   InsertNode(N);
2308   return SDValue(N, 0);
2309 }
2310 
2311 SDValue SelectionDAG::getFreeze(SDValue V) {
2312   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2313 }
2314 
2315 /// getShiftAmountOperand - Return the specified value casted to
2316 /// the target's desired shift amount type.
2317 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2318   EVT OpTy = Op.getValueType();
2319   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2320   if (OpTy == ShTy || OpTy.isVector()) return Op;
2321 
2322   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2323 }
2324 
2325 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2326   SDLoc dl(Node);
2327   const TargetLowering &TLI = getTargetLoweringInfo();
2328   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2329   EVT VT = Node->getValueType(0);
2330   SDValue Tmp1 = Node->getOperand(0);
2331   SDValue Tmp2 = Node->getOperand(1);
2332   const MaybeAlign MA(Node->getConstantOperandVal(3));
2333 
2334   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2335                                Tmp2, MachinePointerInfo(V));
2336   SDValue VAList = VAListLoad;
2337 
2338   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2339     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2340                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2341 
2342     VAList =
2343         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2344                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2345   }
2346 
2347   // Increment the pointer, VAList, to the next vaarg
2348   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2349                  getConstant(getDataLayout().getTypeAllocSize(
2350                                                VT.getTypeForEVT(*getContext())),
2351                              dl, VAList.getValueType()));
2352   // Store the incremented VAList to the legalized pointer
2353   Tmp1 =
2354       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2355   // Load the actual argument out of the pointer VAList
2356   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2357 }
2358 
2359 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2360   SDLoc dl(Node);
2361   const TargetLowering &TLI = getTargetLoweringInfo();
2362   // This defaults to loading a pointer from the input and storing it to the
2363   // output, returning the chain.
2364   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2365   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2366   SDValue Tmp1 =
2367       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2368               Node->getOperand(2), MachinePointerInfo(VS));
2369   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2370                   MachinePointerInfo(VD));
2371 }
2372 
2373 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2374   const DataLayout &DL = getDataLayout();
2375   Type *Ty = VT.getTypeForEVT(*getContext());
2376   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2377 
2378   if (TLI->isTypeLegal(VT) || !VT.isVector())
2379     return RedAlign;
2380 
2381   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2382   const Align StackAlign = TFI->getStackAlign();
2383 
2384   // See if we can choose a smaller ABI alignment in cases where it's an
2385   // illegal vector type that will get broken down.
2386   if (RedAlign > StackAlign) {
2387     EVT IntermediateVT;
2388     MVT RegisterVT;
2389     unsigned NumIntermediates;
2390     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2391                                 NumIntermediates, RegisterVT);
2392     Ty = IntermediateVT.getTypeForEVT(*getContext());
2393     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2394     if (RedAlign2 < RedAlign)
2395       RedAlign = RedAlign2;
2396   }
2397 
2398   return RedAlign;
2399 }
2400 
2401 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2402   MachineFrameInfo &MFI = MF->getFrameInfo();
2403   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2404   int StackID = 0;
2405   if (Bytes.isScalable())
2406     StackID = TFI->getStackIDForScalableVectors();
2407   // The stack id gives an indication of whether the object is scalable or
2408   // not, so it's safe to pass in the minimum size here.
2409   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2410                                        false, nullptr, StackID);
2411   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2412 }
2413 
2414 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2415   Type *Ty = VT.getTypeForEVT(*getContext());
2416   Align StackAlign =
2417       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2418   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2419 }
2420 
2421 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2422   TypeSize VT1Size = VT1.getStoreSize();
2423   TypeSize VT2Size = VT2.getStoreSize();
2424   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2425          "Don't know how to choose the maximum size when creating a stack "
2426          "temporary");
2427   TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2428                        ? VT1Size
2429                        : VT2Size;
2430 
2431   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2432   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2433   const DataLayout &DL = getDataLayout();
2434   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2435   return CreateStackTemporary(Bytes, Align);
2436 }
2437 
2438 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2439                                 ISD::CondCode Cond, const SDLoc &dl) {
2440   EVT OpVT = N1.getValueType();
2441 
2442   auto GetUndefBooleanConstant = [&]() {
2443     if (VT.getScalarType() == MVT::i1 ||
2444         TLI->getBooleanContents(OpVT) ==
2445             TargetLowering::UndefinedBooleanContent)
2446       return getUNDEF(VT);
2447     // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2448     // so we cannot use getUNDEF(). Return zero instead.
2449     return getConstant(0, dl, VT);
2450   };
2451 
2452   // These setcc operations always fold.
2453   switch (Cond) {
2454   default: break;
2455   case ISD::SETFALSE:
2456   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2457   case ISD::SETTRUE:
2458   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2459 
2460   case ISD::SETOEQ:
2461   case ISD::SETOGT:
2462   case ISD::SETOGE:
2463   case ISD::SETOLT:
2464   case ISD::SETOLE:
2465   case ISD::SETONE:
2466   case ISD::SETO:
2467   case ISD::SETUO:
2468   case ISD::SETUEQ:
2469   case ISD::SETUNE:
2470     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2471     break;
2472   }
2473 
2474   if (OpVT.isInteger()) {
2475     // For EQ and NE, we can always pick a value for the undef to make the
2476     // predicate pass or fail, so we can return undef.
2477     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2478     // icmp eq/ne X, undef -> undef.
2479     if ((N1.isUndef() || N2.isUndef()) &&
2480         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2481       return GetUndefBooleanConstant();
2482 
2483     // If both operands are undef, we can return undef for int comparison.
2484     // icmp undef, undef -> undef.
2485     if (N1.isUndef() && N2.isUndef())
2486       return GetUndefBooleanConstant();
2487 
2488     // icmp X, X -> true/false
2489     // icmp X, undef -> true/false because undef could be X.
2490     if (N1 == N2)
2491       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2492   }
2493 
2494   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2495     const APInt &C2 = N2C->getAPIntValue();
2496     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2497       const APInt &C1 = N1C->getAPIntValue();
2498 
2499       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2500                              dl, VT, OpVT);
2501     }
2502   }
2503 
2504   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2505   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2506 
2507   if (N1CFP && N2CFP) {
2508     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2509     switch (Cond) {
2510     default: break;
2511     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2512                         return GetUndefBooleanConstant();
2513                       [[fallthrough]];
2514     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2515                                              OpVT);
2516     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2517                         return GetUndefBooleanConstant();
2518                       [[fallthrough]];
2519     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2520                                              R==APFloat::cmpLessThan, dl, VT,
2521                                              OpVT);
2522     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2523                         return GetUndefBooleanConstant();
2524                       [[fallthrough]];
2525     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2526                                              OpVT);
2527     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2528                         return GetUndefBooleanConstant();
2529                       [[fallthrough]];
2530     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2531                                              VT, OpVT);
2532     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2533                         return GetUndefBooleanConstant();
2534                       [[fallthrough]];
2535     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2536                                              R==APFloat::cmpEqual, dl, VT,
2537                                              OpVT);
2538     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2539                         return GetUndefBooleanConstant();
2540                       [[fallthrough]];
2541     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2542                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2543     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2544                                              OpVT);
2545     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2546                                              OpVT);
2547     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2548                                              R==APFloat::cmpEqual, dl, VT,
2549                                              OpVT);
2550     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2551                                              OpVT);
2552     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2553                                              R==APFloat::cmpLessThan, dl, VT,
2554                                              OpVT);
2555     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2556                                              R==APFloat::cmpUnordered, dl, VT,
2557                                              OpVT);
2558     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2559                                              VT, OpVT);
2560     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2561                                              OpVT);
2562     }
2563   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2564     // Ensure that the constant occurs on the RHS.
2565     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2566     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2567       return SDValue();
2568     return getSetCC(dl, VT, N2, N1, SwappedCond);
2569   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2570              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2571     // If an operand is known to be a nan (or undef that could be a nan), we can
2572     // fold it.
2573     // Choosing NaN for the undef will always make unordered comparison succeed
2574     // and ordered comparison fails.
2575     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2576     switch (ISD::getUnorderedFlavor(Cond)) {
2577     default:
2578       llvm_unreachable("Unknown flavor!");
2579     case 0: // Known false.
2580       return getBoolConstant(false, dl, VT, OpVT);
2581     case 1: // Known true.
2582       return getBoolConstant(true, dl, VT, OpVT);
2583     case 2: // Undefined.
2584       return GetUndefBooleanConstant();
2585     }
2586   }
2587 
2588   // Could not fold it.
2589   return SDValue();
2590 }
2591 
2592 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2593 /// use this predicate to simplify operations downstream.
2594 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2595   unsigned BitWidth = Op.getScalarValueSizeInBits();
2596   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2597 }
2598 
2599 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2600 /// this predicate to simplify operations downstream.  Mask is known to be zero
2601 /// for bits that V cannot have.
2602 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2603                                      unsigned Depth) const {
2604   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2605 }
2606 
2607 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2608 /// DemandedElts.  We use this predicate to simplify operations downstream.
2609 /// Mask is known to be zero for bits that V cannot have.
2610 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2611                                      const APInt &DemandedElts,
2612                                      unsigned Depth) const {
2613   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2614 }
2615 
2616 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2617 /// DemandedElts.  We use this predicate to simplify operations downstream.
2618 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2619                                       unsigned Depth /* = 0 */) const {
2620   return computeKnownBits(V, DemandedElts, Depth).isZero();
2621 }
2622 
2623 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2624 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2625                                         unsigned Depth) const {
2626   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2627 }
2628 
2629 APInt SelectionDAG::computeVectorKnownZeroElements(SDValue Op,
2630                                                    const APInt &DemandedElts,
2631                                                    unsigned Depth) const {
2632   EVT VT = Op.getValueType();
2633   assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2634 
2635   unsigned NumElts = VT.getVectorNumElements();
2636   assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2637 
2638   APInt KnownZeroElements = APInt::getZero(NumElts);
2639   for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2640     if (!DemandedElts[EltIdx])
2641       continue; // Don't query elements that are not demanded.
2642     APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2643     if (MaskedVectorIsZero(Op, Mask, Depth))
2644       KnownZeroElements.setBit(EltIdx);
2645   }
2646   return KnownZeroElements;
2647 }
2648 
2649 /// isSplatValue - Return true if the vector V has the same value
2650 /// across all DemandedElts. For scalable vectors, we don't know the
2651 /// number of lanes at compile time.  Instead, we use a 1 bit APInt
2652 /// to represent a conservative value for all lanes; that is, that
2653 /// one bit value is implicitly splatted across all lanes.
2654 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2655                                 APInt &UndefElts, unsigned Depth) const {
2656   unsigned Opcode = V.getOpcode();
2657   EVT VT = V.getValueType();
2658   assert(VT.isVector() && "Vector type expected");
2659   assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2660          "scalable demanded bits are ignored");
2661 
2662   if (!DemandedElts)
2663     return false; // No demanded elts, better to assume we don't know anything.
2664 
2665   if (Depth >= MaxRecursionDepth)
2666     return false; // Limit search depth.
2667 
2668   // Deal with some common cases here that work for both fixed and scalable
2669   // vector types.
2670   switch (Opcode) {
2671   case ISD::SPLAT_VECTOR:
2672     UndefElts = V.getOperand(0).isUndef()
2673                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2674                     : APInt(DemandedElts.getBitWidth(), 0);
2675     return true;
2676   case ISD::ADD:
2677   case ISD::SUB:
2678   case ISD::AND:
2679   case ISD::XOR:
2680   case ISD::OR: {
2681     APInt UndefLHS, UndefRHS;
2682     SDValue LHS = V.getOperand(0);
2683     SDValue RHS = V.getOperand(1);
2684     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2685         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2686       UndefElts = UndefLHS | UndefRHS;
2687       return true;
2688     }
2689     return false;
2690   }
2691   case ISD::ABS:
2692   case ISD::TRUNCATE:
2693   case ISD::SIGN_EXTEND:
2694   case ISD::ZERO_EXTEND:
2695     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2696   default:
2697     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2698         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2699       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
2700                                             Depth);
2701     break;
2702 }
2703 
2704   // We don't support other cases than those above for scalable vectors at
2705   // the moment.
2706   if (VT.isScalableVector())
2707     return false;
2708 
2709   unsigned NumElts = VT.getVectorNumElements();
2710   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2711   UndefElts = APInt::getZero(NumElts);
2712 
2713   switch (Opcode) {
2714   case ISD::BUILD_VECTOR: {
2715     SDValue Scl;
2716     for (unsigned i = 0; i != NumElts; ++i) {
2717       SDValue Op = V.getOperand(i);
2718       if (Op.isUndef()) {
2719         UndefElts.setBit(i);
2720         continue;
2721       }
2722       if (!DemandedElts[i])
2723         continue;
2724       if (Scl && Scl != Op)
2725         return false;
2726       Scl = Op;
2727     }
2728     return true;
2729   }
2730   case ISD::VECTOR_SHUFFLE: {
2731     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2732     APInt DemandedLHS = APInt::getZero(NumElts);
2733     APInt DemandedRHS = APInt::getZero(NumElts);
2734     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2735     for (int i = 0; i != (int)NumElts; ++i) {
2736       int M = Mask[i];
2737       if (M < 0) {
2738         UndefElts.setBit(i);
2739         continue;
2740       }
2741       if (!DemandedElts[i])
2742         continue;
2743       if (M < (int)NumElts)
2744         DemandedLHS.setBit(M);
2745       else
2746         DemandedRHS.setBit(M - NumElts);
2747     }
2748 
2749     // If we aren't demanding either op, assume there's no splat.
2750     // If we are demanding both ops, assume there's no splat.
2751     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2752         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2753       return false;
2754 
2755     // See if the demanded elts of the source op is a splat or we only demand
2756     // one element, which should always be a splat.
2757     // TODO: Handle source ops splats with undefs.
2758     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2759       APInt SrcUndefs;
2760       return (SrcElts.popcount() == 1) ||
2761              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2762               (SrcElts & SrcUndefs).isZero());
2763     };
2764     if (!DemandedLHS.isZero())
2765       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2766     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2767   }
2768   case ISD::EXTRACT_SUBVECTOR: {
2769     // Offset the demanded elts by the subvector index.
2770     SDValue Src = V.getOperand(0);
2771     // We don't support scalable vectors at the moment.
2772     if (Src.getValueType().isScalableVector())
2773       return false;
2774     uint64_t Idx = V.getConstantOperandVal(1);
2775     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2776     APInt UndefSrcElts;
2777     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2778     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2779       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2780       return true;
2781     }
2782     break;
2783   }
2784   case ISD::ANY_EXTEND_VECTOR_INREG:
2785   case ISD::SIGN_EXTEND_VECTOR_INREG:
2786   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2787     // Widen the demanded elts by the src element count.
2788     SDValue Src = V.getOperand(0);
2789     // We don't support scalable vectors at the moment.
2790     if (Src.getValueType().isScalableVector())
2791       return false;
2792     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2793     APInt UndefSrcElts;
2794     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2795     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2796       UndefElts = UndefSrcElts.trunc(NumElts);
2797       return true;
2798     }
2799     break;
2800   }
2801   case ISD::BITCAST: {
2802     SDValue Src = V.getOperand(0);
2803     EVT SrcVT = Src.getValueType();
2804     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2805     unsigned BitWidth = VT.getScalarSizeInBits();
2806 
2807     // Ignore bitcasts from unsupported types.
2808     // TODO: Add fp support?
2809     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2810       break;
2811 
2812     // Bitcast 'small element' vector to 'large element' vector.
2813     if ((BitWidth % SrcBitWidth) == 0) {
2814       // See if each sub element is a splat.
2815       unsigned Scale = BitWidth / SrcBitWidth;
2816       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2817       APInt ScaledDemandedElts =
2818           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2819       for (unsigned I = 0; I != Scale; ++I) {
2820         APInt SubUndefElts;
2821         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2822         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2823         SubDemandedElts &= ScaledDemandedElts;
2824         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2825           return false;
2826         // TODO: Add support for merging sub undef elements.
2827         if (!SubUndefElts.isZero())
2828           return false;
2829       }
2830       return true;
2831     }
2832     break;
2833   }
2834   }
2835 
2836   return false;
2837 }
2838 
2839 /// Helper wrapper to main isSplatValue function.
2840 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2841   EVT VT = V.getValueType();
2842   assert(VT.isVector() && "Vector type expected");
2843 
2844   APInt UndefElts;
2845   // Since the number of lanes in a scalable vector is unknown at compile time,
2846   // we track one bit which is implicitly broadcast to all lanes.  This means
2847   // that all lanes in a scalable vector are considered demanded.
2848   APInt DemandedElts
2849     = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements());
2850   return isSplatValue(V, DemandedElts, UndefElts) &&
2851          (AllowUndefs || !UndefElts);
2852 }
2853 
2854 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2855   V = peekThroughExtractSubvectors(V);
2856 
2857   EVT VT = V.getValueType();
2858   unsigned Opcode = V.getOpcode();
2859   switch (Opcode) {
2860   default: {
2861     APInt UndefElts;
2862     // Since the number of lanes in a scalable vector is unknown at compile time,
2863     // we track one bit which is implicitly broadcast to all lanes.  This means
2864     // that all lanes in a scalable vector are considered demanded.
2865     APInt DemandedElts
2866       = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements());
2867 
2868     if (isSplatValue(V, DemandedElts, UndefElts)) {
2869       if (VT.isScalableVector()) {
2870         // DemandedElts and UndefElts are ignored for scalable vectors, since
2871         // the only supported cases are SPLAT_VECTOR nodes.
2872         SplatIdx = 0;
2873       } else {
2874         // Handle case where all demanded elements are UNDEF.
2875         if (DemandedElts.isSubsetOf(UndefElts)) {
2876           SplatIdx = 0;
2877           return getUNDEF(VT);
2878         }
2879         SplatIdx = (UndefElts & DemandedElts).countr_one();
2880       }
2881       return V;
2882     }
2883     break;
2884   }
2885   case ISD::SPLAT_VECTOR:
2886     SplatIdx = 0;
2887     return V;
2888   case ISD::VECTOR_SHUFFLE: {
2889     assert(!VT.isScalableVector());
2890     // Check if this is a shuffle node doing a splat.
2891     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2892     // getTargetVShiftNode currently struggles without the splat source.
2893     auto *SVN = cast<ShuffleVectorSDNode>(V);
2894     if (!SVN->isSplat())
2895       break;
2896     int Idx = SVN->getSplatIndex();
2897     int NumElts = V.getValueType().getVectorNumElements();
2898     SplatIdx = Idx % NumElts;
2899     return V.getOperand(Idx / NumElts);
2900   }
2901   }
2902 
2903   return SDValue();
2904 }
2905 
2906 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2907   int SplatIdx;
2908   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2909     EVT SVT = SrcVector.getValueType().getScalarType();
2910     EVT LegalSVT = SVT;
2911     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2912       if (!SVT.isInteger())
2913         return SDValue();
2914       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2915       if (LegalSVT.bitsLT(SVT))
2916         return SDValue();
2917     }
2918     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2919                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2920   }
2921   return SDValue();
2922 }
2923 
2924 const APInt *
2925 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2926                                           const APInt &DemandedElts) const {
2927   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2928           V.getOpcode() == ISD::SRA) &&
2929          "Unknown shift node");
2930   unsigned BitWidth = V.getScalarValueSizeInBits();
2931   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2932     // Shifting more than the bitwidth is not valid.
2933     const APInt &ShAmt = SA->getAPIntValue();
2934     if (ShAmt.ult(BitWidth))
2935       return &ShAmt;
2936   }
2937   return nullptr;
2938 }
2939 
2940 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2941     SDValue V, const APInt &DemandedElts) const {
2942   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2943           V.getOpcode() == ISD::SRA) &&
2944          "Unknown shift node");
2945   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2946     return ValidAmt;
2947   unsigned BitWidth = V.getScalarValueSizeInBits();
2948   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2949   if (!BV)
2950     return nullptr;
2951   const APInt *MinShAmt = nullptr;
2952   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2953     if (!DemandedElts[i])
2954       continue;
2955     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2956     if (!SA)
2957       return nullptr;
2958     // Shifting more than the bitwidth is not valid.
2959     const APInt &ShAmt = SA->getAPIntValue();
2960     if (ShAmt.uge(BitWidth))
2961       return nullptr;
2962     if (MinShAmt && MinShAmt->ule(ShAmt))
2963       continue;
2964     MinShAmt = &ShAmt;
2965   }
2966   return MinShAmt;
2967 }
2968 
2969 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2970     SDValue V, const APInt &DemandedElts) const {
2971   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2972           V.getOpcode() == ISD::SRA) &&
2973          "Unknown shift node");
2974   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2975     return ValidAmt;
2976   unsigned BitWidth = V.getScalarValueSizeInBits();
2977   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2978   if (!BV)
2979     return nullptr;
2980   const APInt *MaxShAmt = nullptr;
2981   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2982     if (!DemandedElts[i])
2983       continue;
2984     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2985     if (!SA)
2986       return nullptr;
2987     // Shifting more than the bitwidth is not valid.
2988     const APInt &ShAmt = SA->getAPIntValue();
2989     if (ShAmt.uge(BitWidth))
2990       return nullptr;
2991     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2992       continue;
2993     MaxShAmt = &ShAmt;
2994   }
2995   return MaxShAmt;
2996 }
2997 
2998 /// Determine which bits of Op are known to be either zero or one and return
2999 /// them in Known. For vectors, the known bits are those that are shared by
3000 /// every vector element.
3001 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
3002   EVT VT = Op.getValueType();
3003 
3004   // Since the number of lanes in a scalable vector is unknown at compile time,
3005   // we track one bit which is implicitly broadcast to all lanes.  This means
3006   // that all lanes in a scalable vector are considered demanded.
3007   APInt DemandedElts = VT.isFixedLengthVector()
3008                            ? APInt::getAllOnes(VT.getVectorNumElements())
3009                            : APInt(1, 1);
3010   return computeKnownBits(Op, DemandedElts, Depth);
3011 }
3012 
3013 /// Determine which bits of Op are known to be either zero or one and return
3014 /// them in Known. The DemandedElts argument allows us to only collect the known
3015 /// bits that are shared by the requested vector elements.
3016 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
3017                                          unsigned Depth) const {
3018   unsigned BitWidth = Op.getScalarValueSizeInBits();
3019 
3020   KnownBits Known(BitWidth);   // Don't know anything.
3021 
3022   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3023     // We know all of the bits for a constant!
3024     return KnownBits::makeConstant(C->getAPIntValue());
3025   }
3026   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
3027     // We know all of the bits for a constant fp!
3028     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
3029   }
3030 
3031   if (Depth >= MaxRecursionDepth)
3032     return Known;  // Limit search depth.
3033 
3034   KnownBits Known2;
3035   unsigned NumElts = DemandedElts.getBitWidth();
3036   assert((!Op.getValueType().isFixedLengthVector() ||
3037           NumElts == Op.getValueType().getVectorNumElements()) &&
3038          "Unexpected vector size");
3039 
3040   if (!DemandedElts)
3041     return Known;  // No demanded elts, better to assume we don't know anything.
3042 
3043   unsigned Opcode = Op.getOpcode();
3044   switch (Opcode) {
3045   case ISD::MERGE_VALUES:
3046     return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3047                             Depth + 1);
3048   case ISD::SPLAT_VECTOR: {
3049     SDValue SrcOp = Op.getOperand(0);
3050     assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3051            "Expected SPLAT_VECTOR implicit truncation");
3052     // Implicitly truncate the bits to match the official semantics of
3053     // SPLAT_VECTOR.
3054     Known = computeKnownBits(SrcOp, Depth + 1).trunc(BitWidth);
3055     break;
3056   }
3057   case ISD::BUILD_VECTOR:
3058     assert(!Op.getValueType().isScalableVector());
3059     // Collect the known bits that are shared by every demanded vector element.
3060     Known.Zero.setAllBits(); Known.One.setAllBits();
3061     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3062       if (!DemandedElts[i])
3063         continue;
3064 
3065       SDValue SrcOp = Op.getOperand(i);
3066       Known2 = computeKnownBits(SrcOp, Depth + 1);
3067 
3068       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3069       if (SrcOp.getValueSizeInBits() != BitWidth) {
3070         assert(SrcOp.getValueSizeInBits() > BitWidth &&
3071                "Expected BUILD_VECTOR implicit truncation");
3072         Known2 = Known2.trunc(BitWidth);
3073       }
3074 
3075       // Known bits are the values that are shared by every demanded element.
3076       Known = Known.intersectWith(Known2);
3077 
3078       // If we don't know any bits, early out.
3079       if (Known.isUnknown())
3080         break;
3081     }
3082     break;
3083   case ISD::VECTOR_SHUFFLE: {
3084     assert(!Op.getValueType().isScalableVector());
3085     // Collect the known bits that are shared by every vector element referenced
3086     // by the shuffle.
3087     APInt DemandedLHS, DemandedRHS;
3088     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3089     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3090     if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3091                                 DemandedLHS, DemandedRHS))
3092       break;
3093 
3094     // Known bits are the values that are shared by every demanded element.
3095     Known.Zero.setAllBits(); Known.One.setAllBits();
3096     if (!!DemandedLHS) {
3097       SDValue LHS = Op.getOperand(0);
3098       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3099       Known = Known.intersectWith(Known2);
3100     }
3101     // If we don't know any bits, early out.
3102     if (Known.isUnknown())
3103       break;
3104     if (!!DemandedRHS) {
3105       SDValue RHS = Op.getOperand(1);
3106       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3107       Known = Known.intersectWith(Known2);
3108     }
3109     break;
3110   }
3111   case ISD::VSCALE: {
3112     const Function &F = getMachineFunction().getFunction();
3113     const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3114     Known = getVScaleRange(&F, BitWidth).multiply(Multiplier).toKnownBits();
3115     break;
3116   }
3117   case ISD::CONCAT_VECTORS: {
3118     if (Op.getValueType().isScalableVector())
3119       break;
3120     // Split DemandedElts and test each of the demanded subvectors.
3121     Known.Zero.setAllBits(); Known.One.setAllBits();
3122     EVT SubVectorVT = Op.getOperand(0).getValueType();
3123     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3124     unsigned NumSubVectors = Op.getNumOperands();
3125     for (unsigned i = 0; i != NumSubVectors; ++i) {
3126       APInt DemandedSub =
3127           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3128       if (!!DemandedSub) {
3129         SDValue Sub = Op.getOperand(i);
3130         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3131         Known = Known.intersectWith(Known2);
3132       }
3133       // If we don't know any bits, early out.
3134       if (Known.isUnknown())
3135         break;
3136     }
3137     break;
3138   }
3139   case ISD::INSERT_SUBVECTOR: {
3140     if (Op.getValueType().isScalableVector())
3141       break;
3142     // Demand any elements from the subvector and the remainder from the src its
3143     // inserted into.
3144     SDValue Src = Op.getOperand(0);
3145     SDValue Sub = Op.getOperand(1);
3146     uint64_t Idx = Op.getConstantOperandVal(2);
3147     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3148     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3149     APInt DemandedSrcElts = DemandedElts;
3150     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3151 
3152     Known.One.setAllBits();
3153     Known.Zero.setAllBits();
3154     if (!!DemandedSubElts) {
3155       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3156       if (Known.isUnknown())
3157         break; // early-out.
3158     }
3159     if (!!DemandedSrcElts) {
3160       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3161       Known = Known.intersectWith(Known2);
3162     }
3163     break;
3164   }
3165   case ISD::EXTRACT_SUBVECTOR: {
3166     // Offset the demanded elts by the subvector index.
3167     SDValue Src = Op.getOperand(0);
3168     // Bail until we can represent demanded elements for scalable vectors.
3169     if (Op.getValueType().isScalableVector() || Src.getValueType().isScalableVector())
3170       break;
3171     uint64_t Idx = Op.getConstantOperandVal(1);
3172     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3173     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3174     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3175     break;
3176   }
3177   case ISD::SCALAR_TO_VECTOR: {
3178     if (Op.getValueType().isScalableVector())
3179       break;
3180     // We know about scalar_to_vector as much as we know about it source,
3181     // which becomes the first element of otherwise unknown vector.
3182     if (DemandedElts != 1)
3183       break;
3184 
3185     SDValue N0 = Op.getOperand(0);
3186     Known = computeKnownBits(N0, Depth + 1);
3187     if (N0.getValueSizeInBits() != BitWidth)
3188       Known = Known.trunc(BitWidth);
3189 
3190     break;
3191   }
3192   case ISD::BITCAST: {
3193     if (Op.getValueType().isScalableVector())
3194       break;
3195 
3196     SDValue N0 = Op.getOperand(0);
3197     EVT SubVT = N0.getValueType();
3198     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3199 
3200     // Ignore bitcasts from unsupported types.
3201     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3202       break;
3203 
3204     // Fast handling of 'identity' bitcasts.
3205     if (BitWidth == SubBitWidth) {
3206       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3207       break;
3208     }
3209 
3210     bool IsLE = getDataLayout().isLittleEndian();
3211 
3212     // Bitcast 'small element' vector to 'large element' scalar/vector.
3213     if ((BitWidth % SubBitWidth) == 0) {
3214       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3215 
3216       // Collect known bits for the (larger) output by collecting the known
3217       // bits from each set of sub elements and shift these into place.
3218       // We need to separately call computeKnownBits for each set of
3219       // sub elements as the knownbits for each is likely to be different.
3220       unsigned SubScale = BitWidth / SubBitWidth;
3221       APInt SubDemandedElts(NumElts * SubScale, 0);
3222       for (unsigned i = 0; i != NumElts; ++i)
3223         if (DemandedElts[i])
3224           SubDemandedElts.setBit(i * SubScale);
3225 
3226       for (unsigned i = 0; i != SubScale; ++i) {
3227         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3228                          Depth + 1);
3229         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3230         Known.insertBits(Known2, SubBitWidth * Shifts);
3231       }
3232     }
3233 
3234     // Bitcast 'large element' scalar/vector to 'small element' vector.
3235     if ((SubBitWidth % BitWidth) == 0) {
3236       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3237 
3238       // Collect known bits for the (smaller) output by collecting the known
3239       // bits from the overlapping larger input elements and extracting the
3240       // sub sections we actually care about.
3241       unsigned SubScale = SubBitWidth / BitWidth;
3242       APInt SubDemandedElts =
3243           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3244       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3245 
3246       Known.Zero.setAllBits(); Known.One.setAllBits();
3247       for (unsigned i = 0; i != NumElts; ++i)
3248         if (DemandedElts[i]) {
3249           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3250           unsigned Offset = (Shifts % SubScale) * BitWidth;
3251           Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3252           // If we don't know any bits, early out.
3253           if (Known.isUnknown())
3254             break;
3255         }
3256     }
3257     break;
3258   }
3259   case ISD::AND:
3260     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3261     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3262 
3263     Known &= Known2;
3264     break;
3265   case ISD::OR:
3266     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3267     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3268 
3269     Known |= Known2;
3270     break;
3271   case ISD::XOR:
3272     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3273     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3274 
3275     Known ^= Known2;
3276     break;
3277   case ISD::MUL: {
3278     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3279     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3280     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3281     // TODO: SelfMultiply can be poison, but not undef.
3282     if (SelfMultiply)
3283       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3284           Op.getOperand(0), DemandedElts, false, Depth + 1);
3285     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3286 
3287     // If the multiplication is known not to overflow, the product of a number
3288     // with itself is non-negative. Only do this if we didn't already computed
3289     // the opposite value for the sign bit.
3290     if (Op->getFlags().hasNoSignedWrap() &&
3291         Op.getOperand(0) == Op.getOperand(1) &&
3292         !Known.isNegative())
3293       Known.makeNonNegative();
3294     break;
3295   }
3296   case ISD::MULHU: {
3297     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3298     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3299     Known = KnownBits::mulhu(Known, Known2);
3300     break;
3301   }
3302   case ISD::MULHS: {
3303     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3304     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3305     Known = KnownBits::mulhs(Known, Known2);
3306     break;
3307   }
3308   case ISD::UMUL_LOHI: {
3309     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3310     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3311     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3312     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3313     if (Op.getResNo() == 0)
3314       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3315     else
3316       Known = KnownBits::mulhu(Known, Known2);
3317     break;
3318   }
3319   case ISD::SMUL_LOHI: {
3320     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3321     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3322     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3323     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3324     if (Op.getResNo() == 0)
3325       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3326     else
3327       Known = KnownBits::mulhs(Known, Known2);
3328     break;
3329   }
3330   case ISD::AVGCEILU: {
3331     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3332     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3333     Known = Known.zext(BitWidth + 1);
3334     Known2 = Known2.zext(BitWidth + 1);
3335     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3336     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3337     Known = Known.extractBits(BitWidth, 1);
3338     break;
3339   }
3340   case ISD::SELECT:
3341   case ISD::VSELECT:
3342     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3343     // If we don't know any bits, early out.
3344     if (Known.isUnknown())
3345       break;
3346     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3347 
3348     // Only known if known in both the LHS and RHS.
3349     Known = Known.intersectWith(Known2);
3350     break;
3351   case ISD::SELECT_CC:
3352     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3353     // If we don't know any bits, early out.
3354     if (Known.isUnknown())
3355       break;
3356     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3357 
3358     // Only known if known in both the LHS and RHS.
3359     Known = Known.intersectWith(Known2);
3360     break;
3361   case ISD::SMULO:
3362   case ISD::UMULO:
3363     if (Op.getResNo() != 1)
3364       break;
3365     // The boolean result conforms to getBooleanContents.
3366     // If we know the result of a setcc has the top bits zero, use this info.
3367     // We know that we have an integer-based boolean since these operations
3368     // are only available for integer.
3369     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3370             TargetLowering::ZeroOrOneBooleanContent &&
3371         BitWidth > 1)
3372       Known.Zero.setBitsFrom(1);
3373     break;
3374   case ISD::SETCC:
3375   case ISD::SETCCCARRY:
3376   case ISD::STRICT_FSETCC:
3377   case ISD::STRICT_FSETCCS: {
3378     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3379     // If we know the result of a setcc has the top bits zero, use this info.
3380     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3381             TargetLowering::ZeroOrOneBooleanContent &&
3382         BitWidth > 1)
3383       Known.Zero.setBitsFrom(1);
3384     break;
3385   }
3386   case ISD::SHL:
3387     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3388     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3389     Known = KnownBits::shl(Known, Known2);
3390 
3391     // Minimum shift low bits are known zero.
3392     if (const APInt *ShMinAmt =
3393             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3394       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3395     break;
3396   case ISD::SRL:
3397     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3398     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3399     Known = KnownBits::lshr(Known, Known2);
3400 
3401     // Minimum shift high bits are known zero.
3402     if (const APInt *ShMinAmt =
3403             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3404       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3405     break;
3406   case ISD::SRA:
3407     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3408     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3409     Known = KnownBits::ashr(Known, Known2);
3410     break;
3411   case ISD::FSHL:
3412   case ISD::FSHR:
3413     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3414       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3415 
3416       // For fshl, 0-shift returns the 1st arg.
3417       // For fshr, 0-shift returns the 2nd arg.
3418       if (Amt == 0) {
3419         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3420                                  DemandedElts, Depth + 1);
3421         break;
3422       }
3423 
3424       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3425       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3426       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3427       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3428       if (Opcode == ISD::FSHL) {
3429         Known.One <<= Amt;
3430         Known.Zero <<= Amt;
3431         Known2.One.lshrInPlace(BitWidth - Amt);
3432         Known2.Zero.lshrInPlace(BitWidth - Amt);
3433       } else {
3434         Known.One <<= BitWidth - Amt;
3435         Known.Zero <<= BitWidth - Amt;
3436         Known2.One.lshrInPlace(Amt);
3437         Known2.Zero.lshrInPlace(Amt);
3438       }
3439       Known = Known.unionWith(Known2);
3440     }
3441     break;
3442   case ISD::SHL_PARTS:
3443   case ISD::SRA_PARTS:
3444   case ISD::SRL_PARTS: {
3445     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3446 
3447     // Collect lo/hi source values and concatenate.
3448     unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3449     unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3450     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3451     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3452     Known = Known2.concat(Known);
3453 
3454     // Collect shift amount.
3455     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3456 
3457     if (Opcode == ISD::SHL_PARTS)
3458       Known = KnownBits::shl(Known, Known2);
3459     else if (Opcode == ISD::SRA_PARTS)
3460       Known = KnownBits::ashr(Known, Known2);
3461     else // if (Opcode == ISD::SRL_PARTS)
3462       Known = KnownBits::lshr(Known, Known2);
3463 
3464     // TODO: Minimum shift low/high bits are known zero.
3465 
3466     if (Op.getResNo() == 0)
3467       Known = Known.extractBits(LoBits, 0);
3468     else
3469       Known = Known.extractBits(HiBits, LoBits);
3470     break;
3471   }
3472   case ISD::SIGN_EXTEND_INREG: {
3473     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3474     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3475     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3476     break;
3477   }
3478   case ISD::CTTZ:
3479   case ISD::CTTZ_ZERO_UNDEF: {
3480     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3481     // If we have a known 1, its position is our upper bound.
3482     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3483     unsigned LowBits = llvm::bit_width(PossibleTZ);
3484     Known.Zero.setBitsFrom(LowBits);
3485     break;
3486   }
3487   case ISD::CTLZ:
3488   case ISD::CTLZ_ZERO_UNDEF: {
3489     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3490     // If we have a known 1, its position is our upper bound.
3491     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3492     unsigned LowBits = llvm::bit_width(PossibleLZ);
3493     Known.Zero.setBitsFrom(LowBits);
3494     break;
3495   }
3496   case ISD::CTPOP: {
3497     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3498     // If we know some of the bits are zero, they can't be one.
3499     unsigned PossibleOnes = Known2.countMaxPopulation();
3500     Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3501     break;
3502   }
3503   case ISD::PARITY: {
3504     // Parity returns 0 everywhere but the LSB.
3505     Known.Zero.setBitsFrom(1);
3506     break;
3507   }
3508   case ISD::LOAD: {
3509     LoadSDNode *LD = cast<LoadSDNode>(Op);
3510     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3511     if (ISD::isNON_EXTLoad(LD) && Cst) {
3512       // Determine any common known bits from the loaded constant pool value.
3513       Type *CstTy = Cst->getType();
3514       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3515           !Op.getValueType().isScalableVector()) {
3516         // If its a vector splat, then we can (quickly) reuse the scalar path.
3517         // NOTE: We assume all elements match and none are UNDEF.
3518         if (CstTy->isVectorTy()) {
3519           if (const Constant *Splat = Cst->getSplatValue()) {
3520             Cst = Splat;
3521             CstTy = Cst->getType();
3522           }
3523         }
3524         // TODO - do we need to handle different bitwidths?
3525         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3526           // Iterate across all vector elements finding common known bits.
3527           Known.One.setAllBits();
3528           Known.Zero.setAllBits();
3529           for (unsigned i = 0; i != NumElts; ++i) {
3530             if (!DemandedElts[i])
3531               continue;
3532             if (Constant *Elt = Cst->getAggregateElement(i)) {
3533               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3534                 const APInt &Value = CInt->getValue();
3535                 Known.One &= Value;
3536                 Known.Zero &= ~Value;
3537                 continue;
3538               }
3539               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3540                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3541                 Known.One &= Value;
3542                 Known.Zero &= ~Value;
3543                 continue;
3544               }
3545             }
3546             Known.One.clearAllBits();
3547             Known.Zero.clearAllBits();
3548             break;
3549           }
3550         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3551           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3552             Known = KnownBits::makeConstant(CInt->getValue());
3553           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3554             Known =
3555                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3556           }
3557         }
3558       }
3559     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3560       // If this is a ZEXTLoad and we are looking at the loaded value.
3561       EVT VT = LD->getMemoryVT();
3562       unsigned MemBits = VT.getScalarSizeInBits();
3563       Known.Zero.setBitsFrom(MemBits);
3564     } else if (const MDNode *Ranges = LD->getRanges()) {
3565       EVT VT = LD->getValueType(0);
3566 
3567       // TODO: Handle for extending loads
3568       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3569         if (VT.isVector()) {
3570           // Handle truncation to the first demanded element.
3571           // TODO: Figure out which demanded elements are covered
3572           if (DemandedElts != 1 || !getDataLayout().isLittleEndian())
3573             break;
3574 
3575           // Handle the case where a load has a vector type, but scalar memory
3576           // with an attached range.
3577           EVT MemVT = LD->getMemoryVT();
3578           KnownBits KnownFull(MemVT.getSizeInBits());
3579 
3580           computeKnownBitsFromRangeMetadata(*Ranges, KnownFull);
3581           Known = KnownFull.trunc(BitWidth);
3582         } else
3583           computeKnownBitsFromRangeMetadata(*Ranges, Known);
3584       }
3585     }
3586     break;
3587   }
3588   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3589     if (Op.getValueType().isScalableVector())
3590       break;
3591     EVT InVT = Op.getOperand(0).getValueType();
3592     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3593     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3594     Known = Known.zext(BitWidth);
3595     break;
3596   }
3597   case ISD::ZERO_EXTEND: {
3598     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3599     Known = Known.zext(BitWidth);
3600     break;
3601   }
3602   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3603     if (Op.getValueType().isScalableVector())
3604       break;
3605     EVT InVT = Op.getOperand(0).getValueType();
3606     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3607     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3608     // If the sign bit is known to be zero or one, then sext will extend
3609     // it to the top bits, else it will just zext.
3610     Known = Known.sext(BitWidth);
3611     break;
3612   }
3613   case ISD::SIGN_EXTEND: {
3614     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3615     // If the sign bit is known to be zero or one, then sext will extend
3616     // it to the top bits, else it will just zext.
3617     Known = Known.sext(BitWidth);
3618     break;
3619   }
3620   case ISD::ANY_EXTEND_VECTOR_INREG: {
3621     if (Op.getValueType().isScalableVector())
3622       break;
3623     EVT InVT = Op.getOperand(0).getValueType();
3624     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3625     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3626     Known = Known.anyext(BitWidth);
3627     break;
3628   }
3629   case ISD::ANY_EXTEND: {
3630     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3631     Known = Known.anyext(BitWidth);
3632     break;
3633   }
3634   case ISD::TRUNCATE: {
3635     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3636     Known = Known.trunc(BitWidth);
3637     break;
3638   }
3639   case ISD::AssertZext: {
3640     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3641     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3642     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3643     Known.Zero |= (~InMask);
3644     Known.One  &= (~Known.Zero);
3645     break;
3646   }
3647   case ISD::AssertAlign: {
3648     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3649     assert(LogOfAlign != 0);
3650 
3651     // TODO: Should use maximum with source
3652     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3653     // well as clearing one bits.
3654     Known.Zero.setLowBits(LogOfAlign);
3655     Known.One.clearLowBits(LogOfAlign);
3656     break;
3657   }
3658   case ISD::FGETSIGN:
3659     // All bits are zero except the low bit.
3660     Known.Zero.setBitsFrom(1);
3661     break;
3662   case ISD::ADD:
3663   case ISD::SUB: {
3664     SDNodeFlags Flags = Op.getNode()->getFlags();
3665     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667     Known = KnownBits::computeForAddSub(Op.getOpcode() == ISD::ADD,
3668                                         Flags.hasNoSignedWrap(), Known, Known2);
3669     break;
3670   }
3671   case ISD::USUBO:
3672   case ISD::SSUBO:
3673   case ISD::USUBO_CARRY:
3674   case ISD::SSUBO_CARRY:
3675     if (Op.getResNo() == 1) {
3676       // If we know the result of a setcc has the top bits zero, use this info.
3677       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3678               TargetLowering::ZeroOrOneBooleanContent &&
3679           BitWidth > 1)
3680         Known.Zero.setBitsFrom(1);
3681       break;
3682     }
3683     [[fallthrough]];
3684   case ISD::SUBC: {
3685     assert(Op.getResNo() == 0 &&
3686            "We only compute knownbits for the difference here.");
3687 
3688     // TODO: Compute influence of the carry operand.
3689     if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY)
3690       break;
3691 
3692     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3693     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3694     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3695                                         Known, Known2);
3696     break;
3697   }
3698   case ISD::UADDO:
3699   case ISD::SADDO:
3700   case ISD::UADDO_CARRY:
3701   case ISD::SADDO_CARRY:
3702     if (Op.getResNo() == 1) {
3703       // If we know the result of a setcc has the top bits zero, use this info.
3704       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3705               TargetLowering::ZeroOrOneBooleanContent &&
3706           BitWidth > 1)
3707         Known.Zero.setBitsFrom(1);
3708       break;
3709     }
3710     [[fallthrough]];
3711   case ISD::ADDC:
3712   case ISD::ADDE: {
3713     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3714 
3715     // With ADDE and UADDO_CARRY, a carry bit may be added in.
3716     KnownBits Carry(1);
3717     if (Opcode == ISD::ADDE)
3718       // Can't track carry from glue, set carry to unknown.
3719       Carry.resetAll();
3720     else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY)
3721       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3722       // the trouble (how often will we find a known carry bit). And I haven't
3723       // tested this very much yet, but something like this might work:
3724       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3725       //   Carry = Carry.zextOrTrunc(1, false);
3726       Carry.resetAll();
3727     else
3728       Carry.setAllZero();
3729 
3730     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3731     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3732     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3733     break;
3734   }
3735   case ISD::UDIV: {
3736     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3737     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3738     Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
3739     break;
3740   }
3741   case ISD::SDIV: {
3742     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3743     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3744     Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
3745     break;
3746   }
3747   case ISD::SREM: {
3748     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3749     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3750     Known = KnownBits::srem(Known, Known2);
3751     break;
3752   }
3753   case ISD::UREM: {
3754     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3755     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3756     Known = KnownBits::urem(Known, Known2);
3757     break;
3758   }
3759   case ISD::EXTRACT_ELEMENT: {
3760     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3761     const unsigned Index = Op.getConstantOperandVal(1);
3762     const unsigned EltBitWidth = Op.getValueSizeInBits();
3763 
3764     // Remove low part of known bits mask
3765     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3766     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3767 
3768     // Remove high part of known bit mask
3769     Known = Known.trunc(EltBitWidth);
3770     break;
3771   }
3772   case ISD::EXTRACT_VECTOR_ELT: {
3773     SDValue InVec = Op.getOperand(0);
3774     SDValue EltNo = Op.getOperand(1);
3775     EVT VecVT = InVec.getValueType();
3776     // computeKnownBits not yet implemented for scalable vectors.
3777     if (VecVT.isScalableVector())
3778       break;
3779     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3780     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3781 
3782     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3783     // anything about the extended bits.
3784     if (BitWidth > EltBitWidth)
3785       Known = Known.trunc(EltBitWidth);
3786 
3787     // If we know the element index, just demand that vector element, else for
3788     // an unknown element index, ignore DemandedElts and demand them all.
3789     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3790     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3791     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3792       DemandedSrcElts =
3793           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3794 
3795     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3796     if (BitWidth > EltBitWidth)
3797       Known = Known.anyext(BitWidth);
3798     break;
3799   }
3800   case ISD::INSERT_VECTOR_ELT: {
3801     if (Op.getValueType().isScalableVector())
3802       break;
3803 
3804     // If we know the element index, split the demand between the
3805     // source vector and the inserted element, otherwise assume we need
3806     // the original demanded vector elements and the value.
3807     SDValue InVec = Op.getOperand(0);
3808     SDValue InVal = Op.getOperand(1);
3809     SDValue EltNo = Op.getOperand(2);
3810     bool DemandedVal = true;
3811     APInt DemandedVecElts = DemandedElts;
3812     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3813     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3814       unsigned EltIdx = CEltNo->getZExtValue();
3815       DemandedVal = !!DemandedElts[EltIdx];
3816       DemandedVecElts.clearBit(EltIdx);
3817     }
3818     Known.One.setAllBits();
3819     Known.Zero.setAllBits();
3820     if (DemandedVal) {
3821       Known2 = computeKnownBits(InVal, Depth + 1);
3822       Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
3823     }
3824     if (!!DemandedVecElts) {
3825       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3826       Known = Known.intersectWith(Known2);
3827     }
3828     break;
3829   }
3830   case ISD::BITREVERSE: {
3831     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3832     Known = Known2.reverseBits();
3833     break;
3834   }
3835   case ISD::BSWAP: {
3836     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3837     Known = Known2.byteSwap();
3838     break;
3839   }
3840   case ISD::ABS: {
3841     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3842     Known = Known2.abs();
3843     break;
3844   }
3845   case ISD::USUBSAT: {
3846     // The result of usubsat will never be larger than the LHS.
3847     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3848     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3849     break;
3850   }
3851   case ISD::UMIN: {
3852     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3853     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3854     Known = KnownBits::umin(Known, Known2);
3855     break;
3856   }
3857   case ISD::UMAX: {
3858     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3859     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3860     Known = KnownBits::umax(Known, Known2);
3861     break;
3862   }
3863   case ISD::SMIN:
3864   case ISD::SMAX: {
3865     // If we have a clamp pattern, we know that the number of sign bits will be
3866     // the minimum of the clamp min/max range.
3867     bool IsMax = (Opcode == ISD::SMAX);
3868     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3869     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3870       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3871         CstHigh =
3872             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3873     if (CstLow && CstHigh) {
3874       if (!IsMax)
3875         std::swap(CstLow, CstHigh);
3876 
3877       const APInt &ValueLow = CstLow->getAPIntValue();
3878       const APInt &ValueHigh = CstHigh->getAPIntValue();
3879       if (ValueLow.sle(ValueHigh)) {
3880         unsigned LowSignBits = ValueLow.getNumSignBits();
3881         unsigned HighSignBits = ValueHigh.getNumSignBits();
3882         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3883         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3884           Known.One.setHighBits(MinSignBits);
3885           break;
3886         }
3887         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3888           Known.Zero.setHighBits(MinSignBits);
3889           break;
3890         }
3891       }
3892     }
3893 
3894     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3895     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3896     if (IsMax)
3897       Known = KnownBits::smax(Known, Known2);
3898     else
3899       Known = KnownBits::smin(Known, Known2);
3900 
3901     // For SMAX, if CstLow is non-negative we know the result will be
3902     // non-negative and thus all sign bits are 0.
3903     // TODO: There's an equivalent of this for smin with negative constant for
3904     // known ones.
3905     if (IsMax && CstLow) {
3906       const APInt &ValueLow = CstLow->getAPIntValue();
3907       if (ValueLow.isNonNegative()) {
3908         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3909         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3910       }
3911     }
3912 
3913     break;
3914   }
3915   case ISD::FP_TO_UINT_SAT: {
3916     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3917     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3918     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3919     break;
3920   }
3921   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3922     if (Op.getResNo() == 1) {
3923       // The boolean result conforms to getBooleanContents.
3924       // If we know the result of a setcc has the top bits zero, use this info.
3925       // We know that we have an integer-based boolean since these operations
3926       // are only available for integer.
3927       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3928               TargetLowering::ZeroOrOneBooleanContent &&
3929           BitWidth > 1)
3930         Known.Zero.setBitsFrom(1);
3931       break;
3932     }
3933     [[fallthrough]];
3934   case ISD::ATOMIC_CMP_SWAP:
3935   case ISD::ATOMIC_SWAP:
3936   case ISD::ATOMIC_LOAD_ADD:
3937   case ISD::ATOMIC_LOAD_SUB:
3938   case ISD::ATOMIC_LOAD_AND:
3939   case ISD::ATOMIC_LOAD_CLR:
3940   case ISD::ATOMIC_LOAD_OR:
3941   case ISD::ATOMIC_LOAD_XOR:
3942   case ISD::ATOMIC_LOAD_NAND:
3943   case ISD::ATOMIC_LOAD_MIN:
3944   case ISD::ATOMIC_LOAD_MAX:
3945   case ISD::ATOMIC_LOAD_UMIN:
3946   case ISD::ATOMIC_LOAD_UMAX:
3947   case ISD::ATOMIC_LOAD: {
3948     unsigned MemBits =
3949         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3950     // If we are looking at the loaded value.
3951     if (Op.getResNo() == 0) {
3952       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3953         Known.Zero.setBitsFrom(MemBits);
3954     }
3955     break;
3956   }
3957   case ISD::FrameIndex:
3958   case ISD::TargetFrameIndex:
3959     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3960                                        Known, getMachineFunction());
3961     break;
3962 
3963   default:
3964     if (Opcode < ISD::BUILTIN_OP_END)
3965       break;
3966     [[fallthrough]];
3967   case ISD::INTRINSIC_WO_CHAIN:
3968   case ISD::INTRINSIC_W_CHAIN:
3969   case ISD::INTRINSIC_VOID:
3970     // TODO: Probably okay to remove after audit; here to reduce change size
3971     // in initial enablement patch for scalable vectors
3972     if (Op.getValueType().isScalableVector())
3973       break;
3974 
3975     // Allow the target to implement this method for its nodes.
3976     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3977     break;
3978   }
3979 
3980   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3981   return Known;
3982 }
3983 
3984 /// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
3985 static SelectionDAG::OverflowKind mapOverflowResult(ConstantRange::OverflowResult OR) {
3986   switch (OR) {
3987   case ConstantRange::OverflowResult::MayOverflow:
3988     return SelectionDAG::OFK_Sometime;
3989   case ConstantRange::OverflowResult::AlwaysOverflowsLow:
3990   case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
3991     return SelectionDAG::OFK_Always;
3992   case ConstantRange::OverflowResult::NeverOverflows:
3993     return SelectionDAG::OFK_Never;
3994   }
3995   llvm_unreachable("Unknown OverflowResult");
3996 }
3997 
3998 SelectionDAG::OverflowKind
3999 SelectionDAG::computeOverflowForSignedAdd(SDValue N0, SDValue N1) const {
4000   // X + 0 never overflow
4001   if (isNullConstant(N1))
4002     return OFK_Never;
4003 
4004   // If both operands each have at least two sign bits, the addition
4005   // cannot overflow.
4006   if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4007     return OFK_Never;
4008 
4009   // TODO: Add ConstantRange::signedAddMayOverflow handling.
4010   return OFK_Sometime;
4011 }
4012 
4013 SelectionDAG::OverflowKind
4014 SelectionDAG::computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const {
4015   // X + 0 never overflow
4016   if (isNullConstant(N1))
4017     return OFK_Never;
4018 
4019   // mulhi + 1 never overflow
4020   KnownBits N1Known = computeKnownBits(N1);
4021   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4022       N1Known.getMaxValue().ult(2))
4023     return OFK_Never;
4024 
4025   KnownBits N0Known = computeKnownBits(N0);
4026   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4027       N0Known.getMaxValue().ult(2))
4028     return OFK_Never;
4029 
4030   // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4031   ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4032   ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4033   return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4034 }
4035 
4036 SelectionDAG::OverflowKind
4037 SelectionDAG::computeOverflowForSignedSub(SDValue N0, SDValue N1) const {
4038   // X - 0 never overflow
4039   if (isNullConstant(N1))
4040     return OFK_Never;
4041 
4042   // If both operands each have at least two sign bits, the subtraction
4043   // cannot overflow.
4044   if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4045     return OFK_Never;
4046 
4047   // TODO: Add ConstantRange::signedSubMayOverflow handling.
4048   return OFK_Sometime;
4049 }
4050 
4051 SelectionDAG::OverflowKind
4052 SelectionDAG::computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const {
4053   // X - 0 never overflow
4054   if (isNullConstant(N1))
4055     return OFK_Never;
4056 
4057   // TODO: Add ConstantRange::unsignedSubMayOverflow handling.
4058   return OFK_Sometime;
4059 }
4060 
4061 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val, unsigned Depth) const {
4062   if (Depth >= MaxRecursionDepth)
4063     return false; // Limit search depth.
4064 
4065   EVT OpVT = Val.getValueType();
4066   unsigned BitWidth = OpVT.getScalarSizeInBits();
4067 
4068   // Is the constant a known power of 2?
4069   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
4070     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
4071 
4072   // A left-shift of a constant one will have exactly one bit set because
4073   // shifting the bit off the end is undefined.
4074   if (Val.getOpcode() == ISD::SHL) {
4075     auto *C = isConstOrConstSplat(Val.getOperand(0));
4076     if (C && C->getAPIntValue() == 1)
4077       return true;
4078   }
4079 
4080   // Similarly, a logical right-shift of a constant sign-bit will have exactly
4081   // one bit set.
4082   if (Val.getOpcode() == ISD::SRL) {
4083     auto *C = isConstOrConstSplat(Val.getOperand(0));
4084     if (C && C->getAPIntValue().isSignMask())
4085       return true;
4086   }
4087 
4088   // Are all operands of a build vector constant powers of two?
4089   if (Val.getOpcode() == ISD::BUILD_VECTOR)
4090     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
4091           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
4092             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
4093           return false;
4094         }))
4095       return true;
4096 
4097   // Is the operand of a splat vector a constant power of two?
4098   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
4099     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
4100       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
4101         return true;
4102 
4103   // vscale(power-of-two) is a power-of-two for some targets
4104   if (Val.getOpcode() == ISD::VSCALE &&
4105       getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
4106       isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1))
4107     return true;
4108 
4109   // More could be done here, though the above checks are enough
4110   // to handle some common cases.
4111   return false;
4112 }
4113 
4114 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
4115   EVT VT = Op.getValueType();
4116 
4117   // Since the number of lanes in a scalable vector is unknown at compile time,
4118   // we track one bit which is implicitly broadcast to all lanes.  This means
4119   // that all lanes in a scalable vector are considered demanded.
4120   APInt DemandedElts = VT.isFixedLengthVector()
4121                            ? APInt::getAllOnes(VT.getVectorNumElements())
4122                            : APInt(1, 1);
4123   return ComputeNumSignBits(Op, DemandedElts, Depth);
4124 }
4125 
4126 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4127                                           unsigned Depth) const {
4128   EVT VT = Op.getValueType();
4129   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4130   unsigned VTBits = VT.getScalarSizeInBits();
4131   unsigned NumElts = DemandedElts.getBitWidth();
4132   unsigned Tmp, Tmp2;
4133   unsigned FirstAnswer = 1;
4134 
4135   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4136     const APInt &Val = C->getAPIntValue();
4137     return Val.getNumSignBits();
4138   }
4139 
4140   if (Depth >= MaxRecursionDepth)
4141     return 1;  // Limit search depth.
4142 
4143   if (!DemandedElts)
4144     return 1;  // No demanded elts, better to assume we don't know anything.
4145 
4146   unsigned Opcode = Op.getOpcode();
4147   switch (Opcode) {
4148   default: break;
4149   case ISD::AssertSext:
4150     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4151     return VTBits-Tmp+1;
4152   case ISD::AssertZext:
4153     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4154     return VTBits-Tmp;
4155   case ISD::MERGE_VALUES:
4156     return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4157                               Depth + 1);
4158   case ISD::SPLAT_VECTOR: {
4159     // Check if the sign bits of source go down as far as the truncated value.
4160     unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4161     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4162     if (NumSrcSignBits > (NumSrcBits - VTBits))
4163       return NumSrcSignBits - (NumSrcBits - VTBits);
4164     break;
4165   }
4166   case ISD::BUILD_VECTOR:
4167     assert(!VT.isScalableVector());
4168     Tmp = VTBits;
4169     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4170       if (!DemandedElts[i])
4171         continue;
4172 
4173       SDValue SrcOp = Op.getOperand(i);
4174       // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4175       // for constant nodes to ensure we only look at the sign bits.
4176       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SrcOp)) {
4177         APInt T = C->getAPIntValue().trunc(VTBits);
4178         Tmp2 = T.getNumSignBits();
4179       } else {
4180         Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4181 
4182         if (SrcOp.getValueSizeInBits() != VTBits) {
4183           assert(SrcOp.getValueSizeInBits() > VTBits &&
4184                  "Expected BUILD_VECTOR implicit truncation");
4185           unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4186           Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4187         }
4188       }
4189       Tmp = std::min(Tmp, Tmp2);
4190     }
4191     return Tmp;
4192 
4193   case ISD::VECTOR_SHUFFLE: {
4194     // Collect the minimum number of sign bits that are shared by every vector
4195     // element referenced by the shuffle.
4196     APInt DemandedLHS, DemandedRHS;
4197     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4198     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4199     if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4200                                 DemandedLHS, DemandedRHS))
4201       return 1;
4202 
4203     Tmp = std::numeric_limits<unsigned>::max();
4204     if (!!DemandedLHS)
4205       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
4206     if (!!DemandedRHS) {
4207       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
4208       Tmp = std::min(Tmp, Tmp2);
4209     }
4210     // If we don't know anything, early out and try computeKnownBits fall-back.
4211     if (Tmp == 1)
4212       break;
4213     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4214     return Tmp;
4215   }
4216 
4217   case ISD::BITCAST: {
4218     if (VT.isScalableVector())
4219       break;
4220     SDValue N0 = Op.getOperand(0);
4221     EVT SrcVT = N0.getValueType();
4222     unsigned SrcBits = SrcVT.getScalarSizeInBits();
4223 
4224     // Ignore bitcasts from unsupported types..
4225     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
4226       break;
4227 
4228     // Fast handling of 'identity' bitcasts.
4229     if (VTBits == SrcBits)
4230       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
4231 
4232     bool IsLE = getDataLayout().isLittleEndian();
4233 
4234     // Bitcast 'large element' scalar/vector to 'small element' vector.
4235     if ((SrcBits % VTBits) == 0) {
4236       assert(VT.isVector() && "Expected bitcast to vector");
4237 
4238       unsigned Scale = SrcBits / VTBits;
4239       APInt SrcDemandedElts =
4240           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
4241 
4242       // Fast case - sign splat can be simply split across the small elements.
4243       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
4244       if (Tmp == SrcBits)
4245         return VTBits;
4246 
4247       // Slow case - determine how far the sign extends into each sub-element.
4248       Tmp2 = VTBits;
4249       for (unsigned i = 0; i != NumElts; ++i)
4250         if (DemandedElts[i]) {
4251           unsigned SubOffset = i % Scale;
4252           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4253           SubOffset = SubOffset * VTBits;
4254           if (Tmp <= SubOffset)
4255             return 1;
4256           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4257         }
4258       return Tmp2;
4259     }
4260     break;
4261   }
4262 
4263   case ISD::FP_TO_SINT_SAT:
4264     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4265     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4266     return VTBits - Tmp + 1;
4267   case ISD::SIGN_EXTEND:
4268     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4269     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4270   case ISD::SIGN_EXTEND_INREG:
4271     // Max of the input and what this extends.
4272     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4273     Tmp = VTBits-Tmp+1;
4274     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4275     return std::max(Tmp, Tmp2);
4276   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4277     if (VT.isScalableVector())
4278       break;
4279     SDValue Src = Op.getOperand(0);
4280     EVT SrcVT = Src.getValueType();
4281     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4282     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4283     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4284   }
4285   case ISD::SRA:
4286     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4287     // SRA X, C -> adds C sign bits.
4288     if (const APInt *ShAmt =
4289             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4290       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4291     return Tmp;
4292   case ISD::SHL:
4293     if (const APInt *ShAmt =
4294             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4295       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4296       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4297       if (ShAmt->ult(Tmp))
4298         return Tmp - ShAmt->getZExtValue();
4299     }
4300     break;
4301   case ISD::AND:
4302   case ISD::OR:
4303   case ISD::XOR:    // NOT is handled here.
4304     // Logical binary ops preserve the number of sign bits at the worst.
4305     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4306     if (Tmp != 1) {
4307       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4308       FirstAnswer = std::min(Tmp, Tmp2);
4309       // We computed what we know about the sign bits as our first
4310       // answer. Now proceed to the generic code that uses
4311       // computeKnownBits, and pick whichever answer is better.
4312     }
4313     break;
4314 
4315   case ISD::SELECT:
4316   case ISD::VSELECT:
4317     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4318     if (Tmp == 1) return 1;  // Early out.
4319     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4320     return std::min(Tmp, Tmp2);
4321   case ISD::SELECT_CC:
4322     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4323     if (Tmp == 1) return 1;  // Early out.
4324     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4325     return std::min(Tmp, Tmp2);
4326 
4327   case ISD::SMIN:
4328   case ISD::SMAX: {
4329     // If we have a clamp pattern, we know that the number of sign bits will be
4330     // the minimum of the clamp min/max range.
4331     bool IsMax = (Opcode == ISD::SMAX);
4332     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4333     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4334       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4335         CstHigh =
4336             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4337     if (CstLow && CstHigh) {
4338       if (!IsMax)
4339         std::swap(CstLow, CstHigh);
4340       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4341         Tmp = CstLow->getAPIntValue().getNumSignBits();
4342         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4343         return std::min(Tmp, Tmp2);
4344       }
4345     }
4346 
4347     // Fallback - just get the minimum number of sign bits of the operands.
4348     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4349     if (Tmp == 1)
4350       return 1;  // Early out.
4351     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4352     return std::min(Tmp, Tmp2);
4353   }
4354   case ISD::UMIN:
4355   case ISD::UMAX:
4356     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4357     if (Tmp == 1)
4358       return 1;  // Early out.
4359     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4360     return std::min(Tmp, Tmp2);
4361   case ISD::SADDO:
4362   case ISD::UADDO:
4363   case ISD::SADDO_CARRY:
4364   case ISD::UADDO_CARRY:
4365   case ISD::SSUBO:
4366   case ISD::USUBO:
4367   case ISD::SSUBO_CARRY:
4368   case ISD::USUBO_CARRY:
4369   case ISD::SMULO:
4370   case ISD::UMULO:
4371     if (Op.getResNo() != 1)
4372       break;
4373     // The boolean result conforms to getBooleanContents.  Fall through.
4374     // If setcc returns 0/-1, all bits are sign bits.
4375     // We know that we have an integer-based boolean since these operations
4376     // are only available for integer.
4377     if (TLI->getBooleanContents(VT.isVector(), false) ==
4378         TargetLowering::ZeroOrNegativeOneBooleanContent)
4379       return VTBits;
4380     break;
4381   case ISD::SETCC:
4382   case ISD::SETCCCARRY:
4383   case ISD::STRICT_FSETCC:
4384   case ISD::STRICT_FSETCCS: {
4385     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4386     // If setcc returns 0/-1, all bits are sign bits.
4387     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4388         TargetLowering::ZeroOrNegativeOneBooleanContent)
4389       return VTBits;
4390     break;
4391   }
4392   case ISD::ROTL:
4393   case ISD::ROTR:
4394     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4395 
4396     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4397     if (Tmp == VTBits)
4398       return VTBits;
4399 
4400     if (ConstantSDNode *C =
4401             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4402       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4403 
4404       // Handle rotate right by N like a rotate left by 32-N.
4405       if (Opcode == ISD::ROTR)
4406         RotAmt = (VTBits - RotAmt) % VTBits;
4407 
4408       // If we aren't rotating out all of the known-in sign bits, return the
4409       // number that are left.  This handles rotl(sext(x), 1) for example.
4410       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4411     }
4412     break;
4413   case ISD::ADD:
4414   case ISD::ADDC:
4415     // Add can have at most one carry bit.  Thus we know that the output
4416     // is, at worst, one more bit than the inputs.
4417     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4418     if (Tmp == 1) return 1; // Early out.
4419 
4420     // Special case decrementing a value (ADD X, -1):
4421     if (ConstantSDNode *CRHS =
4422             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4423       if (CRHS->isAllOnes()) {
4424         KnownBits Known =
4425             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4426 
4427         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4428         // sign bits set.
4429         if ((Known.Zero | 1).isAllOnes())
4430           return VTBits;
4431 
4432         // If we are subtracting one from a positive number, there is no carry
4433         // out of the result.
4434         if (Known.isNonNegative())
4435           return Tmp;
4436       }
4437 
4438     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4439     if (Tmp2 == 1) return 1; // Early out.
4440     return std::min(Tmp, Tmp2) - 1;
4441   case ISD::SUB:
4442     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4443     if (Tmp2 == 1) return 1; // Early out.
4444 
4445     // Handle NEG.
4446     if (ConstantSDNode *CLHS =
4447             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4448       if (CLHS->isZero()) {
4449         KnownBits Known =
4450             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4451         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4452         // sign bits set.
4453         if ((Known.Zero | 1).isAllOnes())
4454           return VTBits;
4455 
4456         // If the input is known to be positive (the sign bit is known clear),
4457         // the output of the NEG has the same number of sign bits as the input.
4458         if (Known.isNonNegative())
4459           return Tmp2;
4460 
4461         // Otherwise, we treat this like a SUB.
4462       }
4463 
4464     // Sub can have at most one carry bit.  Thus we know that the output
4465     // is, at worst, one more bit than the inputs.
4466     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4467     if (Tmp == 1) return 1; // Early out.
4468     return std::min(Tmp, Tmp2) - 1;
4469   case ISD::MUL: {
4470     // The output of the Mul can be at most twice the valid bits in the inputs.
4471     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4472     if (SignBitsOp0 == 1)
4473       break;
4474     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4475     if (SignBitsOp1 == 1)
4476       break;
4477     unsigned OutValidBits =
4478         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4479     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4480   }
4481   case ISD::SREM:
4482     // The sign bit is the LHS's sign bit, except when the result of the
4483     // remainder is zero. The magnitude of the result should be less than or
4484     // equal to the magnitude of the LHS. Therefore, the result should have
4485     // at least as many sign bits as the left hand side.
4486     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4487   case ISD::TRUNCATE: {
4488     // Check if the sign bits of source go down as far as the truncated value.
4489     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4490     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4491     if (NumSrcSignBits > (NumSrcBits - VTBits))
4492       return NumSrcSignBits - (NumSrcBits - VTBits);
4493     break;
4494   }
4495   case ISD::EXTRACT_ELEMENT: {
4496     if (VT.isScalableVector())
4497       break;
4498     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4499     const int BitWidth = Op.getValueSizeInBits();
4500     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4501 
4502     // Get reverse index (starting from 1), Op1 value indexes elements from
4503     // little end. Sign starts at big end.
4504     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4505 
4506     // If the sign portion ends in our element the subtraction gives correct
4507     // result. Otherwise it gives either negative or > bitwidth result
4508     return std::clamp(KnownSign - rIndex * BitWidth, 0, BitWidth);
4509   }
4510   case ISD::INSERT_VECTOR_ELT: {
4511     if (VT.isScalableVector())
4512       break;
4513     // If we know the element index, split the demand between the
4514     // source vector and the inserted element, otherwise assume we need
4515     // the original demanded vector elements and the value.
4516     SDValue InVec = Op.getOperand(0);
4517     SDValue InVal = Op.getOperand(1);
4518     SDValue EltNo = Op.getOperand(2);
4519     bool DemandedVal = true;
4520     APInt DemandedVecElts = DemandedElts;
4521     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4522     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4523       unsigned EltIdx = CEltNo->getZExtValue();
4524       DemandedVal = !!DemandedElts[EltIdx];
4525       DemandedVecElts.clearBit(EltIdx);
4526     }
4527     Tmp = std::numeric_limits<unsigned>::max();
4528     if (DemandedVal) {
4529       // TODO - handle implicit truncation of inserted elements.
4530       if (InVal.getScalarValueSizeInBits() != VTBits)
4531         break;
4532       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4533       Tmp = std::min(Tmp, Tmp2);
4534     }
4535     if (!!DemandedVecElts) {
4536       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4537       Tmp = std::min(Tmp, Tmp2);
4538     }
4539     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4540     return Tmp;
4541   }
4542   case ISD::EXTRACT_VECTOR_ELT: {
4543     assert(!VT.isScalableVector());
4544     SDValue InVec = Op.getOperand(0);
4545     SDValue EltNo = Op.getOperand(1);
4546     EVT VecVT = InVec.getValueType();
4547     // ComputeNumSignBits not yet implemented for scalable vectors.
4548     if (VecVT.isScalableVector())
4549       break;
4550     const unsigned BitWidth = Op.getValueSizeInBits();
4551     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4552     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4553 
4554     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4555     // anything about sign bits. But if the sizes match we can derive knowledge
4556     // about sign bits from the vector operand.
4557     if (BitWidth != EltBitWidth)
4558       break;
4559 
4560     // If we know the element index, just demand that vector element, else for
4561     // an unknown element index, ignore DemandedElts and demand them all.
4562     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4563     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4564     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4565       DemandedSrcElts =
4566           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4567 
4568     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4569   }
4570   case ISD::EXTRACT_SUBVECTOR: {
4571     // Offset the demanded elts by the subvector index.
4572     SDValue Src = Op.getOperand(0);
4573     // Bail until we can represent demanded elements for scalable vectors.
4574     if (Src.getValueType().isScalableVector())
4575       break;
4576     uint64_t Idx = Op.getConstantOperandVal(1);
4577     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4578     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4579     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4580   }
4581   case ISD::CONCAT_VECTORS: {
4582     if (VT.isScalableVector())
4583       break;
4584     // Determine the minimum number of sign bits across all demanded
4585     // elts of the input vectors. Early out if the result is already 1.
4586     Tmp = std::numeric_limits<unsigned>::max();
4587     EVT SubVectorVT = Op.getOperand(0).getValueType();
4588     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4589     unsigned NumSubVectors = Op.getNumOperands();
4590     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4591       APInt DemandedSub =
4592           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4593       if (!DemandedSub)
4594         continue;
4595       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4596       Tmp = std::min(Tmp, Tmp2);
4597     }
4598     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4599     return Tmp;
4600   }
4601   case ISD::INSERT_SUBVECTOR: {
4602     if (VT.isScalableVector())
4603       break;
4604     // Demand any elements from the subvector and the remainder from the src its
4605     // inserted into.
4606     SDValue Src = Op.getOperand(0);
4607     SDValue Sub = Op.getOperand(1);
4608     uint64_t Idx = Op.getConstantOperandVal(2);
4609     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4610     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4611     APInt DemandedSrcElts = DemandedElts;
4612     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4613 
4614     Tmp = std::numeric_limits<unsigned>::max();
4615     if (!!DemandedSubElts) {
4616       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4617       if (Tmp == 1)
4618         return 1; // early-out
4619     }
4620     if (!!DemandedSrcElts) {
4621       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4622       Tmp = std::min(Tmp, Tmp2);
4623     }
4624     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4625     return Tmp;
4626   }
4627   case ISD::LOAD: {
4628     LoadSDNode *LD = cast<LoadSDNode>(Op);
4629     if (const MDNode *Ranges = LD->getRanges()) {
4630       if (DemandedElts != 1)
4631         break;
4632 
4633       ConstantRange CR = getConstantRangeFromMetadata(*Ranges);
4634       if (VTBits > CR.getBitWidth()) {
4635         switch (LD->getExtensionType()) {
4636         case ISD::SEXTLOAD:
4637           CR = CR.signExtend(VTBits);
4638           break;
4639         case ISD::ZEXTLOAD:
4640           CR = CR.zeroExtend(VTBits);
4641           break;
4642         default:
4643           break;
4644         }
4645       }
4646 
4647       if (VTBits != CR.getBitWidth())
4648         break;
4649       return std::min(CR.getSignedMin().getNumSignBits(),
4650                       CR.getSignedMax().getNumSignBits());
4651     }
4652 
4653     break;
4654   }
4655   case ISD::ATOMIC_CMP_SWAP:
4656   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4657   case ISD::ATOMIC_SWAP:
4658   case ISD::ATOMIC_LOAD_ADD:
4659   case ISD::ATOMIC_LOAD_SUB:
4660   case ISD::ATOMIC_LOAD_AND:
4661   case ISD::ATOMIC_LOAD_CLR:
4662   case ISD::ATOMIC_LOAD_OR:
4663   case ISD::ATOMIC_LOAD_XOR:
4664   case ISD::ATOMIC_LOAD_NAND:
4665   case ISD::ATOMIC_LOAD_MIN:
4666   case ISD::ATOMIC_LOAD_MAX:
4667   case ISD::ATOMIC_LOAD_UMIN:
4668   case ISD::ATOMIC_LOAD_UMAX:
4669   case ISD::ATOMIC_LOAD: {
4670     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4671     // If we are looking at the loaded value.
4672     if (Op.getResNo() == 0) {
4673       if (Tmp == VTBits)
4674         return 1; // early-out
4675       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4676         return VTBits - Tmp + 1;
4677       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4678         return VTBits - Tmp;
4679     }
4680     break;
4681   }
4682   }
4683 
4684   // If we are looking at the loaded value of the SDNode.
4685   if (Op.getResNo() == 0) {
4686     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4687     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4688       unsigned ExtType = LD->getExtensionType();
4689       switch (ExtType) {
4690       default: break;
4691       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4692         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4693         return VTBits - Tmp + 1;
4694       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4695         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4696         return VTBits - Tmp;
4697       case ISD::NON_EXTLOAD:
4698         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4699           // We only need to handle vectors - computeKnownBits should handle
4700           // scalar cases.
4701           Type *CstTy = Cst->getType();
4702           if (CstTy->isVectorTy() && !VT.isScalableVector() &&
4703               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4704               VTBits == CstTy->getScalarSizeInBits()) {
4705             Tmp = VTBits;
4706             for (unsigned i = 0; i != NumElts; ++i) {
4707               if (!DemandedElts[i])
4708                 continue;
4709               if (Constant *Elt = Cst->getAggregateElement(i)) {
4710                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4711                   const APInt &Value = CInt->getValue();
4712                   Tmp = std::min(Tmp, Value.getNumSignBits());
4713                   continue;
4714                 }
4715                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4716                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4717                   Tmp = std::min(Tmp, Value.getNumSignBits());
4718                   continue;
4719                 }
4720               }
4721               // Unknown type. Conservatively assume no bits match sign bit.
4722               return 1;
4723             }
4724             return Tmp;
4725           }
4726         }
4727         break;
4728       }
4729     }
4730   }
4731 
4732   // Allow the target to implement this method for its nodes.
4733   if (Opcode >= ISD::BUILTIN_OP_END ||
4734       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4735       Opcode == ISD::INTRINSIC_W_CHAIN ||
4736       Opcode == ISD::INTRINSIC_VOID) {
4737     // TODO: This can probably be removed once target code is audited.  This
4738     // is here purely to reduce patch size and review complexity.
4739     if (!VT.isScalableVector()) {
4740       unsigned NumBits =
4741         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4742       if (NumBits > 1)
4743         FirstAnswer = std::max(FirstAnswer, NumBits);
4744     }
4745   }
4746 
4747   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4748   // use this information.
4749   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4750   return std::max(FirstAnswer, Known.countMinSignBits());
4751 }
4752 
4753 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4754                                                  unsigned Depth) const {
4755   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4756   return Op.getScalarValueSizeInBits() - SignBits + 1;
4757 }
4758 
4759 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4760                                                  const APInt &DemandedElts,
4761                                                  unsigned Depth) const {
4762   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4763   return Op.getScalarValueSizeInBits() - SignBits + 1;
4764 }
4765 
4766 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4767                                                     unsigned Depth) const {
4768   // Early out for FREEZE.
4769   if (Op.getOpcode() == ISD::FREEZE)
4770     return true;
4771 
4772   // TODO: Assume we don't know anything for now.
4773   EVT VT = Op.getValueType();
4774   if (VT.isScalableVector())
4775     return false;
4776 
4777   APInt DemandedElts = VT.isVector()
4778                            ? APInt::getAllOnes(VT.getVectorNumElements())
4779                            : APInt(1, 1);
4780   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4781 }
4782 
4783 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4784                                                     const APInt &DemandedElts,
4785                                                     bool PoisonOnly,
4786                                                     unsigned Depth) const {
4787   unsigned Opcode = Op.getOpcode();
4788 
4789   // Early out for FREEZE.
4790   if (Opcode == ISD::FREEZE)
4791     return true;
4792 
4793   if (Depth >= MaxRecursionDepth)
4794     return false; // Limit search depth.
4795 
4796   if (isIntOrFPConstant(Op))
4797     return true;
4798 
4799   switch (Opcode) {
4800   case ISD::VALUETYPE:
4801   case ISD::FrameIndex:
4802   case ISD::TargetFrameIndex:
4803     return true;
4804 
4805   case ISD::UNDEF:
4806     return PoisonOnly;
4807 
4808   case ISD::BUILD_VECTOR:
4809     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4810     // this shouldn't affect the result.
4811     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4812       if (!DemandedElts[i])
4813         continue;
4814       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4815                                             Depth + 1))
4816         return false;
4817     }
4818     return true;
4819 
4820     // TODO: Search for noundef attributes from library functions.
4821 
4822     // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4823 
4824   default:
4825     // Allow the target to implement this method for its nodes.
4826     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4827         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4828       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4829           Op, DemandedElts, *this, PoisonOnly, Depth);
4830     break;
4831   }
4832 
4833   // If Op can't create undef/poison and none of its operands are undef/poison
4834   // then Op is never undef/poison.
4835   // NOTE: TargetNodes should handle this in themselves in
4836   // isGuaranteedNotToBeUndefOrPoisonForTargetNode.
4837   return !canCreateUndefOrPoison(Op, PoisonOnly, /*ConsiderFlags*/ true,
4838                                  Depth) &&
4839          all_of(Op->ops(), [&](SDValue V) {
4840            return isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, Depth + 1);
4841          });
4842 }
4843 
4844 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, bool PoisonOnly,
4845                                           bool ConsiderFlags,
4846                                           unsigned Depth) const {
4847   // TODO: Assume we don't know anything for now.
4848   EVT VT = Op.getValueType();
4849   if (VT.isScalableVector())
4850     return true;
4851 
4852   APInt DemandedElts = VT.isVector()
4853                            ? APInt::getAllOnes(VT.getVectorNumElements())
4854                            : APInt(1, 1);
4855   return canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly, ConsiderFlags,
4856                                 Depth);
4857 }
4858 
4859 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts,
4860                                           bool PoisonOnly, bool ConsiderFlags,
4861                                           unsigned Depth) const {
4862   // TODO: Assume we don't know anything for now.
4863   EVT VT = Op.getValueType();
4864   if (VT.isScalableVector())
4865     return true;
4866 
4867   unsigned Opcode = Op.getOpcode();
4868   switch (Opcode) {
4869   case ISD::AssertSext:
4870   case ISD::AssertZext:
4871   case ISD::FREEZE:
4872   case ISD::CONCAT_VECTORS:
4873   case ISD::INSERT_SUBVECTOR:
4874   case ISD::AND:
4875   case ISD::OR:
4876   case ISD::XOR:
4877   case ISD::ROTL:
4878   case ISD::ROTR:
4879   case ISD::FSHL:
4880   case ISD::FSHR:
4881   case ISD::BSWAP:
4882   case ISD::CTPOP:
4883   case ISD::BITREVERSE:
4884   case ISD::PARITY:
4885   case ISD::SIGN_EXTEND:
4886   case ISD::ZERO_EXTEND:
4887   case ISD::TRUNCATE:
4888   case ISD::SIGN_EXTEND_INREG:
4889   case ISD::SIGN_EXTEND_VECTOR_INREG:
4890   case ISD::ZERO_EXTEND_VECTOR_INREG:
4891   case ISD::BITCAST:
4892   case ISD::BUILD_VECTOR:
4893   case ISD::BUILD_PAIR:
4894     return false;
4895 
4896   case ISD::ADD:
4897   case ISD::SUB:
4898   case ISD::MUL:
4899     // Matches hasPoisonGeneratingFlags().
4900     return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() ||
4901                              Op->getFlags().hasNoUnsignedWrap());
4902 
4903   case ISD::SHL:
4904     // If the max shift amount isn't in range, then the shift can create poison.
4905     if (!getValidMaximumShiftAmountConstant(Op, DemandedElts))
4906       return true;
4907 
4908     // Matches hasPoisonGeneratingFlags().
4909     return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() ||
4910                              Op->getFlags().hasNoUnsignedWrap());
4911 
4912   case ISD::INSERT_VECTOR_ELT:{
4913     // Ensure that the element index is in bounds.
4914     EVT VecVT = Op.getOperand(0).getValueType();
4915     KnownBits KnownIdx = computeKnownBits(Op.getOperand(2), Depth + 1);
4916     return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
4917   }
4918 
4919   default:
4920     // Allow the target to implement this method for its nodes.
4921     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4922         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4923       return TLI->canCreateUndefOrPoisonForTargetNode(
4924           Op, DemandedElts, *this, PoisonOnly, ConsiderFlags, Depth);
4925     break;
4926   }
4927 
4928   // Be conservative and return true.
4929   return true;
4930 }
4931 
4932 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4933   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4934       !isa<ConstantSDNode>(Op.getOperand(1)))
4935     return false;
4936 
4937   if (Op.getOpcode() == ISD::OR &&
4938       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4939     return false;
4940 
4941   return true;
4942 }
4943 
4944 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4945   // If we're told that NaNs won't happen, assume they won't.
4946   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4947     return true;
4948 
4949   if (Depth >= MaxRecursionDepth)
4950     return false; // Limit search depth.
4951 
4952   // If the value is a constant, we can obviously see if it is a NaN or not.
4953   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4954     return !C->getValueAPF().isNaN() ||
4955            (SNaN && !C->getValueAPF().isSignaling());
4956   }
4957 
4958   unsigned Opcode = Op.getOpcode();
4959   switch (Opcode) {
4960   case ISD::FADD:
4961   case ISD::FSUB:
4962   case ISD::FMUL:
4963   case ISD::FDIV:
4964   case ISD::FREM:
4965   case ISD::FSIN:
4966   case ISD::FCOS:
4967   case ISD::FMA:
4968   case ISD::FMAD: {
4969     if (SNaN)
4970       return true;
4971     // TODO: Need isKnownNeverInfinity
4972     return false;
4973   }
4974   case ISD::FCANONICALIZE:
4975   case ISD::FEXP:
4976   case ISD::FEXP2:
4977   case ISD::FTRUNC:
4978   case ISD::FFLOOR:
4979   case ISD::FCEIL:
4980   case ISD::FROUND:
4981   case ISD::FROUNDEVEN:
4982   case ISD::FRINT:
4983   case ISD::FNEARBYINT:
4984   case ISD::FLDEXP: {
4985     if (SNaN)
4986       return true;
4987     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4988   }
4989   case ISD::FABS:
4990   case ISD::FNEG:
4991   case ISD::FCOPYSIGN: {
4992     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4993   }
4994   case ISD::SELECT:
4995     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4996            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4997   case ISD::FP_EXTEND:
4998   case ISD::FP_ROUND: {
4999     if (SNaN)
5000       return true;
5001     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
5002   }
5003   case ISD::SINT_TO_FP:
5004   case ISD::UINT_TO_FP:
5005     return true;
5006   case ISD::FSQRT: // Need is known positive
5007   case ISD::FLOG:
5008   case ISD::FLOG2:
5009   case ISD::FLOG10:
5010   case ISD::FPOWI:
5011   case ISD::FPOW: {
5012     if (SNaN)
5013       return true;
5014     // TODO: Refine on operand
5015     return false;
5016   }
5017   case ISD::FMINNUM:
5018   case ISD::FMAXNUM: {
5019     // Only one needs to be known not-nan, since it will be returned if the
5020     // other ends up being one.
5021     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
5022            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
5023   }
5024   case ISD::FMINNUM_IEEE:
5025   case ISD::FMAXNUM_IEEE: {
5026     if (SNaN)
5027       return true;
5028     // This can return a NaN if either operand is an sNaN, or if both operands
5029     // are NaN.
5030     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
5031             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
5032            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
5033             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
5034   }
5035   case ISD::FMINIMUM:
5036   case ISD::FMAXIMUM: {
5037     // TODO: Does this quiet or return the origina NaN as-is?
5038     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
5039            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
5040   }
5041   case ISD::EXTRACT_VECTOR_ELT: {
5042     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
5043   }
5044   case ISD::BUILD_VECTOR: {
5045     for (const SDValue &Opnd : Op->ops())
5046       if (!isKnownNeverNaN(Opnd, SNaN, Depth + 1))
5047         return false;
5048     return true;
5049   }
5050   default:
5051     if (Opcode >= ISD::BUILTIN_OP_END ||
5052         Opcode == ISD::INTRINSIC_WO_CHAIN ||
5053         Opcode == ISD::INTRINSIC_W_CHAIN ||
5054         Opcode == ISD::INTRINSIC_VOID) {
5055       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
5056     }
5057 
5058     return false;
5059   }
5060 }
5061 
5062 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
5063   assert(Op.getValueType().isFloatingPoint() &&
5064          "Floating point type expected");
5065 
5066   // If the value is a constant, we can obviously see if it is a zero or not.
5067   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
5068     return !C->isZero();
5069 
5070   // Return false if we find any zero in a vector.
5071   if (Op->getOpcode() == ISD::BUILD_VECTOR ||
5072       Op->getOpcode() == ISD::SPLAT_VECTOR) {
5073     for (const SDValue &OpVal : Op->op_values()) {
5074       if (OpVal.isUndef())
5075         return false;
5076       if (auto *C = dyn_cast<ConstantFPSDNode>(OpVal))
5077         if (C->isZero())
5078           return false;
5079     }
5080     return true;
5081   }
5082   return false;
5083 }
5084 
5085 bool SelectionDAG::isKnownNeverZero(SDValue Op, unsigned Depth) const {
5086   if (Depth >= MaxRecursionDepth)
5087     return false; // Limit search depth.
5088 
5089   assert(!Op.getValueType().isFloatingPoint() &&
5090          "Floating point types unsupported - use isKnownNeverZeroFloat");
5091 
5092   // If the value is a constant, we can obviously see if it is a zero or not.
5093   if (ISD::matchUnaryPredicate(Op,
5094                                [](ConstantSDNode *C) { return !C->isZero(); }))
5095     return true;
5096 
5097   // TODO: Recognize more cases here. Most of the cases are also incomplete to
5098   // some degree.
5099   switch (Op.getOpcode()) {
5100   default:
5101     break;
5102 
5103   case ISD::OR:
5104     return isKnownNeverZero(Op.getOperand(1), Depth + 1) ||
5105            isKnownNeverZero(Op.getOperand(0), Depth + 1);
5106 
5107   case ISD::VSELECT:
5108   case ISD::SELECT:
5109     return isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
5110            isKnownNeverZero(Op.getOperand(2), Depth + 1);
5111 
5112   case ISD::SHL:
5113     if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
5114       return isKnownNeverZero(Op.getOperand(0), Depth + 1);
5115 
5116     // 1 << X is never zero. TODO: This can be expanded if we can bound X.
5117     // The expression is really !Known.One[BitWidth-MaxLog2(Known):0].isZero()
5118     if (computeKnownBits(Op.getOperand(0), Depth + 1).One[0])
5119       return true;
5120     break;
5121 
5122   case ISD::UADDSAT:
5123   case ISD::UMAX:
5124     return isKnownNeverZero(Op.getOperand(1), Depth + 1) ||
5125            isKnownNeverZero(Op.getOperand(0), Depth + 1);
5126 
5127   case ISD::UMIN:
5128     return isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
5129            isKnownNeverZero(Op.getOperand(0), Depth + 1);
5130 
5131   case ISD::ROTL:
5132   case ISD::ROTR:
5133   case ISD::BITREVERSE:
5134   case ISD::BSWAP:
5135   case ISD::CTPOP:
5136   case ISD::ABS:
5137     return isKnownNeverZero(Op.getOperand(0), Depth + 1);
5138 
5139   case ISD::SRA:
5140   case ISD::SRL:
5141     if (Op->getFlags().hasExact())
5142       return isKnownNeverZero(Op.getOperand(0), Depth + 1);
5143     // Signed >> X is never zero. TODO: This can be expanded if we can bound X.
5144     // The expression is really
5145     // !Known.One[SignBit:SignBit-(BitWidth-MaxLog2(Known))].isZero()
5146     if (computeKnownBits(Op.getOperand(0), Depth + 1).isNegative())
5147       return true;
5148     break;
5149 
5150   case ISD::UDIV:
5151   case ISD::SDIV:
5152     // div exact can only produce a zero if the dividend is zero.
5153     // TODO: For udiv this is also true if Op1 u<= Op0
5154     if (Op->getFlags().hasExact())
5155       return isKnownNeverZero(Op.getOperand(0), Depth + 1);
5156     break;
5157 
5158   case ISD::ADD:
5159     if (Op->getFlags().hasNoUnsignedWrap())
5160       if (isKnownNeverZero(Op.getOperand(1), Depth + 1) ||
5161           isKnownNeverZero(Op.getOperand(0), Depth + 1))
5162         return true;
5163     // TODO: There are a lot more cases we can prove for add.
5164     break;
5165 
5166   case ISD::SUB: {
5167     if (isNullConstant(Op.getOperand(0)))
5168       return isKnownNeverZero(Op.getOperand(1), Depth + 1);
5169 
5170     std::optional<bool> ne =
5171         KnownBits::ne(computeKnownBits(Op.getOperand(0), Depth + 1),
5172                       computeKnownBits(Op.getOperand(1), Depth + 1));
5173     return ne && *ne;
5174   }
5175 
5176   case ISD::MUL:
5177     if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
5178       if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
5179           isKnownNeverZero(Op.getOperand(0), Depth + 1))
5180         return true;
5181     break;
5182 
5183   case ISD::ZERO_EXTEND:
5184   case ISD::SIGN_EXTEND:
5185     return isKnownNeverZero(Op.getOperand(0), Depth + 1);
5186   }
5187 
5188   return computeKnownBits(Op, Depth).isNonZero();
5189 }
5190 
5191 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
5192   // Check the obvious case.
5193   if (A == B) return true;
5194 
5195   // For negative and positive zero.
5196   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
5197     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
5198       if (CA->isZero() && CB->isZero()) return true;
5199 
5200   // Otherwise they may not be equal.
5201   return false;
5202 }
5203 
5204 // Only bits set in Mask must be negated, other bits may be arbitrary.
5205 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
5206   if (isBitwiseNot(V, AllowUndefs))
5207     return V.getOperand(0);
5208 
5209   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
5210   // bits in the non-extended part.
5211   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
5212   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
5213     return SDValue();
5214   SDValue ExtArg = V.getOperand(0);
5215   if (ExtArg.getScalarValueSizeInBits() >=
5216           MaskC->getAPIntValue().getActiveBits() &&
5217       isBitwiseNot(ExtArg, AllowUndefs) &&
5218       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5219       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
5220     return ExtArg.getOperand(0).getOperand(0);
5221   return SDValue();
5222 }
5223 
5224 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
5225   // Match masked merge pattern (X & ~M) op (Y & M)
5226   // Including degenerate case (X & ~M) op M
5227   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
5228                                       SDValue Other) {
5229     if (SDValue NotOperand =
5230             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
5231       if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
5232           NotOperand->getOpcode() == ISD::TRUNCATE)
5233         NotOperand = NotOperand->getOperand(0);
5234 
5235       if (Other == NotOperand)
5236         return true;
5237       if (Other->getOpcode() == ISD::AND)
5238         return NotOperand == Other->getOperand(0) ||
5239                NotOperand == Other->getOperand(1);
5240     }
5241     return false;
5242   };
5243 
5244   if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
5245     A = A->getOperand(0);
5246 
5247   if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
5248     B = B->getOperand(0);
5249 
5250   if (A->getOpcode() == ISD::AND)
5251     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
5252            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
5253   return false;
5254 }
5255 
5256 // FIXME: unify with llvm::haveNoCommonBitsSet.
5257 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
5258   assert(A.getValueType() == B.getValueType() &&
5259          "Values must have the same type");
5260   if (haveNoCommonBitsSetCommutative(A, B) ||
5261       haveNoCommonBitsSetCommutative(B, A))
5262     return true;
5263   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
5264                                         computeKnownBits(B));
5265 }
5266 
5267 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
5268                                SelectionDAG &DAG) {
5269   if (cast<ConstantSDNode>(Step)->isZero())
5270     return DAG.getConstant(0, DL, VT);
5271 
5272   return SDValue();
5273 }
5274 
5275 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
5276                                 ArrayRef<SDValue> Ops,
5277                                 SelectionDAG &DAG) {
5278   int NumOps = Ops.size();
5279   assert(NumOps != 0 && "Can't build an empty vector!");
5280   assert(!VT.isScalableVector() &&
5281          "BUILD_VECTOR cannot be used with scalable types");
5282   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
5283          "Incorrect element count in BUILD_VECTOR!");
5284 
5285   // BUILD_VECTOR of UNDEFs is UNDEF.
5286   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
5287     return DAG.getUNDEF(VT);
5288 
5289   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
5290   SDValue IdentitySrc;
5291   bool IsIdentity = true;
5292   for (int i = 0; i != NumOps; ++i) {
5293     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5294         Ops[i].getOperand(0).getValueType() != VT ||
5295         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
5296         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
5297         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
5298       IsIdentity = false;
5299       break;
5300     }
5301     IdentitySrc = Ops[i].getOperand(0);
5302   }
5303   if (IsIdentity)
5304     return IdentitySrc;
5305 
5306   return SDValue();
5307 }
5308 
5309 /// Try to simplify vector concatenation to an input value, undef, or build
5310 /// vector.
5311 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
5312                                   ArrayRef<SDValue> Ops,
5313                                   SelectionDAG &DAG) {
5314   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
5315   assert(llvm::all_of(Ops,
5316                       [Ops](SDValue Op) {
5317                         return Ops[0].getValueType() == Op.getValueType();
5318                       }) &&
5319          "Concatenation of vectors with inconsistent value types!");
5320   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
5321              VT.getVectorElementCount() &&
5322          "Incorrect element count in vector concatenation!");
5323 
5324   if (Ops.size() == 1)
5325     return Ops[0];
5326 
5327   // Concat of UNDEFs is UNDEF.
5328   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
5329     return DAG.getUNDEF(VT);
5330 
5331   // Scan the operands and look for extract operations from a single source
5332   // that correspond to insertion at the same location via this concatenation:
5333   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
5334   SDValue IdentitySrc;
5335   bool IsIdentity = true;
5336   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
5337     SDValue Op = Ops[i];
5338     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
5339     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
5340         Op.getOperand(0).getValueType() != VT ||
5341         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
5342         Op.getConstantOperandVal(1) != IdentityIndex) {
5343       IsIdentity = false;
5344       break;
5345     }
5346     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
5347            "Unexpected identity source vector for concat of extracts");
5348     IdentitySrc = Op.getOperand(0);
5349   }
5350   if (IsIdentity) {
5351     assert(IdentitySrc && "Failed to set source vector of extracts");
5352     return IdentitySrc;
5353   }
5354 
5355   // The code below this point is only designed to work for fixed width
5356   // vectors, so we bail out for now.
5357   if (VT.isScalableVector())
5358     return SDValue();
5359 
5360   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
5361   // simplified to one big BUILD_VECTOR.
5362   // FIXME: Add support for SCALAR_TO_VECTOR as well.
5363   EVT SVT = VT.getScalarType();
5364   SmallVector<SDValue, 16> Elts;
5365   for (SDValue Op : Ops) {
5366     EVT OpVT = Op.getValueType();
5367     if (Op.isUndef())
5368       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
5369     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
5370       Elts.append(Op->op_begin(), Op->op_end());
5371     else
5372       return SDValue();
5373   }
5374 
5375   // BUILD_VECTOR requires all inputs to be of the same type, find the
5376   // maximum type and extend them all.
5377   for (SDValue Op : Elts)
5378     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
5379 
5380   if (SVT.bitsGT(VT.getScalarType())) {
5381     for (SDValue &Op : Elts) {
5382       if (Op.isUndef())
5383         Op = DAG.getUNDEF(SVT);
5384       else
5385         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
5386                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
5387                  : DAG.getSExtOrTrunc(Op, DL, SVT);
5388     }
5389   }
5390 
5391   SDValue V = DAG.getBuildVector(VT, DL, Elts);
5392   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
5393   return V;
5394 }
5395 
5396 /// Gets or creates the specified node.
5397 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
5398   FoldingSetNodeID ID;
5399   AddNodeIDNode(ID, Opcode, getVTList(VT), std::nullopt);
5400   void *IP = nullptr;
5401   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5402     return SDValue(E, 0);
5403 
5404   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5405                               getVTList(VT));
5406   CSEMap.InsertNode(N, IP);
5407 
5408   InsertNode(N);
5409   SDValue V = SDValue(N, 0);
5410   NewSDValueDbgMsg(V, "Creating new node: ", this);
5411   return V;
5412 }
5413 
5414 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5415                               SDValue N1) {
5416   SDNodeFlags Flags;
5417   if (Inserter)
5418     Flags = Inserter->getFlags();
5419   return getNode(Opcode, DL, VT, N1, Flags);
5420 }
5421 
5422 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5423                               SDValue N1, const SDNodeFlags Flags) {
5424   assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
5425   // Constant fold unary operations with an integer constant operand. Even
5426   // opaque constant will be folded, because the folding of unary operations
5427   // doesn't create new constants with different values. Nevertheless, the
5428   // opaque flag is preserved during folding to prevent future folding with
5429   // other constants.
5430   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
5431     const APInt &Val = C->getAPIntValue();
5432     switch (Opcode) {
5433     default: break;
5434     case ISD::SIGN_EXTEND:
5435       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
5436                          C->isTargetOpcode(), C->isOpaque());
5437     case ISD::TRUNCATE:
5438       if (C->isOpaque())
5439         break;
5440       [[fallthrough]];
5441     case ISD::ZERO_EXTEND:
5442       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
5443                          C->isTargetOpcode(), C->isOpaque());
5444     case ISD::ANY_EXTEND:
5445       // Some targets like RISCV prefer to sign extend some types.
5446       if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
5447         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
5448                            C->isTargetOpcode(), C->isOpaque());
5449       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
5450                          C->isTargetOpcode(), C->isOpaque());
5451     case ISD::UINT_TO_FP:
5452     case ISD::SINT_TO_FP: {
5453       APFloat apf(EVTToAPFloatSemantics(VT),
5454                   APInt::getZero(VT.getSizeInBits()));
5455       (void)apf.convertFromAPInt(Val,
5456                                  Opcode==ISD::SINT_TO_FP,
5457                                  APFloat::rmNearestTiesToEven);
5458       return getConstantFP(apf, DL, VT);
5459     }
5460     case ISD::BITCAST:
5461       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
5462         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
5463       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
5464         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
5465       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
5466         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
5467       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
5468         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
5469       break;
5470     case ISD::ABS:
5471       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
5472                          C->isOpaque());
5473     case ISD::BITREVERSE:
5474       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
5475                          C->isOpaque());
5476     case ISD::BSWAP:
5477       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
5478                          C->isOpaque());
5479     case ISD::CTPOP:
5480       return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
5481                          C->isOpaque());
5482     case ISD::CTLZ:
5483     case ISD::CTLZ_ZERO_UNDEF:
5484       return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
5485                          C->isOpaque());
5486     case ISD::CTTZ:
5487     case ISD::CTTZ_ZERO_UNDEF:
5488       return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
5489                          C->isOpaque());
5490     case ISD::FP16_TO_FP:
5491     case ISD::BF16_TO_FP: {
5492       bool Ignored;
5493       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
5494                                             : APFloat::BFloat(),
5495                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
5496 
5497       // This can return overflow, underflow, or inexact; we don't care.
5498       // FIXME need to be more flexible about rounding mode.
5499       (void)FPV.convert(EVTToAPFloatSemantics(VT),
5500                         APFloat::rmNearestTiesToEven, &Ignored);
5501       return getConstantFP(FPV, DL, VT);
5502     }
5503     case ISD::STEP_VECTOR: {
5504       if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
5505         return V;
5506       break;
5507     }
5508     }
5509   }
5510 
5511   // Constant fold unary operations with a floating point constant operand.
5512   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N1)) {
5513     APFloat V = C->getValueAPF();    // make copy
5514     switch (Opcode) {
5515     case ISD::FNEG:
5516       V.changeSign();
5517       return getConstantFP(V, DL, VT);
5518     case ISD::FABS:
5519       V.clearSign();
5520       return getConstantFP(V, DL, VT);
5521     case ISD::FCEIL: {
5522       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5523       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5524         return getConstantFP(V, DL, VT);
5525       break;
5526     }
5527     case ISD::FTRUNC: {
5528       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5529       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5530         return getConstantFP(V, DL, VT);
5531       break;
5532     }
5533     case ISD::FFLOOR: {
5534       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5535       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5536         return getConstantFP(V, DL, VT);
5537       break;
5538     }
5539     case ISD::FP_EXTEND: {
5540       bool ignored;
5541       // This can return overflow, underflow, or inexact; we don't care.
5542       // FIXME need to be more flexible about rounding mode.
5543       (void)V.convert(EVTToAPFloatSemantics(VT),
5544                       APFloat::rmNearestTiesToEven, &ignored);
5545       return getConstantFP(V, DL, VT);
5546     }
5547     case ISD::FP_TO_SINT:
5548     case ISD::FP_TO_UINT: {
5549       bool ignored;
5550       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5551       // FIXME need to be more flexible about rounding mode.
5552       APFloat::opStatus s =
5553           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5554       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5555         break;
5556       return getConstant(IntVal, DL, VT);
5557     }
5558     case ISD::BITCAST:
5559       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5560         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5561       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5562         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5563       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5564         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5565       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5566         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5567       break;
5568     case ISD::FP_TO_FP16:
5569     case ISD::FP_TO_BF16: {
5570       bool Ignored;
5571       // This can return overflow, underflow, or inexact; we don't care.
5572       // FIXME need to be more flexible about rounding mode.
5573       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5574                                                 : APFloat::BFloat(),
5575                       APFloat::rmNearestTiesToEven, &Ignored);
5576       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5577     }
5578     }
5579   }
5580 
5581   // Constant fold unary operations with a vector integer or float operand.
5582   switch (Opcode) {
5583   default:
5584     // FIXME: Entirely reasonable to perform folding of other unary
5585     // operations here as the need arises.
5586     break;
5587   case ISD::FNEG:
5588   case ISD::FABS:
5589   case ISD::FCEIL:
5590   case ISD::FTRUNC:
5591   case ISD::FFLOOR:
5592   case ISD::FP_EXTEND:
5593   case ISD::FP_TO_SINT:
5594   case ISD::FP_TO_UINT:
5595   case ISD::TRUNCATE:
5596   case ISD::ANY_EXTEND:
5597   case ISD::ZERO_EXTEND:
5598   case ISD::SIGN_EXTEND:
5599   case ISD::UINT_TO_FP:
5600   case ISD::SINT_TO_FP:
5601   case ISD::ABS:
5602   case ISD::BITREVERSE:
5603   case ISD::BSWAP:
5604   case ISD::CTLZ:
5605   case ISD::CTLZ_ZERO_UNDEF:
5606   case ISD::CTTZ:
5607   case ISD::CTTZ_ZERO_UNDEF:
5608   case ISD::CTPOP: {
5609     SDValue Ops = {N1};
5610     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5611       return Fold;
5612   }
5613   }
5614 
5615   unsigned OpOpcode = N1.getNode()->getOpcode();
5616   switch (Opcode) {
5617   case ISD::STEP_VECTOR:
5618     assert(VT.isScalableVector() &&
5619            "STEP_VECTOR can only be used with scalable types");
5620     assert(OpOpcode == ISD::TargetConstant &&
5621            VT.getVectorElementType() == N1.getValueType() &&
5622            "Unexpected step operand");
5623     break;
5624   case ISD::FREEZE:
5625     assert(VT == N1.getValueType() && "Unexpected VT!");
5626     if (isGuaranteedNotToBeUndefOrPoison(N1, /*PoisonOnly*/ false,
5627                                          /*Depth*/ 1))
5628       return N1;
5629     break;
5630   case ISD::TokenFactor:
5631   case ISD::MERGE_VALUES:
5632   case ISD::CONCAT_VECTORS:
5633     return N1;         // Factor, merge or concat of one node?  No need.
5634   case ISD::BUILD_VECTOR: {
5635     // Attempt to simplify BUILD_VECTOR.
5636     SDValue Ops[] = {N1};
5637     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5638       return V;
5639     break;
5640   }
5641   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5642   case ISD::FP_EXTEND:
5643     assert(VT.isFloatingPoint() && N1.getValueType().isFloatingPoint() &&
5644            "Invalid FP cast!");
5645     if (N1.getValueType() == VT) return N1;  // noop conversion.
5646     assert((!VT.isVector() || VT.getVectorElementCount() ==
5647                                   N1.getValueType().getVectorElementCount()) &&
5648            "Vector element count mismatch!");
5649     assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
5650     if (N1.isUndef())
5651       return getUNDEF(VT);
5652     break;
5653   case ISD::FP_TO_SINT:
5654   case ISD::FP_TO_UINT:
5655     if (N1.isUndef())
5656       return getUNDEF(VT);
5657     break;
5658   case ISD::SINT_TO_FP:
5659   case ISD::UINT_TO_FP:
5660     // [us]itofp(undef) = 0, because the result value is bounded.
5661     if (N1.isUndef())
5662       return getConstantFP(0.0, DL, VT);
5663     break;
5664   case ISD::SIGN_EXTEND:
5665     assert(VT.isInteger() && N1.getValueType().isInteger() &&
5666            "Invalid SIGN_EXTEND!");
5667     assert(VT.isVector() == N1.getValueType().isVector() &&
5668            "SIGN_EXTEND result type type should be vector iff the operand "
5669            "type is vector!");
5670     if (N1.getValueType() == VT) return N1;   // noop extension
5671     assert((!VT.isVector() || VT.getVectorElementCount() ==
5672                                   N1.getValueType().getVectorElementCount()) &&
5673            "Vector element count mismatch!");
5674     assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
5675     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5676       return getNode(OpOpcode, DL, VT, N1.getOperand(0));
5677     if (OpOpcode == ISD::UNDEF)
5678       // sext(undef) = 0, because the top bits will all be the same.
5679       return getConstant(0, DL, VT);
5680     break;
5681   case ISD::ZERO_EXTEND:
5682     assert(VT.isInteger() && N1.getValueType().isInteger() &&
5683            "Invalid ZERO_EXTEND!");
5684     assert(VT.isVector() == N1.getValueType().isVector() &&
5685            "ZERO_EXTEND result type type should be vector iff the operand "
5686            "type is vector!");
5687     if (N1.getValueType() == VT) return N1;   // noop extension
5688     assert((!VT.isVector() || VT.getVectorElementCount() ==
5689                                   N1.getValueType().getVectorElementCount()) &&
5690            "Vector element count mismatch!");
5691     assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
5692     if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
5693       return getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0));
5694     if (OpOpcode == ISD::UNDEF)
5695       // zext(undef) = 0, because the top bits will be zero.
5696       return getConstant(0, DL, VT);
5697     break;
5698   case ISD::ANY_EXTEND:
5699     assert(VT.isInteger() && N1.getValueType().isInteger() &&
5700            "Invalid ANY_EXTEND!");
5701     assert(VT.isVector() == N1.getValueType().isVector() &&
5702            "ANY_EXTEND result type type should be vector iff the operand "
5703            "type is vector!");
5704     if (N1.getValueType() == VT) return N1;   // noop extension
5705     assert((!VT.isVector() || VT.getVectorElementCount() ==
5706                                   N1.getValueType().getVectorElementCount()) &&
5707            "Vector element count mismatch!");
5708     assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
5709 
5710     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5711         OpOpcode == ISD::ANY_EXTEND)
5712       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5713       return getNode(OpOpcode, DL, VT, N1.getOperand(0));
5714     if (OpOpcode == ISD::UNDEF)
5715       return getUNDEF(VT);
5716 
5717     // (ext (trunc x)) -> x
5718     if (OpOpcode == ISD::TRUNCATE) {
5719       SDValue OpOp = N1.getOperand(0);
5720       if (OpOp.getValueType() == VT) {
5721         transferDbgValues(N1, OpOp);
5722         return OpOp;
5723       }
5724     }
5725     break;
5726   case ISD::TRUNCATE:
5727     assert(VT.isInteger() && N1.getValueType().isInteger() &&
5728            "Invalid TRUNCATE!");
5729     assert(VT.isVector() == N1.getValueType().isVector() &&
5730            "TRUNCATE result type type should be vector iff the operand "
5731            "type is vector!");
5732     if (N1.getValueType() == VT) return N1;   // noop truncate
5733     assert((!VT.isVector() || VT.getVectorElementCount() ==
5734                                   N1.getValueType().getVectorElementCount()) &&
5735            "Vector element count mismatch!");
5736     assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
5737     if (OpOpcode == ISD::TRUNCATE)
5738       return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
5739     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5740         OpOpcode == ISD::ANY_EXTEND) {
5741       // If the source is smaller than the dest, we still need an extend.
5742       if (N1.getOperand(0).getValueType().getScalarType().bitsLT(
5743               VT.getScalarType()))
5744         return getNode(OpOpcode, DL, VT, N1.getOperand(0));
5745       if (N1.getOperand(0).getValueType().bitsGT(VT))
5746         return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
5747       return N1.getOperand(0);
5748     }
5749     if (OpOpcode == ISD::UNDEF)
5750       return getUNDEF(VT);
5751     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5752       return getVScale(DL, VT,
5753                        N1.getConstantOperandAPInt(0).trunc(VT.getSizeInBits()));
5754     break;
5755   case ISD::ANY_EXTEND_VECTOR_INREG:
5756   case ISD::ZERO_EXTEND_VECTOR_INREG:
5757   case ISD::SIGN_EXTEND_VECTOR_INREG:
5758     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5759     assert(N1.getValueType().bitsLE(VT) &&
5760            "The input must be the same size or smaller than the result.");
5761     assert(VT.getVectorMinNumElements() <
5762                N1.getValueType().getVectorMinNumElements() &&
5763            "The destination vector type must have fewer lanes than the input.");
5764     break;
5765   case ISD::ABS:
5766     assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
5767     if (OpOpcode == ISD::UNDEF)
5768       return getConstant(0, DL, VT);
5769     break;
5770   case ISD::BSWAP:
5771     assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
5772     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5773            "BSWAP types must be a multiple of 16 bits!");
5774     if (OpOpcode == ISD::UNDEF)
5775       return getUNDEF(VT);
5776     // bswap(bswap(X)) -> X.
5777     if (OpOpcode == ISD::BSWAP)
5778       return N1.getOperand(0);
5779     break;
5780   case ISD::BITREVERSE:
5781     assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
5782     if (OpOpcode == ISD::UNDEF)
5783       return getUNDEF(VT);
5784     break;
5785   case ISD::BITCAST:
5786     assert(VT.getSizeInBits() == N1.getValueSizeInBits() &&
5787            "Cannot BITCAST between types of different sizes!");
5788     if (VT == N1.getValueType()) return N1;   // noop conversion.
5789     if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
5790       return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
5791     if (OpOpcode == ISD::UNDEF)
5792       return getUNDEF(VT);
5793     break;
5794   case ISD::SCALAR_TO_VECTOR:
5795     assert(VT.isVector() && !N1.getValueType().isVector() &&
5796            (VT.getVectorElementType() == N1.getValueType() ||
5797             (VT.getVectorElementType().isInteger() &&
5798              N1.getValueType().isInteger() &&
5799              VT.getVectorElementType().bitsLE(N1.getValueType()))) &&
5800            "Illegal SCALAR_TO_VECTOR node!");
5801     if (OpOpcode == ISD::UNDEF)
5802       return getUNDEF(VT);
5803     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5804     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5805         isa<ConstantSDNode>(N1.getOperand(1)) &&
5806         N1.getConstantOperandVal(1) == 0 &&
5807         N1.getOperand(0).getValueType() == VT)
5808       return N1.getOperand(0);
5809     break;
5810   case ISD::FNEG:
5811     // Negation of an unknown bag of bits is still completely undefined.
5812     if (OpOpcode == ISD::UNDEF)
5813       return getUNDEF(VT);
5814 
5815     if (OpOpcode == ISD::FNEG) // --X -> X
5816       return N1.getOperand(0);
5817     break;
5818   case ISD::FABS:
5819     if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
5820       return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
5821     break;
5822   case ISD::VSCALE:
5823     assert(VT == N1.getValueType() && "Unexpected VT!");
5824     break;
5825   case ISD::CTPOP:
5826     if (N1.getValueType().getScalarType() == MVT::i1)
5827       return N1;
5828     break;
5829   case ISD::CTLZ:
5830   case ISD::CTTZ:
5831     if (N1.getValueType().getScalarType() == MVT::i1)
5832       return getNOT(DL, N1, N1.getValueType());
5833     break;
5834   case ISD::VECREDUCE_ADD:
5835     if (N1.getValueType().getScalarType() == MVT::i1)
5836       return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
5837     break;
5838   case ISD::VECREDUCE_SMIN:
5839   case ISD::VECREDUCE_UMAX:
5840     if (N1.getValueType().getScalarType() == MVT::i1)
5841       return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
5842     break;
5843   case ISD::VECREDUCE_SMAX:
5844   case ISD::VECREDUCE_UMIN:
5845     if (N1.getValueType().getScalarType() == MVT::i1)
5846       return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
5847     break;
5848   }
5849 
5850   SDNode *N;
5851   SDVTList VTs = getVTList(VT);
5852   SDValue Ops[] = {N1};
5853   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5854     FoldingSetNodeID ID;
5855     AddNodeIDNode(ID, Opcode, VTs, Ops);
5856     void *IP = nullptr;
5857     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5858       E->intersectFlagsWith(Flags);
5859       return SDValue(E, 0);
5860     }
5861 
5862     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5863     N->setFlags(Flags);
5864     createOperands(N, Ops);
5865     CSEMap.InsertNode(N, IP);
5866   } else {
5867     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5868     createOperands(N, Ops);
5869   }
5870 
5871   InsertNode(N);
5872   SDValue V = SDValue(N, 0);
5873   NewSDValueDbgMsg(V, "Creating new node: ", this);
5874   return V;
5875 }
5876 
5877 static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5878                                       const APInt &C2) {
5879   switch (Opcode) {
5880   case ISD::ADD:  return C1 + C2;
5881   case ISD::SUB:  return C1 - C2;
5882   case ISD::MUL:  return C1 * C2;
5883   case ISD::AND:  return C1 & C2;
5884   case ISD::OR:   return C1 | C2;
5885   case ISD::XOR:  return C1 ^ C2;
5886   case ISD::SHL:  return C1 << C2;
5887   case ISD::SRL:  return C1.lshr(C2);
5888   case ISD::SRA:  return C1.ashr(C2);
5889   case ISD::ROTL: return C1.rotl(C2);
5890   case ISD::ROTR: return C1.rotr(C2);
5891   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5892   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5893   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5894   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5895   case ISD::SADDSAT: return C1.sadd_sat(C2);
5896   case ISD::UADDSAT: return C1.uadd_sat(C2);
5897   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5898   case ISD::USUBSAT: return C1.usub_sat(C2);
5899   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5900   case ISD::USHLSAT: return C1.ushl_sat(C2);
5901   case ISD::UDIV:
5902     if (!C2.getBoolValue())
5903       break;
5904     return C1.udiv(C2);
5905   case ISD::UREM:
5906     if (!C2.getBoolValue())
5907       break;
5908     return C1.urem(C2);
5909   case ISD::SDIV:
5910     if (!C2.getBoolValue())
5911       break;
5912     return C1.sdiv(C2);
5913   case ISD::SREM:
5914     if (!C2.getBoolValue())
5915       break;
5916     return C1.srem(C2);
5917   case ISD::MULHS: {
5918     unsigned FullWidth = C1.getBitWidth() * 2;
5919     APInt C1Ext = C1.sext(FullWidth);
5920     APInt C2Ext = C2.sext(FullWidth);
5921     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5922   }
5923   case ISD::MULHU: {
5924     unsigned FullWidth = C1.getBitWidth() * 2;
5925     APInt C1Ext = C1.zext(FullWidth);
5926     APInt C2Ext = C2.zext(FullWidth);
5927     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5928   }
5929   case ISD::AVGFLOORS: {
5930     unsigned FullWidth = C1.getBitWidth() + 1;
5931     APInt C1Ext = C1.sext(FullWidth);
5932     APInt C2Ext = C2.sext(FullWidth);
5933     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5934   }
5935   case ISD::AVGFLOORU: {
5936     unsigned FullWidth = C1.getBitWidth() + 1;
5937     APInt C1Ext = C1.zext(FullWidth);
5938     APInt C2Ext = C2.zext(FullWidth);
5939     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5940   }
5941   case ISD::AVGCEILS: {
5942     unsigned FullWidth = C1.getBitWidth() + 1;
5943     APInt C1Ext = C1.sext(FullWidth);
5944     APInt C2Ext = C2.sext(FullWidth);
5945     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5946   }
5947   case ISD::AVGCEILU: {
5948     unsigned FullWidth = C1.getBitWidth() + 1;
5949     APInt C1Ext = C1.zext(FullWidth);
5950     APInt C2Ext = C2.zext(FullWidth);
5951     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5952   }
5953   case ISD::ABDS:
5954     return APIntOps::smax(C1, C2) - APIntOps::smin(C1, C2);
5955   case ISD::ABDU:
5956     return APIntOps::umax(C1, C2) - APIntOps::umin(C1, C2);
5957   }
5958   return std::nullopt;
5959 }
5960 
5961 // Handle constant folding with UNDEF.
5962 // TODO: Handle more cases.
5963 static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
5964                                                bool IsUndef1, const APInt &C2,
5965                                                bool IsUndef2) {
5966   if (!(IsUndef1 || IsUndef2))
5967     return FoldValue(Opcode, C1, C2);
5968 
5969   // Fold and(x, undef) -> 0
5970   // Fold mul(x, undef) -> 0
5971   if (Opcode == ISD::AND || Opcode == ISD::MUL)
5972     return APInt::getZero(C1.getBitWidth());
5973 
5974   return std::nullopt;
5975 }
5976 
5977 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5978                                        const GlobalAddressSDNode *GA,
5979                                        const SDNode *N2) {
5980   if (GA->getOpcode() != ISD::GlobalAddress)
5981     return SDValue();
5982   if (!TLI->isOffsetFoldingLegal(GA))
5983     return SDValue();
5984   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5985   if (!C2)
5986     return SDValue();
5987   int64_t Offset = C2->getSExtValue();
5988   switch (Opcode) {
5989   case ISD::ADD: break;
5990   case ISD::SUB: Offset = -uint64_t(Offset); break;
5991   default: return SDValue();
5992   }
5993   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5994                           GA->getOffset() + uint64_t(Offset));
5995 }
5996 
5997 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5998   switch (Opcode) {
5999   case ISD::SDIV:
6000   case ISD::UDIV:
6001   case ISD::SREM:
6002   case ISD::UREM: {
6003     // If a divisor is zero/undef or any element of a divisor vector is
6004     // zero/undef, the whole op is undef.
6005     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
6006     SDValue Divisor = Ops[1];
6007     if (Divisor.isUndef() || isNullConstant(Divisor))
6008       return true;
6009 
6010     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
6011            llvm::any_of(Divisor->op_values(),
6012                         [](SDValue V) { return V.isUndef() ||
6013                                         isNullConstant(V); });
6014     // TODO: Handle signed overflow.
6015   }
6016   // TODO: Handle oversized shifts.
6017   default:
6018     return false;
6019   }
6020 }
6021 
6022 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
6023                                              EVT VT, ArrayRef<SDValue> Ops) {
6024   // If the opcode is a target-specific ISD node, there's nothing we can
6025   // do here and the operand rules may not line up with the below, so
6026   // bail early.
6027   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
6028   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
6029   // foldCONCAT_VECTORS in getNode before this is called.
6030   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
6031     return SDValue();
6032 
6033   unsigned NumOps = Ops.size();
6034   if (NumOps == 0)
6035     return SDValue();
6036 
6037   if (isUndef(Opcode, Ops))
6038     return getUNDEF(VT);
6039 
6040   // Handle binops special cases.
6041   if (NumOps == 2) {
6042     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
6043       return CFP;
6044 
6045     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
6046       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
6047         if (C1->isOpaque() || C2->isOpaque())
6048           return SDValue();
6049 
6050         std::optional<APInt> FoldAttempt =
6051             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
6052         if (!FoldAttempt)
6053           return SDValue();
6054 
6055         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
6056         assert((!Folded || !VT.isVector()) &&
6057                "Can't fold vectors ops with scalar operands");
6058         return Folded;
6059       }
6060     }
6061 
6062     // fold (add Sym, c) -> Sym+c
6063     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
6064       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
6065     if (TLI->isCommutativeBinOp(Opcode))
6066       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
6067         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
6068   }
6069 
6070   // This is for vector folding only from here on.
6071   if (!VT.isVector())
6072     return SDValue();
6073 
6074   ElementCount NumElts = VT.getVectorElementCount();
6075 
6076   // See if we can fold through bitcasted integer ops.
6077   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
6078       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
6079       Ops[0].getOpcode() == ISD::BITCAST &&
6080       Ops[1].getOpcode() == ISD::BITCAST) {
6081     SDValue N1 = peekThroughBitcasts(Ops[0]);
6082     SDValue N2 = peekThroughBitcasts(Ops[1]);
6083     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6084     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
6085     EVT BVVT = N1.getValueType();
6086     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
6087       bool IsLE = getDataLayout().isLittleEndian();
6088       unsigned EltBits = VT.getScalarSizeInBits();
6089       SmallVector<APInt> RawBits1, RawBits2;
6090       BitVector UndefElts1, UndefElts2;
6091       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
6092           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
6093         SmallVector<APInt> RawBits;
6094         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
6095           std::optional<APInt> Fold = FoldValueWithUndef(
6096               Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
6097           if (!Fold)
6098             break;
6099           RawBits.push_back(*Fold);
6100         }
6101         if (RawBits.size() == NumElts.getFixedValue()) {
6102           // We have constant folded, but we need to cast this again back to
6103           // the original (possibly legalized) type.
6104           SmallVector<APInt> DstBits;
6105           BitVector DstUndefs;
6106           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
6107                                            DstBits, RawBits, DstUndefs,
6108                                            BitVector(RawBits.size(), false));
6109           EVT BVEltVT = BV1->getOperand(0).getValueType();
6110           unsigned BVEltBits = BVEltVT.getSizeInBits();
6111           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
6112           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
6113             if (DstUndefs[I])
6114               continue;
6115             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
6116           }
6117           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
6118         }
6119       }
6120     }
6121   }
6122 
6123   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
6124   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
6125   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
6126       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
6127     APInt RHSVal;
6128     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
6129       APInt NewStep = Opcode == ISD::MUL
6130                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
6131                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
6132       return getStepVector(DL, VT, NewStep);
6133     }
6134   }
6135 
6136   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
6137     return !Op.getValueType().isVector() ||
6138            Op.getValueType().getVectorElementCount() == NumElts;
6139   };
6140 
6141   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
6142     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
6143            Op.getOpcode() == ISD::BUILD_VECTOR ||
6144            Op.getOpcode() == ISD::SPLAT_VECTOR;
6145   };
6146 
6147   // All operands must be vector types with the same number of elements as
6148   // the result type and must be either UNDEF or a build/splat vector
6149   // or UNDEF scalars.
6150   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
6151       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
6152     return SDValue();
6153 
6154   // If we are comparing vectors, then the result needs to be a i1 boolean that
6155   // is then extended back to the legal result type depending on how booleans
6156   // are represented.
6157   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
6158   ISD::NodeType ExtendCode =
6159       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
6160           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
6161           : ISD::SIGN_EXTEND;
6162 
6163   // Find legal integer scalar type for constant promotion and
6164   // ensure that its scalar size is at least as large as source.
6165   EVT LegalSVT = VT.getScalarType();
6166   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
6167     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
6168     if (LegalSVT.bitsLT(VT.getScalarType()))
6169       return SDValue();
6170   }
6171 
6172   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
6173   // only have one operand to check. For fixed-length vector types we may have
6174   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
6175   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
6176 
6177   // Constant fold each scalar lane separately.
6178   SmallVector<SDValue, 4> ScalarResults;
6179   for (unsigned I = 0; I != NumVectorElts; I++) {
6180     SmallVector<SDValue, 4> ScalarOps;
6181     for (SDValue Op : Ops) {
6182       EVT InSVT = Op.getValueType().getScalarType();
6183       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
6184           Op.getOpcode() != ISD::SPLAT_VECTOR) {
6185         if (Op.isUndef())
6186           ScalarOps.push_back(getUNDEF(InSVT));
6187         else
6188           ScalarOps.push_back(Op);
6189         continue;
6190       }
6191 
6192       SDValue ScalarOp =
6193           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
6194       EVT ScalarVT = ScalarOp.getValueType();
6195 
6196       // Build vector (integer) scalar operands may need implicit
6197       // truncation - do this before constant folding.
6198       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
6199         // Don't create illegally-typed nodes unless they're constants or undef
6200         // - if we fail to constant fold we can't guarantee the (dead) nodes
6201         // we're creating will be cleaned up before being visited for
6202         // legalization.
6203         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
6204             !isa<ConstantSDNode>(ScalarOp) &&
6205             TLI->getTypeAction(*getContext(), InSVT) !=
6206                 TargetLowering::TypeLegal)
6207           return SDValue();
6208         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
6209       }
6210 
6211       ScalarOps.push_back(ScalarOp);
6212     }
6213 
6214     // Constant fold the scalar operands.
6215     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
6216 
6217     // Legalize the (integer) scalar constant if necessary.
6218     if (LegalSVT != SVT)
6219       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
6220 
6221     // Scalar folding only succeeded if the result is a constant or UNDEF.
6222     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
6223         ScalarResult.getOpcode() != ISD::ConstantFP)
6224       return SDValue();
6225     ScalarResults.push_back(ScalarResult);
6226   }
6227 
6228   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
6229                                    : getBuildVector(VT, DL, ScalarResults);
6230   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
6231   return V;
6232 }
6233 
6234 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
6235                                          EVT VT, SDValue N1, SDValue N2) {
6236   // TODO: We don't do any constant folding for strict FP opcodes here, but we
6237   //       should. That will require dealing with a potentially non-default
6238   //       rounding mode, checking the "opStatus" return value from the APFloat
6239   //       math calculations, and possibly other variations.
6240   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
6241   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
6242   if (N1CFP && N2CFP) {
6243     APFloat C1 = N1CFP->getValueAPF(); // make copy
6244     const APFloat &C2 = N2CFP->getValueAPF();
6245     switch (Opcode) {
6246     case ISD::FADD:
6247       C1.add(C2, APFloat::rmNearestTiesToEven);
6248       return getConstantFP(C1, DL, VT);
6249     case ISD::FSUB:
6250       C1.subtract(C2, APFloat::rmNearestTiesToEven);
6251       return getConstantFP(C1, DL, VT);
6252     case ISD::FMUL:
6253       C1.multiply(C2, APFloat::rmNearestTiesToEven);
6254       return getConstantFP(C1, DL, VT);
6255     case ISD::FDIV:
6256       C1.divide(C2, APFloat::rmNearestTiesToEven);
6257       return getConstantFP(C1, DL, VT);
6258     case ISD::FREM:
6259       C1.mod(C2);
6260       return getConstantFP(C1, DL, VT);
6261     case ISD::FCOPYSIGN:
6262       C1.copySign(C2);
6263       return getConstantFP(C1, DL, VT);
6264     case ISD::FMINNUM:
6265       return getConstantFP(minnum(C1, C2), DL, VT);
6266     case ISD::FMAXNUM:
6267       return getConstantFP(maxnum(C1, C2), DL, VT);
6268     case ISD::FMINIMUM:
6269       return getConstantFP(minimum(C1, C2), DL, VT);
6270     case ISD::FMAXIMUM:
6271       return getConstantFP(maximum(C1, C2), DL, VT);
6272     default: break;
6273     }
6274   }
6275   if (N1CFP && Opcode == ISD::FP_ROUND) {
6276     APFloat C1 = N1CFP->getValueAPF();    // make copy
6277     bool Unused;
6278     // This can return overflow, underflow, or inexact; we don't care.
6279     // FIXME need to be more flexible about rounding mode.
6280     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
6281                       &Unused);
6282     return getConstantFP(C1, DL, VT);
6283   }
6284 
6285   switch (Opcode) {
6286   case ISD::FSUB:
6287     // -0.0 - undef --> undef (consistent with "fneg undef")
6288     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
6289       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
6290         return getUNDEF(VT);
6291     [[fallthrough]];
6292 
6293   case ISD::FADD:
6294   case ISD::FMUL:
6295   case ISD::FDIV:
6296   case ISD::FREM:
6297     // If both operands are undef, the result is undef. If 1 operand is undef,
6298     // the result is NaN. This should match the behavior of the IR optimizer.
6299     if (N1.isUndef() && N2.isUndef())
6300       return getUNDEF(VT);
6301     if (N1.isUndef() || N2.isUndef())
6302       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
6303   }
6304   return SDValue();
6305 }
6306 
6307 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
6308   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
6309 
6310   // There's no need to assert on a byte-aligned pointer. All pointers are at
6311   // least byte aligned.
6312   if (A == Align(1))
6313     return Val;
6314 
6315   FoldingSetNodeID ID;
6316   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
6317   ID.AddInteger(A.value());
6318 
6319   void *IP = nullptr;
6320   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6321     return SDValue(E, 0);
6322 
6323   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
6324                                          Val.getValueType(), A);
6325   createOperands(N, {Val});
6326 
6327   CSEMap.InsertNode(N, IP);
6328   InsertNode(N);
6329 
6330   SDValue V(N, 0);
6331   NewSDValueDbgMsg(V, "Creating new node: ", this);
6332   return V;
6333 }
6334 
6335 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6336                               SDValue N1, SDValue N2) {
6337   SDNodeFlags Flags;
6338   if (Inserter)
6339     Flags = Inserter->getFlags();
6340   return getNode(Opcode, DL, VT, N1, N2, Flags);
6341 }
6342 
6343 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
6344                                                 SDValue &N2) const {
6345   if (!TLI->isCommutativeBinOp(Opcode))
6346     return;
6347 
6348   // Canonicalize:
6349   //   binop(const, nonconst) -> binop(nonconst, const)
6350   SDNode *N1C = isConstantIntBuildVectorOrConstantInt(N1);
6351   SDNode *N2C = isConstantIntBuildVectorOrConstantInt(N2);
6352   SDNode *N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
6353   SDNode *N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
6354   if ((N1C && !N2C) || (N1CFP && !N2CFP))
6355     std::swap(N1, N2);
6356 
6357   // Canonicalize:
6358   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
6359   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
6360            N2.getOpcode() == ISD::STEP_VECTOR)
6361     std::swap(N1, N2);
6362 }
6363 
6364 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6365                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
6366   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6367          N2.getOpcode() != ISD::DELETED_NODE &&
6368          "Operand is DELETED_NODE!");
6369 
6370   canonicalizeCommutativeBinop(Opcode, N1, N2);
6371 
6372   auto *N1C = dyn_cast<ConstantSDNode>(N1);
6373   auto *N2C = dyn_cast<ConstantSDNode>(N2);
6374 
6375   // Don't allow undefs in vector splats - we might be returning N2 when folding
6376   // to zero etc.
6377   ConstantSDNode *N2CV =
6378       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
6379 
6380   switch (Opcode) {
6381   default: break;
6382   case ISD::TokenFactor:
6383     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
6384            N2.getValueType() == MVT::Other && "Invalid token factor!");
6385     // Fold trivial token factors.
6386     if (N1.getOpcode() == ISD::EntryToken) return N2;
6387     if (N2.getOpcode() == ISD::EntryToken) return N1;
6388     if (N1 == N2) return N1;
6389     break;
6390   case ISD::BUILD_VECTOR: {
6391     // Attempt to simplify BUILD_VECTOR.
6392     SDValue Ops[] = {N1, N2};
6393     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6394       return V;
6395     break;
6396   }
6397   case ISD::CONCAT_VECTORS: {
6398     SDValue Ops[] = {N1, N2};
6399     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6400       return V;
6401     break;
6402   }
6403   case ISD::AND:
6404     assert(VT.isInteger() && "This operator does not apply to FP types!");
6405     assert(N1.getValueType() == N2.getValueType() &&
6406            N1.getValueType() == VT && "Binary operator types must match!");
6407     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
6408     // worth handling here.
6409     if (N2CV && N2CV->isZero())
6410       return N2;
6411     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
6412       return N1;
6413     break;
6414   case ISD::OR:
6415   case ISD::XOR:
6416   case ISD::ADD:
6417   case ISD::SUB:
6418     assert(VT.isInteger() && "This operator does not apply to FP types!");
6419     assert(N1.getValueType() == N2.getValueType() &&
6420            N1.getValueType() == VT && "Binary operator types must match!");
6421     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
6422     // it's worth handling here.
6423     if (N2CV && N2CV->isZero())
6424       return N1;
6425     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
6426         VT.getVectorElementType() == MVT::i1)
6427       return getNode(ISD::XOR, DL, VT, N1, N2);
6428     break;
6429   case ISD::MUL:
6430     assert(VT.isInteger() && "This operator does not apply to FP types!");
6431     assert(N1.getValueType() == N2.getValueType() &&
6432            N1.getValueType() == VT && "Binary operator types must match!");
6433     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
6434       return getNode(ISD::AND, DL, VT, N1, N2);
6435     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
6436       const APInt &MulImm = N1->getConstantOperandAPInt(0);
6437       const APInt &N2CImm = N2C->getAPIntValue();
6438       return getVScale(DL, VT, MulImm * N2CImm);
6439     }
6440     break;
6441   case ISD::UDIV:
6442   case ISD::UREM:
6443   case ISD::MULHU:
6444   case ISD::MULHS:
6445   case ISD::SDIV:
6446   case ISD::SREM:
6447   case ISD::SADDSAT:
6448   case ISD::SSUBSAT:
6449   case ISD::UADDSAT:
6450   case ISD::USUBSAT:
6451     assert(VT.isInteger() && "This operator does not apply to FP types!");
6452     assert(N1.getValueType() == N2.getValueType() &&
6453            N1.getValueType() == VT && "Binary operator types must match!");
6454     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
6455       // fold (add_sat x, y) -> (or x, y) for bool types.
6456       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
6457         return getNode(ISD::OR, DL, VT, N1, N2);
6458       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
6459       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
6460         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
6461     }
6462     break;
6463   case ISD::ABDS:
6464   case ISD::ABDU:
6465     assert(VT.isInteger() && "This operator does not apply to FP types!");
6466     assert(N1.getValueType() == N2.getValueType() &&
6467            N1.getValueType() == VT && "Binary operator types must match!");
6468     break;
6469   case ISD::SMIN:
6470   case ISD::UMAX:
6471     assert(VT.isInteger() && "This operator does not apply to FP types!");
6472     assert(N1.getValueType() == N2.getValueType() &&
6473            N1.getValueType() == VT && "Binary operator types must match!");
6474     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
6475       return getNode(ISD::OR, DL, VT, N1, N2);
6476     break;
6477   case ISD::SMAX:
6478   case ISD::UMIN:
6479     assert(VT.isInteger() && "This operator does not apply to FP types!");
6480     assert(N1.getValueType() == N2.getValueType() &&
6481            N1.getValueType() == VT && "Binary operator types must match!");
6482     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
6483       return getNode(ISD::AND, DL, VT, N1, N2);
6484     break;
6485   case ISD::FADD:
6486   case ISD::FSUB:
6487   case ISD::FMUL:
6488   case ISD::FDIV:
6489   case ISD::FREM:
6490     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6491     assert(N1.getValueType() == N2.getValueType() &&
6492            N1.getValueType() == VT && "Binary operator types must match!");
6493     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
6494       return V;
6495     break;
6496   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
6497     assert(N1.getValueType() == VT &&
6498            N1.getValueType().isFloatingPoint() &&
6499            N2.getValueType().isFloatingPoint() &&
6500            "Invalid FCOPYSIGN!");
6501     break;
6502   case ISD::SHL:
6503     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
6504       const APInt &MulImm = N1->getConstantOperandAPInt(0);
6505       const APInt &ShiftImm = N2C->getAPIntValue();
6506       return getVScale(DL, VT, MulImm << ShiftImm);
6507     }
6508     [[fallthrough]];
6509   case ISD::SRA:
6510   case ISD::SRL:
6511     if (SDValue V = simplifyShift(N1, N2))
6512       return V;
6513     [[fallthrough]];
6514   case ISD::ROTL:
6515   case ISD::ROTR:
6516     assert(VT == N1.getValueType() &&
6517            "Shift operators return type must be the same as their first arg");
6518     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6519            "Shifts only work on integers");
6520     assert((!VT.isVector() || VT == N2.getValueType()) &&
6521            "Vector shift amounts must be in the same as their first arg");
6522     // Verify that the shift amount VT is big enough to hold valid shift
6523     // amounts.  This catches things like trying to shift an i1024 value by an
6524     // i8, which is easy to fall into in generic code that uses
6525     // TLI.getShiftAmount().
6526     assert(N2.getValueType().getScalarSizeInBits() >=
6527                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6528            "Invalid use of small shift amount with oversized value!");
6529 
6530     // Always fold shifts of i1 values so the code generator doesn't need to
6531     // handle them.  Since we know the size of the shift has to be less than the
6532     // size of the value, the shift/rotate count is guaranteed to be zero.
6533     if (VT == MVT::i1)
6534       return N1;
6535     if (N2CV && N2CV->isZero())
6536       return N1;
6537     break;
6538   case ISD::FP_ROUND:
6539     assert(VT.isFloatingPoint() &&
6540            N1.getValueType().isFloatingPoint() &&
6541            VT.bitsLE(N1.getValueType()) &&
6542            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6543            "Invalid FP_ROUND!");
6544     if (N1.getValueType() == VT) return N1;  // noop conversion.
6545     break;
6546   case ISD::AssertSext:
6547   case ISD::AssertZext: {
6548     EVT EVT = cast<VTSDNode>(N2)->getVT();
6549     assert(VT == N1.getValueType() && "Not an inreg extend!");
6550     assert(VT.isInteger() && EVT.isInteger() &&
6551            "Cannot *_EXTEND_INREG FP types");
6552     assert(!EVT.isVector() &&
6553            "AssertSExt/AssertZExt type should be the vector element type "
6554            "rather than the vector type!");
6555     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6556     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6557     break;
6558   }
6559   case ISD::SIGN_EXTEND_INREG: {
6560     EVT EVT = cast<VTSDNode>(N2)->getVT();
6561     assert(VT == N1.getValueType() && "Not an inreg extend!");
6562     assert(VT.isInteger() && EVT.isInteger() &&
6563            "Cannot *_EXTEND_INREG FP types");
6564     assert(EVT.isVector() == VT.isVector() &&
6565            "SIGN_EXTEND_INREG type should be vector iff the operand "
6566            "type is vector!");
6567     assert((!EVT.isVector() ||
6568             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6569            "Vector element counts must match in SIGN_EXTEND_INREG");
6570     assert(EVT.bitsLE(VT) && "Not extending!");
6571     if (EVT == VT) return N1;  // Not actually extending
6572 
6573     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6574       unsigned FromBits = EVT.getScalarSizeInBits();
6575       Val <<= Val.getBitWidth() - FromBits;
6576       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6577       return getConstant(Val, DL, ConstantVT);
6578     };
6579 
6580     if (N1C) {
6581       const APInt &Val = N1C->getAPIntValue();
6582       return SignExtendInReg(Val, VT);
6583     }
6584 
6585     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6586       SmallVector<SDValue, 8> Ops;
6587       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6588       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6589         SDValue Op = N1.getOperand(i);
6590         if (Op.isUndef()) {
6591           Ops.push_back(getUNDEF(OpVT));
6592           continue;
6593         }
6594         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6595         APInt Val = C->getAPIntValue();
6596         Ops.push_back(SignExtendInReg(Val, OpVT));
6597       }
6598       return getBuildVector(VT, DL, Ops);
6599     }
6600     break;
6601   }
6602   case ISD::FP_TO_SINT_SAT:
6603   case ISD::FP_TO_UINT_SAT: {
6604     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6605            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6606     assert(N1.getValueType().isVector() == VT.isVector() &&
6607            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6608            "vector!");
6609     assert((!VT.isVector() || VT.getVectorElementCount() ==
6610                                   N1.getValueType().getVectorElementCount()) &&
6611            "Vector element counts must match in FP_TO_*INT_SAT");
6612     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6613            "Type to saturate to must be a scalar.");
6614     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6615            "Not extending!");
6616     break;
6617   }
6618   case ISD::EXTRACT_VECTOR_ELT:
6619     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6620            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6621              element type of the vector.");
6622 
6623     // Extract from an undefined value or using an undefined index is undefined.
6624     if (N1.isUndef() || N2.isUndef())
6625       return getUNDEF(VT);
6626 
6627     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6628     // vectors. For scalable vectors we will provide appropriate support for
6629     // dealing with arbitrary indices.
6630     if (N2C && N1.getValueType().isFixedLengthVector() &&
6631         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6632       return getUNDEF(VT);
6633 
6634     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6635     // expanding copies of large vectors from registers. This only works for
6636     // fixed length vectors, since we need to know the exact number of
6637     // elements.
6638     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6639         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6640       unsigned Factor =
6641         N1.getOperand(0).getValueType().getVectorNumElements();
6642       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6643                      N1.getOperand(N2C->getZExtValue() / Factor),
6644                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6645     }
6646 
6647     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6648     // lowering is expanding large vector constants.
6649     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6650                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6651       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6652               N1.getValueType().isFixedLengthVector()) &&
6653              "BUILD_VECTOR used for scalable vectors");
6654       unsigned Index =
6655           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6656       SDValue Elt = N1.getOperand(Index);
6657 
6658       if (VT != Elt.getValueType())
6659         // If the vector element type is not legal, the BUILD_VECTOR operands
6660         // are promoted and implicitly truncated, and the result implicitly
6661         // extended. Make that explicit here.
6662         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6663 
6664       return Elt;
6665     }
6666 
6667     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6668     // operations are lowered to scalars.
6669     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6670       // If the indices are the same, return the inserted element else
6671       // if the indices are known different, extract the element from
6672       // the original vector.
6673       SDValue N1Op2 = N1.getOperand(2);
6674       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6675 
6676       if (N1Op2C && N2C) {
6677         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6678           if (VT == N1.getOperand(1).getValueType())
6679             return N1.getOperand(1);
6680           if (VT.isFloatingPoint()) {
6681             assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6682             return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6683           }
6684           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6685         }
6686         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6687       }
6688     }
6689 
6690     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6691     // when vector types are scalarized and v1iX is legal.
6692     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6693     // Here we are completely ignoring the extract element index (N2),
6694     // which is fine for fixed width vectors, since any index other than 0
6695     // is undefined anyway. However, this cannot be ignored for scalable
6696     // vectors - in theory we could support this, but we don't want to do this
6697     // without a profitability check.
6698     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6699         N1.getValueType().isFixedLengthVector() &&
6700         N1.getValueType().getVectorNumElements() == 1) {
6701       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6702                      N1.getOperand(1));
6703     }
6704     break;
6705   case ISD::EXTRACT_ELEMENT:
6706     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6707     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6708            (N1.getValueType().isInteger() == VT.isInteger()) &&
6709            N1.getValueType() != VT &&
6710            "Wrong types for EXTRACT_ELEMENT!");
6711 
6712     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6713     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6714     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6715     if (N1.getOpcode() == ISD::BUILD_PAIR)
6716       return N1.getOperand(N2C->getZExtValue());
6717 
6718     // EXTRACT_ELEMENT of a constant int is also very common.
6719     if (N1C) {
6720       unsigned ElementSize = VT.getSizeInBits();
6721       unsigned Shift = ElementSize * N2C->getZExtValue();
6722       const APInt &Val = N1C->getAPIntValue();
6723       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6724     }
6725     break;
6726   case ISD::EXTRACT_SUBVECTOR: {
6727     EVT N1VT = N1.getValueType();
6728     assert(VT.isVector() && N1VT.isVector() &&
6729            "Extract subvector VTs must be vectors!");
6730     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6731            "Extract subvector VTs must have the same element type!");
6732     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6733            "Cannot extract a scalable vector from a fixed length vector!");
6734     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6735             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6736            "Extract subvector must be from larger vector to smaller vector!");
6737     assert(N2C && "Extract subvector index must be a constant");
6738     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6739             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6740                 N1VT.getVectorMinNumElements()) &&
6741            "Extract subvector overflow!");
6742     assert(N2C->getAPIntValue().getBitWidth() ==
6743                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6744            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6745 
6746     // Trivial extraction.
6747     if (VT == N1VT)
6748       return N1;
6749 
6750     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6751     if (N1.isUndef())
6752       return getUNDEF(VT);
6753 
6754     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6755     // the concat have the same type as the extract.
6756     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6757         VT == N1.getOperand(0).getValueType()) {
6758       unsigned Factor = VT.getVectorMinNumElements();
6759       return N1.getOperand(N2C->getZExtValue() / Factor);
6760     }
6761 
6762     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6763     // during shuffle legalization.
6764     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6765         VT == N1.getOperand(1).getValueType())
6766       return N1.getOperand(1);
6767     break;
6768   }
6769   }
6770 
6771   // Perform trivial constant folding.
6772   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6773     return SV;
6774 
6775   // Canonicalize an UNDEF to the RHS, even over a constant.
6776   if (N1.isUndef()) {
6777     if (TLI->isCommutativeBinOp(Opcode)) {
6778       std::swap(N1, N2);
6779     } else {
6780       switch (Opcode) {
6781       case ISD::SUB:
6782         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6783       case ISD::SIGN_EXTEND_INREG:
6784       case ISD::UDIV:
6785       case ISD::SDIV:
6786       case ISD::UREM:
6787       case ISD::SREM:
6788       case ISD::SSUBSAT:
6789       case ISD::USUBSAT:
6790         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6791       }
6792     }
6793   }
6794 
6795   // Fold a bunch of operators when the RHS is undef.
6796   if (N2.isUndef()) {
6797     switch (Opcode) {
6798     case ISD::XOR:
6799       if (N1.isUndef())
6800         // Handle undef ^ undef -> 0 special case. This is a common
6801         // idiom (misuse).
6802         return getConstant(0, DL, VT);
6803       [[fallthrough]];
6804     case ISD::ADD:
6805     case ISD::SUB:
6806     case ISD::UDIV:
6807     case ISD::SDIV:
6808     case ISD::UREM:
6809     case ISD::SREM:
6810       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6811     case ISD::MUL:
6812     case ISD::AND:
6813     case ISD::SSUBSAT:
6814     case ISD::USUBSAT:
6815       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6816     case ISD::OR:
6817     case ISD::SADDSAT:
6818     case ISD::UADDSAT:
6819       return getAllOnesConstant(DL, VT);
6820     }
6821   }
6822 
6823   // Memoize this node if possible.
6824   SDNode *N;
6825   SDVTList VTs = getVTList(VT);
6826   SDValue Ops[] = {N1, N2};
6827   if (VT != MVT::Glue) {
6828     FoldingSetNodeID ID;
6829     AddNodeIDNode(ID, Opcode, VTs, Ops);
6830     void *IP = nullptr;
6831     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6832       E->intersectFlagsWith(Flags);
6833       return SDValue(E, 0);
6834     }
6835 
6836     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6837     N->setFlags(Flags);
6838     createOperands(N, Ops);
6839     CSEMap.InsertNode(N, IP);
6840   } else {
6841     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6842     createOperands(N, Ops);
6843   }
6844 
6845   InsertNode(N);
6846   SDValue V = SDValue(N, 0);
6847   NewSDValueDbgMsg(V, "Creating new node: ", this);
6848   return V;
6849 }
6850 
6851 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6852                               SDValue N1, SDValue N2, SDValue N3) {
6853   SDNodeFlags Flags;
6854   if (Inserter)
6855     Flags = Inserter->getFlags();
6856   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6857 }
6858 
6859 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6860                               SDValue N1, SDValue N2, SDValue N3,
6861                               const SDNodeFlags Flags) {
6862   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6863          N2.getOpcode() != ISD::DELETED_NODE &&
6864          N3.getOpcode() != ISD::DELETED_NODE &&
6865          "Operand is DELETED_NODE!");
6866   // Perform various simplifications.
6867   switch (Opcode) {
6868   case ISD::FMA: {
6869     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6870     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6871            N3.getValueType() == VT && "FMA types must match!");
6872     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6873     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6874     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6875     if (N1CFP && N2CFP && N3CFP) {
6876       APFloat  V1 = N1CFP->getValueAPF();
6877       const APFloat &V2 = N2CFP->getValueAPF();
6878       const APFloat &V3 = N3CFP->getValueAPF();
6879       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6880       return getConstantFP(V1, DL, VT);
6881     }
6882     break;
6883   }
6884   case ISD::BUILD_VECTOR: {
6885     // Attempt to simplify BUILD_VECTOR.
6886     SDValue Ops[] = {N1, N2, N3};
6887     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6888       return V;
6889     break;
6890   }
6891   case ISD::CONCAT_VECTORS: {
6892     SDValue Ops[] = {N1, N2, N3};
6893     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6894       return V;
6895     break;
6896   }
6897   case ISD::SETCC: {
6898     assert(VT.isInteger() && "SETCC result type must be an integer!");
6899     assert(N1.getValueType() == N2.getValueType() &&
6900            "SETCC operands must have the same type!");
6901     assert(VT.isVector() == N1.getValueType().isVector() &&
6902            "SETCC type should be vector iff the operand type is vector!");
6903     assert((!VT.isVector() || VT.getVectorElementCount() ==
6904                                   N1.getValueType().getVectorElementCount()) &&
6905            "SETCC vector element counts must match!");
6906     // Use FoldSetCC to simplify SETCC's.
6907     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6908       return V;
6909     // Vector constant folding.
6910     SDValue Ops[] = {N1, N2, N3};
6911     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6912       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6913       return V;
6914     }
6915     break;
6916   }
6917   case ISD::SELECT:
6918   case ISD::VSELECT:
6919     if (SDValue V = simplifySelect(N1, N2, N3))
6920       return V;
6921     break;
6922   case ISD::VECTOR_SHUFFLE:
6923     llvm_unreachable("should use getVectorShuffle constructor!");
6924   case ISD::VECTOR_SPLICE: {
6925     if (cast<ConstantSDNode>(N3)->isZero())
6926       return N1;
6927     break;
6928   }
6929   case ISD::INSERT_VECTOR_ELT: {
6930     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6931     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6932     // for scalable vectors where we will generate appropriate code to
6933     // deal with out-of-bounds cases correctly.
6934     if (N3C && N1.getValueType().isFixedLengthVector() &&
6935         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6936       return getUNDEF(VT);
6937 
6938     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6939     if (N3.isUndef())
6940       return getUNDEF(VT);
6941 
6942     // If the inserted element is an UNDEF, just use the input vector.
6943     if (N2.isUndef())
6944       return N1;
6945 
6946     break;
6947   }
6948   case ISD::INSERT_SUBVECTOR: {
6949     // Inserting undef into undef is still undef.
6950     if (N1.isUndef() && N2.isUndef())
6951       return getUNDEF(VT);
6952 
6953     EVT N2VT = N2.getValueType();
6954     assert(VT == N1.getValueType() &&
6955            "Dest and insert subvector source types must match!");
6956     assert(VT.isVector() && N2VT.isVector() &&
6957            "Insert subvector VTs must be vectors!");
6958     assert(VT.getVectorElementType() == N2VT.getVectorElementType() &&
6959            "Insert subvector VTs must have the same element type!");
6960     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6961            "Cannot insert a scalable vector into a fixed length vector!");
6962     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6963             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6964            "Insert subvector must be from smaller vector to larger vector!");
6965     assert(isa<ConstantSDNode>(N3) &&
6966            "Insert subvector index must be constant");
6967     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6968             (N2VT.getVectorMinNumElements() +
6969              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6970                 VT.getVectorMinNumElements()) &&
6971            "Insert subvector overflow!");
6972     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6973                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6974            "Constant index for INSERT_SUBVECTOR has an invalid size");
6975 
6976     // Trivial insertion.
6977     if (VT == N2VT)
6978       return N2;
6979 
6980     // If this is an insert of an extracted vector into an undef vector, we
6981     // can just use the input to the extract.
6982     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6983         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6984       return N2.getOperand(0);
6985     break;
6986   }
6987   case ISD::BITCAST:
6988     // Fold bit_convert nodes from a type to themselves.
6989     if (N1.getValueType() == VT)
6990       return N1;
6991     break;
6992   case ISD::VP_TRUNCATE:
6993   case ISD::VP_SIGN_EXTEND:
6994   case ISD::VP_ZERO_EXTEND:
6995     // Don't create noop casts.
6996     if (N1.getValueType() == VT)
6997       return N1;
6998     break;
6999   }
7000 
7001   // Memoize node if it doesn't produce a flag.
7002   SDNode *N;
7003   SDVTList VTs = getVTList(VT);
7004   SDValue Ops[] = {N1, N2, N3};
7005   if (VT != MVT::Glue) {
7006     FoldingSetNodeID ID;
7007     AddNodeIDNode(ID, Opcode, VTs, Ops);
7008     void *IP = nullptr;
7009     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7010       E->intersectFlagsWith(Flags);
7011       return SDValue(E, 0);
7012     }
7013 
7014     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7015     N->setFlags(Flags);
7016     createOperands(N, Ops);
7017     CSEMap.InsertNode(N, IP);
7018   } else {
7019     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7020     createOperands(N, Ops);
7021   }
7022 
7023   InsertNode(N);
7024   SDValue V = SDValue(N, 0);
7025   NewSDValueDbgMsg(V, "Creating new node: ", this);
7026   return V;
7027 }
7028 
7029 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7030                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7031   SDValue Ops[] = { N1, N2, N3, N4 };
7032   return getNode(Opcode, DL, VT, Ops);
7033 }
7034 
7035 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7036                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7037                               SDValue N5) {
7038   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7039   return getNode(Opcode, DL, VT, Ops);
7040 }
7041 
7042 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
7043 /// the incoming stack arguments to be loaded from the stack.
7044 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
7045   SmallVector<SDValue, 8> ArgChains;
7046 
7047   // Include the original chain at the beginning of the list. When this is
7048   // used by target LowerCall hooks, this helps legalize find the
7049   // CALLSEQ_BEGIN node.
7050   ArgChains.push_back(Chain);
7051 
7052   // Add a chain value for each stack argument.
7053   for (SDNode *U : getEntryNode().getNode()->uses())
7054     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
7055       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
7056         if (FI->getIndex() < 0)
7057           ArgChains.push_back(SDValue(L, 1));
7058 
7059   // Build a tokenfactor for all the chains.
7060   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
7061 }
7062 
7063 /// getMemsetValue - Vectorized representation of the memset value
7064 /// operand.
7065 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
7066                               const SDLoc &dl) {
7067   assert(!Value.isUndef());
7068 
7069   unsigned NumBits = VT.getScalarSizeInBits();
7070   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
7071     assert(C->getAPIntValue().getBitWidth() == 8);
7072     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
7073     if (VT.isInteger()) {
7074       bool IsOpaque = VT.getSizeInBits() > 64 ||
7075           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
7076       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
7077     }
7078     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
7079                              VT);
7080   }
7081 
7082   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
7083   EVT IntVT = VT.getScalarType();
7084   if (!IntVT.isInteger())
7085     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
7086 
7087   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
7088   if (NumBits > 8) {
7089     // Use a multiplication with 0x010101... to extend the input to the
7090     // required length.
7091     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
7092     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
7093                         DAG.getConstant(Magic, dl, IntVT));
7094   }
7095 
7096   if (VT != Value.getValueType() && !VT.isInteger())
7097     Value = DAG.getBitcast(VT.getScalarType(), Value);
7098   if (VT != Value.getValueType())
7099     Value = DAG.getSplatBuildVector(VT, dl, Value);
7100 
7101   return Value;
7102 }
7103 
7104 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
7105 /// used when a memcpy is turned into a memset when the source is a constant
7106 /// string ptr.
7107 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
7108                                   const TargetLowering &TLI,
7109                                   const ConstantDataArraySlice &Slice) {
7110   // Handle vector with all elements zero.
7111   if (Slice.Array == nullptr) {
7112     if (VT.isInteger())
7113       return DAG.getConstant(0, dl, VT);
7114     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
7115       return DAG.getConstantFP(0.0, dl, VT);
7116     if (VT.isVector()) {
7117       unsigned NumElts = VT.getVectorNumElements();
7118       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
7119       return DAG.getNode(ISD::BITCAST, dl, VT,
7120                          DAG.getConstant(0, dl,
7121                                          EVT::getVectorVT(*DAG.getContext(),
7122                                                           EltVT, NumElts)));
7123     }
7124     llvm_unreachable("Expected type!");
7125   }
7126 
7127   assert(!VT.isVector() && "Can't handle vector type here!");
7128   unsigned NumVTBits = VT.getSizeInBits();
7129   unsigned NumVTBytes = NumVTBits / 8;
7130   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
7131 
7132   APInt Val(NumVTBits, 0);
7133   if (DAG.getDataLayout().isLittleEndian()) {
7134     for (unsigned i = 0; i != NumBytes; ++i)
7135       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
7136   } else {
7137     for (unsigned i = 0; i != NumBytes; ++i)
7138       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
7139   }
7140 
7141   // If the "cost" of materializing the integer immediate is less than the cost
7142   // of a load, then it is cost effective to turn the load into the immediate.
7143   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
7144   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
7145     return DAG.getConstant(Val, dl, VT);
7146   return SDValue();
7147 }
7148 
7149 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
7150                                            const SDLoc &DL,
7151                                            const SDNodeFlags Flags) {
7152   EVT VT = Base.getValueType();
7153   SDValue Index;
7154 
7155   if (Offset.isScalable())
7156     Index = getVScale(DL, Base.getValueType(),
7157                       APInt(Base.getValueSizeInBits().getFixedValue(),
7158                             Offset.getKnownMinValue()));
7159   else
7160     Index = getConstant(Offset.getFixedValue(), DL, VT);
7161 
7162   return getMemBasePlusOffset(Base, Index, DL, Flags);
7163 }
7164 
7165 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
7166                                            const SDLoc &DL,
7167                                            const SDNodeFlags Flags) {
7168   assert(Offset.getValueType().isInteger());
7169   EVT BasePtrVT = Ptr.getValueType();
7170   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
7171 }
7172 
7173 /// Returns true if memcpy source is constant data.
7174 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
7175   uint64_t SrcDelta = 0;
7176   GlobalAddressSDNode *G = nullptr;
7177   if (Src.getOpcode() == ISD::GlobalAddress)
7178     G = cast<GlobalAddressSDNode>(Src);
7179   else if (Src.getOpcode() == ISD::ADD &&
7180            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
7181            Src.getOperand(1).getOpcode() == ISD::Constant) {
7182     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
7183     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
7184   }
7185   if (!G)
7186     return false;
7187 
7188   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
7189                                   SrcDelta + G->getOffset());
7190 }
7191 
7192 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
7193                                       SelectionDAG &DAG) {
7194   // On Darwin, -Os means optimize for size without hurting performance, so
7195   // only really optimize for size when -Oz (MinSize) is used.
7196   if (MF.getTarget().getTargetTriple().isOSDarwin())
7197     return MF.getFunction().hasMinSize();
7198   return DAG.shouldOptForSize();
7199 }
7200 
7201 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
7202                           SmallVector<SDValue, 32> &OutChains, unsigned From,
7203                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
7204                           SmallVector<SDValue, 16> &OutStoreChains) {
7205   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
7206   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
7207   SmallVector<SDValue, 16> GluedLoadChains;
7208   for (unsigned i = From; i < To; ++i) {
7209     OutChains.push_back(OutLoadChains[i]);
7210     GluedLoadChains.push_back(OutLoadChains[i]);
7211   }
7212 
7213   // Chain for all loads.
7214   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7215                                   GluedLoadChains);
7216 
7217   for (unsigned i = From; i < To; ++i) {
7218     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
7219     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
7220                                   ST->getBasePtr(), ST->getMemoryVT(),
7221                                   ST->getMemOperand());
7222     OutChains.push_back(NewStore);
7223   }
7224 }
7225 
7226 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
7227                                        SDValue Chain, SDValue Dst, SDValue Src,
7228                                        uint64_t Size, Align Alignment,
7229                                        bool isVol, bool AlwaysInline,
7230                                        MachinePointerInfo DstPtrInfo,
7231                                        MachinePointerInfo SrcPtrInfo,
7232                                        const AAMDNodes &AAInfo, AAResults *AA) {
7233   // Turn a memcpy of undef to nop.
7234   // FIXME: We need to honor volatile even is Src is undef.
7235   if (Src.isUndef())
7236     return Chain;
7237 
7238   // Expand memcpy to a series of load and store ops if the size operand falls
7239   // below a certain threshold.
7240   // TODO: In the AlwaysInline case, if the size is big then generate a loop
7241   // rather than maybe a humongous number of loads and stores.
7242   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7243   const DataLayout &DL = DAG.getDataLayout();
7244   LLVMContext &C = *DAG.getContext();
7245   std::vector<EVT> MemOps;
7246   bool DstAlignCanChange = false;
7247   MachineFunction &MF = DAG.getMachineFunction();
7248   MachineFrameInfo &MFI = MF.getFrameInfo();
7249   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7250   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7251   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7252     DstAlignCanChange = true;
7253   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
7254   if (!SrcAlign || Alignment > *SrcAlign)
7255     SrcAlign = Alignment;
7256   assert(SrcAlign && "SrcAlign must be set");
7257   ConstantDataArraySlice Slice;
7258   // If marked as volatile, perform a copy even when marked as constant.
7259   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
7260   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
7261   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
7262   const MemOp Op = isZeroConstant
7263                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
7264                                     /*IsZeroMemset*/ true, isVol)
7265                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
7266                                      *SrcAlign, isVol, CopyFromConstant);
7267   if (!TLI.findOptimalMemOpLowering(
7268           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
7269           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
7270     return SDValue();
7271 
7272   if (DstAlignCanChange) {
7273     Type *Ty = MemOps[0].getTypeForEVT(C);
7274     Align NewAlign = DL.getABITypeAlign(Ty);
7275 
7276     // Don't promote to an alignment that would require dynamic stack
7277     // realignment which may conflict with optimizations such as tail call
7278     // optimization.
7279     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
7280     if (!TRI->hasStackRealignment(MF))
7281       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
7282         NewAlign = NewAlign.previous();
7283 
7284     if (NewAlign > Alignment) {
7285       // Give the stack frame object a larger alignment if needed.
7286       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7287         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7288       Alignment = NewAlign;
7289     }
7290   }
7291 
7292   // Prepare AAInfo for loads/stores after lowering this memcpy.
7293   AAMDNodes NewAAInfo = AAInfo;
7294   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7295 
7296   const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
7297   bool isConstant =
7298       AA && SrcVal &&
7299       AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
7300 
7301   MachineMemOperand::Flags MMOFlags =
7302       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
7303   SmallVector<SDValue, 16> OutLoadChains;
7304   SmallVector<SDValue, 16> OutStoreChains;
7305   SmallVector<SDValue, 32> OutChains;
7306   unsigned NumMemOps = MemOps.size();
7307   uint64_t SrcOff = 0, DstOff = 0;
7308   for (unsigned i = 0; i != NumMemOps; ++i) {
7309     EVT VT = MemOps[i];
7310     unsigned VTSize = VT.getSizeInBits() / 8;
7311     SDValue Value, Store;
7312 
7313     if (VTSize > Size) {
7314       // Issuing an unaligned load / store pair  that overlaps with the previous
7315       // pair. Adjust the offset accordingly.
7316       assert(i == NumMemOps-1 && i != 0);
7317       SrcOff -= VTSize - Size;
7318       DstOff -= VTSize - Size;
7319     }
7320 
7321     if (CopyFromConstant &&
7322         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
7323       // It's unlikely a store of a vector immediate can be done in a single
7324       // instruction. It would require a load from a constantpool first.
7325       // We only handle zero vectors here.
7326       // FIXME: Handle other cases where store of vector immediate is done in
7327       // a single instruction.
7328       ConstantDataArraySlice SubSlice;
7329       if (SrcOff < Slice.Length) {
7330         SubSlice = Slice;
7331         SubSlice.move(SrcOff);
7332       } else {
7333         // This is an out-of-bounds access and hence UB. Pretend we read zero.
7334         SubSlice.Array = nullptr;
7335         SubSlice.Offset = 0;
7336         SubSlice.Length = VTSize;
7337       }
7338       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
7339       if (Value.getNode()) {
7340         Store = DAG.getStore(
7341             Chain, dl, Value,
7342             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7343             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
7344         OutChains.push_back(Store);
7345       }
7346     }
7347 
7348     if (!Store.getNode()) {
7349       // The type might not be legal for the target.  This should only happen
7350       // if the type is smaller than a legal type, as on PPC, so the right
7351       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
7352       // to Load/Store if NVT==VT.
7353       // FIXME does the case above also need this?
7354       EVT NVT = TLI.getTypeToTransformTo(C, VT);
7355       assert(NVT.bitsGE(VT));
7356 
7357       bool isDereferenceable =
7358         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
7359       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
7360       if (isDereferenceable)
7361         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
7362       if (isConstant)
7363         SrcMMOFlags |= MachineMemOperand::MOInvariant;
7364 
7365       Value = DAG.getExtLoad(
7366           ISD::EXTLOAD, dl, NVT, Chain,
7367           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
7368           SrcPtrInfo.getWithOffset(SrcOff), VT,
7369           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
7370       OutLoadChains.push_back(Value.getValue(1));
7371 
7372       Store = DAG.getTruncStore(
7373           Chain, dl, Value,
7374           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7375           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
7376       OutStoreChains.push_back(Store);
7377     }
7378     SrcOff += VTSize;
7379     DstOff += VTSize;
7380     Size -= VTSize;
7381   }
7382 
7383   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
7384                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
7385   unsigned NumLdStInMemcpy = OutStoreChains.size();
7386 
7387   if (NumLdStInMemcpy) {
7388     // It may be that memcpy might be converted to memset if it's memcpy
7389     // of constants. In such a case, we won't have loads and stores, but
7390     // just stores. In the absence of loads, there is nothing to gang up.
7391     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
7392       // If target does not care, just leave as it.
7393       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
7394         OutChains.push_back(OutLoadChains[i]);
7395         OutChains.push_back(OutStoreChains[i]);
7396       }
7397     } else {
7398       // Ld/St less than/equal limit set by target.
7399       if (NumLdStInMemcpy <= GluedLdStLimit) {
7400           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
7401                                         NumLdStInMemcpy, OutLoadChains,
7402                                         OutStoreChains);
7403       } else {
7404         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
7405         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
7406         unsigned GlueIter = 0;
7407 
7408         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
7409           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
7410           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
7411 
7412           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
7413                                        OutLoadChains, OutStoreChains);
7414           GlueIter += GluedLdStLimit;
7415         }
7416 
7417         // Residual ld/st.
7418         if (RemainingLdStInMemcpy) {
7419           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
7420                                         RemainingLdStInMemcpy, OutLoadChains,
7421                                         OutStoreChains);
7422         }
7423       }
7424     }
7425   }
7426   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7427 }
7428 
7429 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
7430                                         SDValue Chain, SDValue Dst, SDValue Src,
7431                                         uint64_t Size, Align Alignment,
7432                                         bool isVol, bool AlwaysInline,
7433                                         MachinePointerInfo DstPtrInfo,
7434                                         MachinePointerInfo SrcPtrInfo,
7435                                         const AAMDNodes &AAInfo) {
7436   // Turn a memmove of undef to nop.
7437   // FIXME: We need to honor volatile even is Src is undef.
7438   if (Src.isUndef())
7439     return Chain;
7440 
7441   // Expand memmove to a series of load and store ops if the size operand falls
7442   // below a certain threshold.
7443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7444   const DataLayout &DL = DAG.getDataLayout();
7445   LLVMContext &C = *DAG.getContext();
7446   std::vector<EVT> MemOps;
7447   bool DstAlignCanChange = false;
7448   MachineFunction &MF = DAG.getMachineFunction();
7449   MachineFrameInfo &MFI = MF.getFrameInfo();
7450   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7451   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7452   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7453     DstAlignCanChange = true;
7454   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
7455   if (!SrcAlign || Alignment > *SrcAlign)
7456     SrcAlign = Alignment;
7457   assert(SrcAlign && "SrcAlign must be set");
7458   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
7459   if (!TLI.findOptimalMemOpLowering(
7460           MemOps, Limit,
7461           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
7462                       /*IsVolatile*/ true),
7463           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
7464           MF.getFunction().getAttributes()))
7465     return SDValue();
7466 
7467   if (DstAlignCanChange) {
7468     Type *Ty = MemOps[0].getTypeForEVT(C);
7469     Align NewAlign = DL.getABITypeAlign(Ty);
7470 
7471     // Don't promote to an alignment that would require dynamic stack
7472     // realignment which may conflict with optimizations such as tail call
7473     // optimization.
7474     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
7475     if (!TRI->hasStackRealignment(MF))
7476       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
7477         NewAlign = NewAlign.previous();
7478 
7479     if (NewAlign > Alignment) {
7480       // Give the stack frame object a larger alignment if needed.
7481       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7482         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7483       Alignment = NewAlign;
7484     }
7485   }
7486 
7487   // Prepare AAInfo for loads/stores after lowering this memmove.
7488   AAMDNodes NewAAInfo = AAInfo;
7489   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7490 
7491   MachineMemOperand::Flags MMOFlags =
7492       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
7493   uint64_t SrcOff = 0, DstOff = 0;
7494   SmallVector<SDValue, 8> LoadValues;
7495   SmallVector<SDValue, 8> LoadChains;
7496   SmallVector<SDValue, 8> OutChains;
7497   unsigned NumMemOps = MemOps.size();
7498   for (unsigned i = 0; i < NumMemOps; i++) {
7499     EVT VT = MemOps[i];
7500     unsigned VTSize = VT.getSizeInBits() / 8;
7501     SDValue Value;
7502 
7503     bool isDereferenceable =
7504       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
7505     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
7506     if (isDereferenceable)
7507       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
7508 
7509     Value = DAG.getLoad(
7510         VT, dl, Chain,
7511         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
7512         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
7513     LoadValues.push_back(Value);
7514     LoadChains.push_back(Value.getValue(1));
7515     SrcOff += VTSize;
7516   }
7517   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7518   OutChains.clear();
7519   for (unsigned i = 0; i < NumMemOps; i++) {
7520     EVT VT = MemOps[i];
7521     unsigned VTSize = VT.getSizeInBits() / 8;
7522     SDValue Store;
7523 
7524     Store = DAG.getStore(
7525         Chain, dl, LoadValues[i],
7526         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7527         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
7528     OutChains.push_back(Store);
7529     DstOff += VTSize;
7530   }
7531 
7532   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7533 }
7534 
7535 /// Lower the call to 'memset' intrinsic function into a series of store
7536 /// operations.
7537 ///
7538 /// \param DAG Selection DAG where lowered code is placed.
7539 /// \param dl Link to corresponding IR location.
7540 /// \param Chain Control flow dependency.
7541 /// \param Dst Pointer to destination memory location.
7542 /// \param Src Value of byte to write into the memory.
7543 /// \param Size Number of bytes to write.
7544 /// \param Alignment Alignment of the destination in bytes.
7545 /// \param isVol True if destination is volatile.
7546 /// \param AlwaysInline Makes sure no function call is generated.
7547 /// \param DstPtrInfo IR information on the memory pointer.
7548 /// \returns New head in the control flow, if lowering was successful, empty
7549 /// SDValue otherwise.
7550 ///
7551 /// The function tries to replace 'llvm.memset' intrinsic with several store
7552 /// operations and value calculation code. This is usually profitable for small
7553 /// memory size or when the semantic requires inlining.
7554 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7555                                SDValue Chain, SDValue Dst, SDValue Src,
7556                                uint64_t Size, Align Alignment, bool isVol,
7557                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7558                                const AAMDNodes &AAInfo) {
7559   // Turn a memset of undef to nop.
7560   // FIXME: We need to honor volatile even is Src is undef.
7561   if (Src.isUndef())
7562     return Chain;
7563 
7564   // Expand memset to a series of load/store ops if the size operand
7565   // falls below a certain threshold.
7566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7567   std::vector<EVT> MemOps;
7568   bool DstAlignCanChange = false;
7569   MachineFunction &MF = DAG.getMachineFunction();
7570   MachineFrameInfo &MFI = MF.getFrameInfo();
7571   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7572   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7573   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7574     DstAlignCanChange = true;
7575   bool IsZeroVal = isNullConstant(Src);
7576   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7577 
7578   if (!TLI.findOptimalMemOpLowering(
7579           MemOps, Limit,
7580           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7581           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7582     return SDValue();
7583 
7584   if (DstAlignCanChange) {
7585     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7586     const DataLayout &DL = DAG.getDataLayout();
7587     Align NewAlign = DL.getABITypeAlign(Ty);
7588 
7589     // Don't promote to an alignment that would require dynamic stack
7590     // realignment which may conflict with optimizations such as tail call
7591     // optimization.
7592     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
7593     if (!TRI->hasStackRealignment(MF))
7594       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
7595         NewAlign = NewAlign.previous();
7596 
7597     if (NewAlign > Alignment) {
7598       // Give the stack frame object a larger alignment if needed.
7599       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7600         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7601       Alignment = NewAlign;
7602     }
7603   }
7604 
7605   SmallVector<SDValue, 8> OutChains;
7606   uint64_t DstOff = 0;
7607   unsigned NumMemOps = MemOps.size();
7608 
7609   // Find the largest store and generate the bit pattern for it.
7610   EVT LargestVT = MemOps[0];
7611   for (unsigned i = 1; i < NumMemOps; i++)
7612     if (MemOps[i].bitsGT(LargestVT))
7613       LargestVT = MemOps[i];
7614   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7615 
7616   // Prepare AAInfo for loads/stores after lowering this memset.
7617   AAMDNodes NewAAInfo = AAInfo;
7618   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7619 
7620   for (unsigned i = 0; i < NumMemOps; i++) {
7621     EVT VT = MemOps[i];
7622     unsigned VTSize = VT.getSizeInBits() / 8;
7623     if (VTSize > Size) {
7624       // Issuing an unaligned load / store pair  that overlaps with the previous
7625       // pair. Adjust the offset accordingly.
7626       assert(i == NumMemOps-1 && i != 0);
7627       DstOff -= VTSize - Size;
7628     }
7629 
7630     // If this store is smaller than the largest store see whether we can get
7631     // the smaller value for free with a truncate.
7632     SDValue Value = MemSetValue;
7633     if (VT.bitsLT(LargestVT)) {
7634       if (!LargestVT.isVector() && !VT.isVector() &&
7635           TLI.isTruncateFree(LargestVT, VT))
7636         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7637       else
7638         Value = getMemsetValue(Src, VT, DAG, dl);
7639     }
7640     assert(Value.getValueType() == VT && "Value with wrong type.");
7641     SDValue Store = DAG.getStore(
7642         Chain, dl, Value,
7643         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7644         DstPtrInfo.getWithOffset(DstOff), Alignment,
7645         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7646         NewAAInfo);
7647     OutChains.push_back(Store);
7648     DstOff += VT.getSizeInBits() / 8;
7649     Size -= VTSize;
7650   }
7651 
7652   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7653 }
7654 
7655 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7656                                             unsigned AS) {
7657   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7658   // pointer operands can be losslessly bitcasted to pointers of address space 0
7659   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7660     report_fatal_error("cannot lower memory intrinsic in address space " +
7661                        Twine(AS));
7662   }
7663 }
7664 
7665 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7666                                 SDValue Src, SDValue Size, Align Alignment,
7667                                 bool isVol, bool AlwaysInline, bool isTailCall,
7668                                 MachinePointerInfo DstPtrInfo,
7669                                 MachinePointerInfo SrcPtrInfo,
7670                                 const AAMDNodes &AAInfo, AAResults *AA) {
7671   // Check to see if we should lower the memcpy to loads and stores first.
7672   // For cases within the target-specified limits, this is the best choice.
7673   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7674   if (ConstantSize) {
7675     // Memcpy with size zero? Just return the original chain.
7676     if (ConstantSize->isZero())
7677       return Chain;
7678 
7679     SDValue Result = getMemcpyLoadsAndStores(
7680         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7681         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7682     if (Result.getNode())
7683       return Result;
7684   }
7685 
7686   // Then check to see if we should lower the memcpy with target-specific
7687   // code. If the target chooses to do this, this is the next best.
7688   if (TSI) {
7689     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7690         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7691         DstPtrInfo, SrcPtrInfo);
7692     if (Result.getNode())
7693       return Result;
7694   }
7695 
7696   // If we really need inline code and the target declined to provide it,
7697   // use a (potentially long) sequence of loads and stores.
7698   if (AlwaysInline) {
7699     assert(ConstantSize && "AlwaysInline requires a constant size!");
7700     return getMemcpyLoadsAndStores(
7701         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7702         isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7703   }
7704 
7705   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7706   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7707 
7708   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7709   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7710   // respect volatile, so they may do things like read or write memory
7711   // beyond the given memory regions. But fixing this isn't easy, and most
7712   // people don't care.
7713 
7714   // Emit a library call.
7715   TargetLowering::ArgListTy Args;
7716   TargetLowering::ArgListEntry Entry;
7717   Entry.Ty = Type::getInt8PtrTy(*getContext());
7718   Entry.Node = Dst; Args.push_back(Entry);
7719   Entry.Node = Src; Args.push_back(Entry);
7720 
7721   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7722   Entry.Node = Size; Args.push_back(Entry);
7723   // FIXME: pass in SDLoc
7724   TargetLowering::CallLoweringInfo CLI(*this);
7725   CLI.setDebugLoc(dl)
7726       .setChain(Chain)
7727       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7728                     Dst.getValueType().getTypeForEVT(*getContext()),
7729                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7730                                       TLI->getPointerTy(getDataLayout())),
7731                     std::move(Args))
7732       .setDiscardResult()
7733       .setTailCall(isTailCall);
7734 
7735   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7736   return CallResult.second;
7737 }
7738 
7739 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7740                                       SDValue Dst, SDValue Src, SDValue Size,
7741                                       Type *SizeTy, unsigned ElemSz,
7742                                       bool isTailCall,
7743                                       MachinePointerInfo DstPtrInfo,
7744                                       MachinePointerInfo SrcPtrInfo) {
7745   // Emit a library call.
7746   TargetLowering::ArgListTy Args;
7747   TargetLowering::ArgListEntry Entry;
7748   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7749   Entry.Node = Dst;
7750   Args.push_back(Entry);
7751 
7752   Entry.Node = Src;
7753   Args.push_back(Entry);
7754 
7755   Entry.Ty = SizeTy;
7756   Entry.Node = Size;
7757   Args.push_back(Entry);
7758 
7759   RTLIB::Libcall LibraryCall =
7760       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7761   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7762     report_fatal_error("Unsupported element size");
7763 
7764   TargetLowering::CallLoweringInfo CLI(*this);
7765   CLI.setDebugLoc(dl)
7766       .setChain(Chain)
7767       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7768                     Type::getVoidTy(*getContext()),
7769                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7770                                       TLI->getPointerTy(getDataLayout())),
7771                     std::move(Args))
7772       .setDiscardResult()
7773       .setTailCall(isTailCall);
7774 
7775   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7776   return CallResult.second;
7777 }
7778 
7779 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7780                                  SDValue Src, SDValue Size, Align Alignment,
7781                                  bool isVol, bool isTailCall,
7782                                  MachinePointerInfo DstPtrInfo,
7783                                  MachinePointerInfo SrcPtrInfo,
7784                                  const AAMDNodes &AAInfo, AAResults *AA) {
7785   // Check to see if we should lower the memmove to loads and stores first.
7786   // For cases within the target-specified limits, this is the best choice.
7787   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7788   if (ConstantSize) {
7789     // Memmove with size zero? Just return the original chain.
7790     if (ConstantSize->isZero())
7791       return Chain;
7792 
7793     SDValue Result = getMemmoveLoadsAndStores(
7794         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7795         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7796     if (Result.getNode())
7797       return Result;
7798   }
7799 
7800   // Then check to see if we should lower the memmove with target-specific
7801   // code. If the target chooses to do this, this is the next best.
7802   if (TSI) {
7803     SDValue Result =
7804         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7805                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7806     if (Result.getNode())
7807       return Result;
7808   }
7809 
7810   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7811   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7812 
7813   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7814   // not be safe.  See memcpy above for more details.
7815 
7816   // Emit a library call.
7817   TargetLowering::ArgListTy Args;
7818   TargetLowering::ArgListEntry Entry;
7819   Entry.Ty = Type::getInt8PtrTy(*getContext());
7820   Entry.Node = Dst; Args.push_back(Entry);
7821   Entry.Node = Src; Args.push_back(Entry);
7822 
7823   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7824   Entry.Node = Size; Args.push_back(Entry);
7825   // FIXME:  pass in SDLoc
7826   TargetLowering::CallLoweringInfo CLI(*this);
7827   CLI.setDebugLoc(dl)
7828       .setChain(Chain)
7829       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7830                     Dst.getValueType().getTypeForEVT(*getContext()),
7831                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7832                                       TLI->getPointerTy(getDataLayout())),
7833                     std::move(Args))
7834       .setDiscardResult()
7835       .setTailCall(isTailCall);
7836 
7837   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7838   return CallResult.second;
7839 }
7840 
7841 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7842                                        SDValue Dst, SDValue Src, SDValue Size,
7843                                        Type *SizeTy, unsigned ElemSz,
7844                                        bool isTailCall,
7845                                        MachinePointerInfo DstPtrInfo,
7846                                        MachinePointerInfo SrcPtrInfo) {
7847   // Emit a library call.
7848   TargetLowering::ArgListTy Args;
7849   TargetLowering::ArgListEntry Entry;
7850   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7851   Entry.Node = Dst;
7852   Args.push_back(Entry);
7853 
7854   Entry.Node = Src;
7855   Args.push_back(Entry);
7856 
7857   Entry.Ty = SizeTy;
7858   Entry.Node = Size;
7859   Args.push_back(Entry);
7860 
7861   RTLIB::Libcall LibraryCall =
7862       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7863   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7864     report_fatal_error("Unsupported element size");
7865 
7866   TargetLowering::CallLoweringInfo CLI(*this);
7867   CLI.setDebugLoc(dl)
7868       .setChain(Chain)
7869       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7870                     Type::getVoidTy(*getContext()),
7871                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7872                                       TLI->getPointerTy(getDataLayout())),
7873                     std::move(Args))
7874       .setDiscardResult()
7875       .setTailCall(isTailCall);
7876 
7877   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7878   return CallResult.second;
7879 }
7880 
7881 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7882                                 SDValue Src, SDValue Size, Align Alignment,
7883                                 bool isVol, bool AlwaysInline, bool isTailCall,
7884                                 MachinePointerInfo DstPtrInfo,
7885                                 const AAMDNodes &AAInfo) {
7886   // Check to see if we should lower the memset to stores first.
7887   // For cases within the target-specified limits, this is the best choice.
7888   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7889   if (ConstantSize) {
7890     // Memset with size zero? Just return the original chain.
7891     if (ConstantSize->isZero())
7892       return Chain;
7893 
7894     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7895                                      ConstantSize->getZExtValue(), Alignment,
7896                                      isVol, false, DstPtrInfo, AAInfo);
7897 
7898     if (Result.getNode())
7899       return Result;
7900   }
7901 
7902   // Then check to see if we should lower the memset with target-specific
7903   // code. If the target chooses to do this, this is the next best.
7904   if (TSI) {
7905     SDValue Result = TSI->EmitTargetCodeForMemset(
7906         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7907     if (Result.getNode())
7908       return Result;
7909   }
7910 
7911   // If we really need inline code and the target declined to provide it,
7912   // use a (potentially long) sequence of loads and stores.
7913   if (AlwaysInline) {
7914     assert(ConstantSize && "AlwaysInline requires a constant size!");
7915     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7916                                      ConstantSize->getZExtValue(), Alignment,
7917                                      isVol, true, DstPtrInfo, AAInfo);
7918     assert(Result &&
7919            "getMemsetStores must return a valid sequence when AlwaysInline");
7920     return Result;
7921   }
7922 
7923   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7924 
7925   // Emit a library call.
7926   auto &Ctx = *getContext();
7927   const auto& DL = getDataLayout();
7928 
7929   TargetLowering::CallLoweringInfo CLI(*this);
7930   // FIXME: pass in SDLoc
7931   CLI.setDebugLoc(dl).setChain(Chain);
7932 
7933   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7934   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7935   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7936 
7937   // Helper function to create an Entry from Node and Type.
7938   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7939     TargetLowering::ArgListEntry Entry;
7940     Entry.Node = Node;
7941     Entry.Ty = Ty;
7942     return Entry;
7943   };
7944 
7945   // If zeroing out and bzero is present, use it.
7946   if (SrcIsZero && BzeroName) {
7947     TargetLowering::ArgListTy Args;
7948     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7949     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7950     CLI.setLibCallee(
7951         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7952         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7953   } else {
7954     TargetLowering::ArgListTy Args;
7955     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7956     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7957     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7958     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7959                      Dst.getValueType().getTypeForEVT(Ctx),
7960                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7961                                        TLI->getPointerTy(DL)),
7962                      std::move(Args));
7963   }
7964 
7965   CLI.setDiscardResult().setTailCall(isTailCall);
7966 
7967   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7968   return CallResult.second;
7969 }
7970 
7971 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7972                                       SDValue Dst, SDValue Value, SDValue Size,
7973                                       Type *SizeTy, unsigned ElemSz,
7974                                       bool isTailCall,
7975                                       MachinePointerInfo DstPtrInfo) {
7976   // Emit a library call.
7977   TargetLowering::ArgListTy Args;
7978   TargetLowering::ArgListEntry Entry;
7979   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7980   Entry.Node = Dst;
7981   Args.push_back(Entry);
7982 
7983   Entry.Ty = Type::getInt8Ty(*getContext());
7984   Entry.Node = Value;
7985   Args.push_back(Entry);
7986 
7987   Entry.Ty = SizeTy;
7988   Entry.Node = Size;
7989   Args.push_back(Entry);
7990 
7991   RTLIB::Libcall LibraryCall =
7992       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7993   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7994     report_fatal_error("Unsupported element size");
7995 
7996   TargetLowering::CallLoweringInfo CLI(*this);
7997   CLI.setDebugLoc(dl)
7998       .setChain(Chain)
7999       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
8000                     Type::getVoidTy(*getContext()),
8001                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
8002                                       TLI->getPointerTy(getDataLayout())),
8003                     std::move(Args))
8004       .setDiscardResult()
8005       .setTailCall(isTailCall);
8006 
8007   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
8008   return CallResult.second;
8009 }
8010 
8011 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
8012                                 SDVTList VTList, ArrayRef<SDValue> Ops,
8013                                 MachineMemOperand *MMO) {
8014   FoldingSetNodeID ID;
8015   ID.AddInteger(MemVT.getRawBits());
8016   AddNodeIDNode(ID, Opcode, VTList, Ops);
8017   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8018   ID.AddInteger(MMO->getFlags());
8019   void* IP = nullptr;
8020   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8021     cast<AtomicSDNode>(E)->refineAlignment(MMO);
8022     return SDValue(E, 0);
8023   }
8024 
8025   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
8026                                     VTList, MemVT, MMO);
8027   createOperands(N, Ops);
8028 
8029   CSEMap.InsertNode(N, IP);
8030   InsertNode(N);
8031   return SDValue(N, 0);
8032 }
8033 
8034 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
8035                                        EVT MemVT, SDVTList VTs, SDValue Chain,
8036                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
8037                                        MachineMemOperand *MMO) {
8038   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
8039          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
8040   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
8041 
8042   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
8043   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
8044 }
8045 
8046 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
8047                                 SDValue Chain, SDValue Ptr, SDValue Val,
8048                                 MachineMemOperand *MMO) {
8049   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
8050           Opcode == ISD::ATOMIC_LOAD_SUB ||
8051           Opcode == ISD::ATOMIC_LOAD_AND ||
8052           Opcode == ISD::ATOMIC_LOAD_CLR ||
8053           Opcode == ISD::ATOMIC_LOAD_OR ||
8054           Opcode == ISD::ATOMIC_LOAD_XOR ||
8055           Opcode == ISD::ATOMIC_LOAD_NAND ||
8056           Opcode == ISD::ATOMIC_LOAD_MIN ||
8057           Opcode == ISD::ATOMIC_LOAD_MAX ||
8058           Opcode == ISD::ATOMIC_LOAD_UMIN ||
8059           Opcode == ISD::ATOMIC_LOAD_UMAX ||
8060           Opcode == ISD::ATOMIC_LOAD_FADD ||
8061           Opcode == ISD::ATOMIC_LOAD_FSUB ||
8062           Opcode == ISD::ATOMIC_LOAD_FMAX ||
8063           Opcode == ISD::ATOMIC_LOAD_FMIN ||
8064           Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
8065           Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
8066           Opcode == ISD::ATOMIC_SWAP ||
8067           Opcode == ISD::ATOMIC_STORE) &&
8068          "Invalid Atomic Op");
8069 
8070   EVT VT = Val.getValueType();
8071 
8072   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
8073                                                getVTList(VT, MVT::Other);
8074   SDValue Ops[] = {Chain, Ptr, Val};
8075   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
8076 }
8077 
8078 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
8079                                 EVT VT, SDValue Chain, SDValue Ptr,
8080                                 MachineMemOperand *MMO) {
8081   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
8082 
8083   SDVTList VTs = getVTList(VT, MVT::Other);
8084   SDValue Ops[] = {Chain, Ptr};
8085   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
8086 }
8087 
8088 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
8089 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
8090   if (Ops.size() == 1)
8091     return Ops[0];
8092 
8093   SmallVector<EVT, 4> VTs;
8094   VTs.reserve(Ops.size());
8095   for (const SDValue &Op : Ops)
8096     VTs.push_back(Op.getValueType());
8097   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
8098 }
8099 
8100 SDValue SelectionDAG::getMemIntrinsicNode(
8101     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
8102     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
8103     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
8104   if (!Size && MemVT.isScalableVector())
8105     Size = MemoryLocation::UnknownSize;
8106   else if (!Size)
8107     Size = MemVT.getStoreSize();
8108 
8109   MachineFunction &MF = getMachineFunction();
8110   MachineMemOperand *MMO =
8111       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
8112 
8113   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
8114 }
8115 
8116 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
8117                                           SDVTList VTList,
8118                                           ArrayRef<SDValue> Ops, EVT MemVT,
8119                                           MachineMemOperand *MMO) {
8120   assert((Opcode == ISD::INTRINSIC_VOID ||
8121           Opcode == ISD::INTRINSIC_W_CHAIN ||
8122           Opcode == ISD::PREFETCH ||
8123           (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
8124            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
8125          "Opcode is not a memory-accessing opcode!");
8126 
8127   // Memoize the node unless it returns a flag.
8128   MemIntrinsicSDNode *N;
8129   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8130     FoldingSetNodeID ID;
8131     AddNodeIDNode(ID, Opcode, VTList, Ops);
8132     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
8133         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
8134     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8135     ID.AddInteger(MMO->getFlags());
8136     ID.AddInteger(MemVT.getRawBits());
8137     void *IP = nullptr;
8138     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8139       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
8140       return SDValue(E, 0);
8141     }
8142 
8143     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
8144                                       VTList, MemVT, MMO);
8145     createOperands(N, Ops);
8146 
8147   CSEMap.InsertNode(N, IP);
8148   } else {
8149     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
8150                                       VTList, MemVT, MMO);
8151     createOperands(N, Ops);
8152   }
8153   InsertNode(N);
8154   SDValue V(N, 0);
8155   NewSDValueDbgMsg(V, "Creating new node: ", this);
8156   return V;
8157 }
8158 
8159 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
8160                                       SDValue Chain, int FrameIndex,
8161                                       int64_t Size, int64_t Offset) {
8162   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
8163   const auto VTs = getVTList(MVT::Other);
8164   SDValue Ops[2] = {
8165       Chain,
8166       getFrameIndex(FrameIndex,
8167                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
8168                     true)};
8169 
8170   FoldingSetNodeID ID;
8171   AddNodeIDNode(ID, Opcode, VTs, Ops);
8172   ID.AddInteger(FrameIndex);
8173   ID.AddInteger(Size);
8174   ID.AddInteger(Offset);
8175   void *IP = nullptr;
8176   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8177     return SDValue(E, 0);
8178 
8179   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
8180       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
8181   createOperands(N, Ops);
8182   CSEMap.InsertNode(N, IP);
8183   InsertNode(N);
8184   SDValue V(N, 0);
8185   NewSDValueDbgMsg(V, "Creating new node: ", this);
8186   return V;
8187 }
8188 
8189 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
8190                                          uint64_t Guid, uint64_t Index,
8191                                          uint32_t Attr) {
8192   const unsigned Opcode = ISD::PSEUDO_PROBE;
8193   const auto VTs = getVTList(MVT::Other);
8194   SDValue Ops[] = {Chain};
8195   FoldingSetNodeID ID;
8196   AddNodeIDNode(ID, Opcode, VTs, Ops);
8197   ID.AddInteger(Guid);
8198   ID.AddInteger(Index);
8199   void *IP = nullptr;
8200   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
8201     return SDValue(E, 0);
8202 
8203   auto *N = newSDNode<PseudoProbeSDNode>(
8204       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
8205   createOperands(N, Ops);
8206   CSEMap.InsertNode(N, IP);
8207   InsertNode(N);
8208   SDValue V(N, 0);
8209   NewSDValueDbgMsg(V, "Creating new node: ", this);
8210   return V;
8211 }
8212 
8213 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
8214 /// MachinePointerInfo record from it.  This is particularly useful because the
8215 /// code generator has many cases where it doesn't bother passing in a
8216 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
8217 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
8218                                            SelectionDAG &DAG, SDValue Ptr,
8219                                            int64_t Offset = 0) {
8220   // If this is FI+Offset, we can model it.
8221   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
8222     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
8223                                              FI->getIndex(), Offset);
8224 
8225   // If this is (FI+Offset1)+Offset2, we can model it.
8226   if (Ptr.getOpcode() != ISD::ADD ||
8227       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
8228       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
8229     return Info;
8230 
8231   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
8232   return MachinePointerInfo::getFixedStack(
8233       DAG.getMachineFunction(), FI,
8234       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
8235 }
8236 
8237 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
8238 /// MachinePointerInfo record from it.  This is particularly useful because the
8239 /// code generator has many cases where it doesn't bother passing in a
8240 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
8241 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
8242                                            SelectionDAG &DAG, SDValue Ptr,
8243                                            SDValue OffsetOp) {
8244   // If the 'Offset' value isn't a constant, we can't handle this.
8245   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
8246     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
8247   if (OffsetOp.isUndef())
8248     return InferPointerInfo(Info, DAG, Ptr);
8249   return Info;
8250 }
8251 
8252 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
8253                               EVT VT, const SDLoc &dl, SDValue Chain,
8254                               SDValue Ptr, SDValue Offset,
8255                               MachinePointerInfo PtrInfo, EVT MemVT,
8256                               Align Alignment,
8257                               MachineMemOperand::Flags MMOFlags,
8258                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
8259   assert(Chain.getValueType() == MVT::Other &&
8260         "Invalid chain type");
8261 
8262   MMOFlags |= MachineMemOperand::MOLoad;
8263   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8264   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8265   // clients.
8266   if (PtrInfo.V.isNull())
8267     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8268 
8269   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
8270   MachineFunction &MF = getMachineFunction();
8271   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8272                                                    Alignment, AAInfo, Ranges);
8273   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
8274 }
8275 
8276 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
8277                               EVT VT, const SDLoc &dl, SDValue Chain,
8278                               SDValue Ptr, SDValue Offset, EVT MemVT,
8279                               MachineMemOperand *MMO) {
8280   if (VT == MemVT) {
8281     ExtType = ISD::NON_EXTLOAD;
8282   } else if (ExtType == ISD::NON_EXTLOAD) {
8283     assert(VT == MemVT && "Non-extending load from different memory type!");
8284   } else {
8285     // Extending load.
8286     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
8287            "Should only be an extending load, not truncating!");
8288     assert(VT.isInteger() == MemVT.isInteger() &&
8289            "Cannot convert from FP to Int or Int -> FP!");
8290     assert(VT.isVector() == MemVT.isVector() &&
8291            "Cannot use an ext load to convert to or from a vector!");
8292     assert((!VT.isVector() ||
8293             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
8294            "Cannot use an ext load to change the number of vector elements!");
8295   }
8296 
8297   bool Indexed = AM != ISD::UNINDEXED;
8298   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8299 
8300   SDVTList VTs = Indexed ?
8301     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
8302   SDValue Ops[] = { Chain, Ptr, Offset };
8303   FoldingSetNodeID ID;
8304   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
8305   ID.AddInteger(MemVT.getRawBits());
8306   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
8307       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
8308   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8309   ID.AddInteger(MMO->getFlags());
8310   void *IP = nullptr;
8311   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8312     cast<LoadSDNode>(E)->refineAlignment(MMO);
8313     return SDValue(E, 0);
8314   }
8315   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8316                                   ExtType, MemVT, MMO);
8317   createOperands(N, Ops);
8318 
8319   CSEMap.InsertNode(N, IP);
8320   InsertNode(N);
8321   SDValue V(N, 0);
8322   NewSDValueDbgMsg(V, "Creating new node: ", this);
8323   return V;
8324 }
8325 
8326 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8327                               SDValue Ptr, MachinePointerInfo PtrInfo,
8328                               MaybeAlign Alignment,
8329                               MachineMemOperand::Flags MMOFlags,
8330                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
8331   SDValue Undef = getUNDEF(Ptr.getValueType());
8332   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8333                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
8334 }
8335 
8336 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8337                               SDValue Ptr, MachineMemOperand *MMO) {
8338   SDValue Undef = getUNDEF(Ptr.getValueType());
8339   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8340                  VT, MMO);
8341 }
8342 
8343 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
8344                                  EVT VT, SDValue Chain, SDValue Ptr,
8345                                  MachinePointerInfo PtrInfo, EVT MemVT,
8346                                  MaybeAlign Alignment,
8347                                  MachineMemOperand::Flags MMOFlags,
8348                                  const AAMDNodes &AAInfo) {
8349   SDValue Undef = getUNDEF(Ptr.getValueType());
8350   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
8351                  MemVT, Alignment, MMOFlags, AAInfo);
8352 }
8353 
8354 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
8355                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
8356                                  MachineMemOperand *MMO) {
8357   SDValue Undef = getUNDEF(Ptr.getValueType());
8358   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
8359                  MemVT, MMO);
8360 }
8361 
8362 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
8363                                      SDValue Base, SDValue Offset,
8364                                      ISD::MemIndexedMode AM) {
8365   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
8366   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8367   // Don't propagate the invariant or dereferenceable flags.
8368   auto MMOFlags =
8369       LD->getMemOperand()->getFlags() &
8370       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8371   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8372                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
8373                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
8374 }
8375 
8376 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
8377                                SDValue Ptr, MachinePointerInfo PtrInfo,
8378                                Align Alignment,
8379                                MachineMemOperand::Flags MMOFlags,
8380                                const AAMDNodes &AAInfo) {
8381   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8382 
8383   MMOFlags |= MachineMemOperand::MOStore;
8384   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8385 
8386   if (PtrInfo.V.isNull())
8387     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8388 
8389   MachineFunction &MF = getMachineFunction();
8390   uint64_t Size =
8391       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
8392   MachineMemOperand *MMO =
8393       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
8394   return getStore(Chain, dl, Val, Ptr, MMO);
8395 }
8396 
8397 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
8398                                SDValue Ptr, MachineMemOperand *MMO) {
8399   assert(Chain.getValueType() == MVT::Other &&
8400         "Invalid chain type");
8401   EVT VT = Val.getValueType();
8402   SDVTList VTs = getVTList(MVT::Other);
8403   SDValue Undef = getUNDEF(Ptr.getValueType());
8404   SDValue Ops[] = { Chain, Val, Ptr, Undef };
8405   FoldingSetNodeID ID;
8406   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
8407   ID.AddInteger(VT.getRawBits());
8408   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
8409       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
8410   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8411   ID.AddInteger(MMO->getFlags());
8412   void *IP = nullptr;
8413   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8414     cast<StoreSDNode>(E)->refineAlignment(MMO);
8415     return SDValue(E, 0);
8416   }
8417   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8418                                    ISD::UNINDEXED, false, VT, MMO);
8419   createOperands(N, Ops);
8420 
8421   CSEMap.InsertNode(N, IP);
8422   InsertNode(N);
8423   SDValue V(N, 0);
8424   NewSDValueDbgMsg(V, "Creating new node: ", this);
8425   return V;
8426 }
8427 
8428 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
8429                                     SDValue Ptr, MachinePointerInfo PtrInfo,
8430                                     EVT SVT, Align Alignment,
8431                                     MachineMemOperand::Flags MMOFlags,
8432                                     const AAMDNodes &AAInfo) {
8433   assert(Chain.getValueType() == MVT::Other &&
8434         "Invalid chain type");
8435 
8436   MMOFlags |= MachineMemOperand::MOStore;
8437   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8438 
8439   if (PtrInfo.V.isNull())
8440     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8441 
8442   MachineFunction &MF = getMachineFunction();
8443   MachineMemOperand *MMO = MF.getMachineMemOperand(
8444       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8445       Alignment, AAInfo);
8446   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
8447 }
8448 
8449 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
8450                                     SDValue Ptr, EVT SVT,
8451                                     MachineMemOperand *MMO) {
8452   EVT VT = Val.getValueType();
8453 
8454   assert(Chain.getValueType() == MVT::Other &&
8455         "Invalid chain type");
8456   if (VT == SVT)
8457     return getStore(Chain, dl, Val, Ptr, MMO);
8458 
8459   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8460          "Should only be a truncating store, not extending!");
8461   assert(VT.isInteger() == SVT.isInteger() &&
8462          "Can't do FP-INT conversion!");
8463   assert(VT.isVector() == SVT.isVector() &&
8464          "Cannot use trunc store to convert to or from a vector!");
8465   assert((!VT.isVector() ||
8466           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8467          "Cannot use trunc store to change the number of vector elements!");
8468 
8469   SDVTList VTs = getVTList(MVT::Other);
8470   SDValue Undef = getUNDEF(Ptr.getValueType());
8471   SDValue Ops[] = { Chain, Val, Ptr, Undef };
8472   FoldingSetNodeID ID;
8473   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
8474   ID.AddInteger(SVT.getRawBits());
8475   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
8476       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
8477   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8478   ID.AddInteger(MMO->getFlags());
8479   void *IP = nullptr;
8480   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8481     cast<StoreSDNode>(E)->refineAlignment(MMO);
8482     return SDValue(E, 0);
8483   }
8484   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8485                                    ISD::UNINDEXED, true, SVT, MMO);
8486   createOperands(N, Ops);
8487 
8488   CSEMap.InsertNode(N, IP);
8489   InsertNode(N);
8490   SDValue V(N, 0);
8491   NewSDValueDbgMsg(V, "Creating new node: ", this);
8492   return V;
8493 }
8494 
8495 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
8496                                       SDValue Base, SDValue Offset,
8497                                       ISD::MemIndexedMode AM) {
8498   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
8499   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
8500   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8501   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
8502   FoldingSetNodeID ID;
8503   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
8504   ID.AddInteger(ST->getMemoryVT().getRawBits());
8505   ID.AddInteger(ST->getRawSubclassData());
8506   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8507   ID.AddInteger(ST->getMemOperand()->getFlags());
8508   void *IP = nullptr;
8509   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8510     return SDValue(E, 0);
8511 
8512   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8513                                    ST->isTruncatingStore(), ST->getMemoryVT(),
8514                                    ST->getMemOperand());
8515   createOperands(N, Ops);
8516 
8517   CSEMap.InsertNode(N, IP);
8518   InsertNode(N);
8519   SDValue V(N, 0);
8520   NewSDValueDbgMsg(V, "Creating new node: ", this);
8521   return V;
8522 }
8523 
8524 SDValue SelectionDAG::getLoadVP(
8525     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
8526     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
8527     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8528     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8529     const MDNode *Ranges, bool IsExpanding) {
8530   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8531 
8532   MMOFlags |= MachineMemOperand::MOLoad;
8533   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8534   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8535   // clients.
8536   if (PtrInfo.V.isNull())
8537     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8538 
8539   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
8540   MachineFunction &MF = getMachineFunction();
8541   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8542                                                    Alignment, AAInfo, Ranges);
8543   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
8544                    MMO, IsExpanding);
8545 }
8546 
8547 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8548                                 ISD::LoadExtType ExtType, EVT VT,
8549                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8550                                 SDValue Offset, SDValue Mask, SDValue EVL,
8551                                 EVT MemVT, MachineMemOperand *MMO,
8552                                 bool IsExpanding) {
8553   bool Indexed = AM != ISD::UNINDEXED;
8554   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8555 
8556   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8557                          : getVTList(VT, MVT::Other);
8558   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8559   FoldingSetNodeID ID;
8560   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8561   ID.AddInteger(MemVT.getRawBits());
8562   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8563       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8564   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8565   ID.AddInteger(MMO->getFlags());
8566   void *IP = nullptr;
8567   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8568     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8569     return SDValue(E, 0);
8570   }
8571   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8572                                     ExtType, IsExpanding, MemVT, MMO);
8573   createOperands(N, Ops);
8574 
8575   CSEMap.InsertNode(N, IP);
8576   InsertNode(N);
8577   SDValue V(N, 0);
8578   NewSDValueDbgMsg(V, "Creating new node: ", this);
8579   return V;
8580 }
8581 
8582 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8583                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8584                                 MachinePointerInfo PtrInfo,
8585                                 MaybeAlign Alignment,
8586                                 MachineMemOperand::Flags MMOFlags,
8587                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8588                                 bool IsExpanding) {
8589   SDValue Undef = getUNDEF(Ptr.getValueType());
8590   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8591                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8592                    IsExpanding);
8593 }
8594 
8595 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8596                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8597                                 MachineMemOperand *MMO, bool IsExpanding) {
8598   SDValue Undef = getUNDEF(Ptr.getValueType());
8599   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8600                    Mask, EVL, VT, MMO, IsExpanding);
8601 }
8602 
8603 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8604                                    EVT VT, SDValue Chain, SDValue Ptr,
8605                                    SDValue Mask, SDValue EVL,
8606                                    MachinePointerInfo PtrInfo, EVT MemVT,
8607                                    MaybeAlign Alignment,
8608                                    MachineMemOperand::Flags MMOFlags,
8609                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8610   SDValue Undef = getUNDEF(Ptr.getValueType());
8611   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8612                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8613                    IsExpanding);
8614 }
8615 
8616 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8617                                    EVT VT, SDValue Chain, SDValue Ptr,
8618                                    SDValue Mask, SDValue EVL, EVT MemVT,
8619                                    MachineMemOperand *MMO, bool IsExpanding) {
8620   SDValue Undef = getUNDEF(Ptr.getValueType());
8621   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8622                    EVL, MemVT, MMO, IsExpanding);
8623 }
8624 
8625 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8626                                        SDValue Base, SDValue Offset,
8627                                        ISD::MemIndexedMode AM) {
8628   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8629   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8630   // Don't propagate the invariant or dereferenceable flags.
8631   auto MMOFlags =
8632       LD->getMemOperand()->getFlags() &
8633       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8634   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8635                    LD->getChain(), Base, Offset, LD->getMask(),
8636                    LD->getVectorLength(), LD->getPointerInfo(),
8637                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8638                    nullptr, LD->isExpandingLoad());
8639 }
8640 
8641 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8642                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8643                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8644                                  ISD::MemIndexedMode AM, bool IsTruncating,
8645                                  bool IsCompressing) {
8646   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8647   bool Indexed = AM != ISD::UNINDEXED;
8648   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8649   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8650                          : getVTList(MVT::Other);
8651   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8652   FoldingSetNodeID ID;
8653   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8654   ID.AddInteger(MemVT.getRawBits());
8655   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8656       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8657   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8658   ID.AddInteger(MMO->getFlags());
8659   void *IP = nullptr;
8660   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8661     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8662     return SDValue(E, 0);
8663   }
8664   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8665                                      IsTruncating, IsCompressing, MemVT, MMO);
8666   createOperands(N, Ops);
8667 
8668   CSEMap.InsertNode(N, IP);
8669   InsertNode(N);
8670   SDValue V(N, 0);
8671   NewSDValueDbgMsg(V, "Creating new node: ", this);
8672   return V;
8673 }
8674 
8675 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8676                                       SDValue Val, SDValue Ptr, SDValue Mask,
8677                                       SDValue EVL, MachinePointerInfo PtrInfo,
8678                                       EVT SVT, Align Alignment,
8679                                       MachineMemOperand::Flags MMOFlags,
8680                                       const AAMDNodes &AAInfo,
8681                                       bool IsCompressing) {
8682   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8683 
8684   MMOFlags |= MachineMemOperand::MOStore;
8685   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8686 
8687   if (PtrInfo.V.isNull())
8688     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8689 
8690   MachineFunction &MF = getMachineFunction();
8691   MachineMemOperand *MMO = MF.getMachineMemOperand(
8692       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8693       Alignment, AAInfo);
8694   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8695                          IsCompressing);
8696 }
8697 
8698 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8699                                       SDValue Val, SDValue Ptr, SDValue Mask,
8700                                       SDValue EVL, EVT SVT,
8701                                       MachineMemOperand *MMO,
8702                                       bool IsCompressing) {
8703   EVT VT = Val.getValueType();
8704 
8705   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8706   if (VT == SVT)
8707     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8708                       EVL, VT, MMO, ISD::UNINDEXED,
8709                       /*IsTruncating*/ false, IsCompressing);
8710 
8711   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8712          "Should only be a truncating store, not extending!");
8713   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8714   assert(VT.isVector() == SVT.isVector() &&
8715          "Cannot use trunc store to convert to or from a vector!");
8716   assert((!VT.isVector() ||
8717           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8718          "Cannot use trunc store to change the number of vector elements!");
8719 
8720   SDVTList VTs = getVTList(MVT::Other);
8721   SDValue Undef = getUNDEF(Ptr.getValueType());
8722   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8723   FoldingSetNodeID ID;
8724   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8725   ID.AddInteger(SVT.getRawBits());
8726   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8727       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8728   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8729   ID.AddInteger(MMO->getFlags());
8730   void *IP = nullptr;
8731   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8732     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8733     return SDValue(E, 0);
8734   }
8735   auto *N =
8736       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8737                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8738   createOperands(N, Ops);
8739 
8740   CSEMap.InsertNode(N, IP);
8741   InsertNode(N);
8742   SDValue V(N, 0);
8743   NewSDValueDbgMsg(V, "Creating new node: ", this);
8744   return V;
8745 }
8746 
8747 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8748                                         SDValue Base, SDValue Offset,
8749                                         ISD::MemIndexedMode AM) {
8750   auto *ST = cast<VPStoreSDNode>(OrigStore);
8751   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8752   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8753   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8754                    Offset,         ST->getMask(),  ST->getVectorLength()};
8755   FoldingSetNodeID ID;
8756   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8757   ID.AddInteger(ST->getMemoryVT().getRawBits());
8758   ID.AddInteger(ST->getRawSubclassData());
8759   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8760   ID.AddInteger(ST->getMemOperand()->getFlags());
8761   void *IP = nullptr;
8762   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8763     return SDValue(E, 0);
8764 
8765   auto *N = newSDNode<VPStoreSDNode>(
8766       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8767       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8768   createOperands(N, Ops);
8769 
8770   CSEMap.InsertNode(N, IP);
8771   InsertNode(N);
8772   SDValue V(N, 0);
8773   NewSDValueDbgMsg(V, "Creating new node: ", this);
8774   return V;
8775 }
8776 
8777 SDValue SelectionDAG::getStridedLoadVP(
8778     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8779     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8780     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8781     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8782     const MDNode *Ranges, bool IsExpanding) {
8783   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8784 
8785   MMOFlags |= MachineMemOperand::MOLoad;
8786   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8787   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8788   // clients.
8789   if (PtrInfo.V.isNull())
8790     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8791 
8792   uint64_t Size = MemoryLocation::UnknownSize;
8793   MachineFunction &MF = getMachineFunction();
8794   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8795                                                    Alignment, AAInfo, Ranges);
8796   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8797                           EVL, MemVT, MMO, IsExpanding);
8798 }
8799 
8800 SDValue SelectionDAG::getStridedLoadVP(
8801     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8802     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8803     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8804   bool Indexed = AM != ISD::UNINDEXED;
8805   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8806 
8807   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8808   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8809                          : getVTList(VT, MVT::Other);
8810   FoldingSetNodeID ID;
8811   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8812   ID.AddInteger(VT.getRawBits());
8813   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8814       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8815   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8816 
8817   void *IP = nullptr;
8818   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8819     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8820     return SDValue(E, 0);
8821   }
8822 
8823   auto *N =
8824       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8825                                      ExtType, IsExpanding, MemVT, MMO);
8826   createOperands(N, Ops);
8827   CSEMap.InsertNode(N, IP);
8828   InsertNode(N);
8829   SDValue V(N, 0);
8830   NewSDValueDbgMsg(V, "Creating new node: ", this);
8831   return V;
8832 }
8833 
8834 SDValue SelectionDAG::getStridedLoadVP(
8835     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8836     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8837     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8838     const MDNode *Ranges, bool IsExpanding) {
8839   SDValue Undef = getUNDEF(Ptr.getValueType());
8840   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8841                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8842                           MMOFlags, AAInfo, Ranges, IsExpanding);
8843 }
8844 
8845 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8846                                        SDValue Ptr, SDValue Stride,
8847                                        SDValue Mask, SDValue EVL,
8848                                        MachineMemOperand *MMO,
8849                                        bool IsExpanding) {
8850   SDValue Undef = getUNDEF(Ptr.getValueType());
8851   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8852                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8853 }
8854 
8855 SDValue SelectionDAG::getExtStridedLoadVP(
8856     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8857     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8858     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8859     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8860     bool IsExpanding) {
8861   SDValue Undef = getUNDEF(Ptr.getValueType());
8862   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8863                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8864                           MMOFlags, AAInfo, nullptr, IsExpanding);
8865 }
8866 
8867 SDValue SelectionDAG::getExtStridedLoadVP(
8868     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8869     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8870     MachineMemOperand *MMO, bool IsExpanding) {
8871   SDValue Undef = getUNDEF(Ptr.getValueType());
8872   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8873                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8874 }
8875 
8876 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8877                                               SDValue Base, SDValue Offset,
8878                                               ISD::MemIndexedMode AM) {
8879   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8880   assert(SLD->getOffset().isUndef() &&
8881          "Strided load is already a indexed load!");
8882   // Don't propagate the invariant or dereferenceable flags.
8883   auto MMOFlags =
8884       SLD->getMemOperand()->getFlags() &
8885       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8886   return getStridedLoadVP(
8887       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8888       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8889       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8890       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8891 }
8892 
8893 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8894                                         SDValue Val, SDValue Ptr,
8895                                         SDValue Offset, SDValue Stride,
8896                                         SDValue Mask, SDValue EVL, EVT MemVT,
8897                                         MachineMemOperand *MMO,
8898                                         ISD::MemIndexedMode AM,
8899                                         bool IsTruncating, bool IsCompressing) {
8900   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8901   bool Indexed = AM != ISD::UNINDEXED;
8902   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8903   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8904                          : getVTList(MVT::Other);
8905   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8906   FoldingSetNodeID ID;
8907   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8908   ID.AddInteger(MemVT.getRawBits());
8909   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8910       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8911   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8912   void *IP = nullptr;
8913   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8914     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8915     return SDValue(E, 0);
8916   }
8917   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8918                                             VTs, AM, IsTruncating,
8919                                             IsCompressing, MemVT, MMO);
8920   createOperands(N, Ops);
8921 
8922   CSEMap.InsertNode(N, IP);
8923   InsertNode(N);
8924   SDValue V(N, 0);
8925   NewSDValueDbgMsg(V, "Creating new node: ", this);
8926   return V;
8927 }
8928 
8929 SDValue SelectionDAG::getTruncStridedStoreVP(
8930     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8931     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8932     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8933     bool IsCompressing) {
8934   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8935 
8936   MMOFlags |= MachineMemOperand::MOStore;
8937   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8938 
8939   if (PtrInfo.V.isNull())
8940     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8941 
8942   MachineFunction &MF = getMachineFunction();
8943   MachineMemOperand *MMO = MF.getMachineMemOperand(
8944       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8945   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8946                                 MMO, IsCompressing);
8947 }
8948 
8949 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8950                                              SDValue Val, SDValue Ptr,
8951                                              SDValue Stride, SDValue Mask,
8952                                              SDValue EVL, EVT SVT,
8953                                              MachineMemOperand *MMO,
8954                                              bool IsCompressing) {
8955   EVT VT = Val.getValueType();
8956 
8957   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8958   if (VT == SVT)
8959     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8960                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8961                              /*IsTruncating*/ false, IsCompressing);
8962 
8963   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8964          "Should only be a truncating store, not extending!");
8965   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8966   assert(VT.isVector() == SVT.isVector() &&
8967          "Cannot use trunc store to convert to or from a vector!");
8968   assert((!VT.isVector() ||
8969           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8970          "Cannot use trunc store to change the number of vector elements!");
8971 
8972   SDVTList VTs = getVTList(MVT::Other);
8973   SDValue Undef = getUNDEF(Ptr.getValueType());
8974   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8975   FoldingSetNodeID ID;
8976   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8977   ID.AddInteger(SVT.getRawBits());
8978   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8979       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8980   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8981   void *IP = nullptr;
8982   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8983     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8984     return SDValue(E, 0);
8985   }
8986   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8987                                             VTs, ISD::UNINDEXED, true,
8988                                             IsCompressing, SVT, MMO);
8989   createOperands(N, Ops);
8990 
8991   CSEMap.InsertNode(N, IP);
8992   InsertNode(N);
8993   SDValue V(N, 0);
8994   NewSDValueDbgMsg(V, "Creating new node: ", this);
8995   return V;
8996 }
8997 
8998 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8999                                                const SDLoc &DL, SDValue Base,
9000                                                SDValue Offset,
9001                                                ISD::MemIndexedMode AM) {
9002   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
9003   assert(SST->getOffset().isUndef() &&
9004          "Strided store is already an indexed store!");
9005   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
9006   SDValue Ops[] = {
9007       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
9008       SST->getMask(),  SST->getVectorLength()};
9009   FoldingSetNodeID ID;
9010   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
9011   ID.AddInteger(SST->getMemoryVT().getRawBits());
9012   ID.AddInteger(SST->getRawSubclassData());
9013   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
9014   void *IP = nullptr;
9015   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9016     return SDValue(E, 0);
9017 
9018   auto *N = newSDNode<VPStridedStoreSDNode>(
9019       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
9020       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
9021   createOperands(N, Ops);
9022 
9023   CSEMap.InsertNode(N, IP);
9024   InsertNode(N);
9025   SDValue V(N, 0);
9026   NewSDValueDbgMsg(V, "Creating new node: ", this);
9027   return V;
9028 }
9029 
9030 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
9031                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
9032                                   ISD::MemIndexType IndexType) {
9033   assert(Ops.size() == 6 && "Incompatible number of operands");
9034 
9035   FoldingSetNodeID ID;
9036   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
9037   ID.AddInteger(VT.getRawBits());
9038   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
9039       dl.getIROrder(), VTs, VT, MMO, IndexType));
9040   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9041   ID.AddInteger(MMO->getFlags());
9042   void *IP = nullptr;
9043   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9044     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
9045     return SDValue(E, 0);
9046   }
9047 
9048   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
9049                                       VT, MMO, IndexType);
9050   createOperands(N, Ops);
9051 
9052   assert(N->getMask().getValueType().getVectorElementCount() ==
9053              N->getValueType(0).getVectorElementCount() &&
9054          "Vector width mismatch between mask and data");
9055   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
9056              N->getValueType(0).getVectorElementCount().isScalable() &&
9057          "Scalable flags of index and data do not match");
9058   assert(ElementCount::isKnownGE(
9059              N->getIndex().getValueType().getVectorElementCount(),
9060              N->getValueType(0).getVectorElementCount()) &&
9061          "Vector width mismatch between index and data");
9062   assert(isa<ConstantSDNode>(N->getScale()) &&
9063          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
9064          "Scale should be a constant power of 2");
9065 
9066   CSEMap.InsertNode(N, IP);
9067   InsertNode(N);
9068   SDValue V(N, 0);
9069   NewSDValueDbgMsg(V, "Creating new node: ", this);
9070   return V;
9071 }
9072 
9073 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
9074                                    ArrayRef<SDValue> Ops,
9075                                    MachineMemOperand *MMO,
9076                                    ISD::MemIndexType IndexType) {
9077   assert(Ops.size() == 7 && "Incompatible number of operands");
9078 
9079   FoldingSetNodeID ID;
9080   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
9081   ID.AddInteger(VT.getRawBits());
9082   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
9083       dl.getIROrder(), VTs, VT, MMO, IndexType));
9084   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9085   ID.AddInteger(MMO->getFlags());
9086   void *IP = nullptr;
9087   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9088     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
9089     return SDValue(E, 0);
9090   }
9091   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
9092                                        VT, MMO, IndexType);
9093   createOperands(N, Ops);
9094 
9095   assert(N->getMask().getValueType().getVectorElementCount() ==
9096              N->getValue().getValueType().getVectorElementCount() &&
9097          "Vector width mismatch between mask and data");
9098   assert(
9099       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
9100           N->getValue().getValueType().getVectorElementCount().isScalable() &&
9101       "Scalable flags of index and data do not match");
9102   assert(ElementCount::isKnownGE(
9103              N->getIndex().getValueType().getVectorElementCount(),
9104              N->getValue().getValueType().getVectorElementCount()) &&
9105          "Vector width mismatch between index and data");
9106   assert(isa<ConstantSDNode>(N->getScale()) &&
9107          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
9108          "Scale should be a constant power of 2");
9109 
9110   CSEMap.InsertNode(N, IP);
9111   InsertNode(N);
9112   SDValue V(N, 0);
9113   NewSDValueDbgMsg(V, "Creating new node: ", this);
9114   return V;
9115 }
9116 
9117 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
9118                                     SDValue Base, SDValue Offset, SDValue Mask,
9119                                     SDValue PassThru, EVT MemVT,
9120                                     MachineMemOperand *MMO,
9121                                     ISD::MemIndexedMode AM,
9122                                     ISD::LoadExtType ExtTy, bool isExpanding) {
9123   bool Indexed = AM != ISD::UNINDEXED;
9124   assert((Indexed || Offset.isUndef()) &&
9125          "Unindexed masked load with an offset!");
9126   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
9127                          : getVTList(VT, MVT::Other);
9128   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
9129   FoldingSetNodeID ID;
9130   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
9131   ID.AddInteger(MemVT.getRawBits());
9132   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
9133       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
9134   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9135   ID.AddInteger(MMO->getFlags());
9136   void *IP = nullptr;
9137   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9138     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
9139     return SDValue(E, 0);
9140   }
9141   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
9142                                         AM, ExtTy, isExpanding, MemVT, MMO);
9143   createOperands(N, Ops);
9144 
9145   CSEMap.InsertNode(N, IP);
9146   InsertNode(N);
9147   SDValue V(N, 0);
9148   NewSDValueDbgMsg(V, "Creating new node: ", this);
9149   return V;
9150 }
9151 
9152 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
9153                                            SDValue Base, SDValue Offset,
9154                                            ISD::MemIndexedMode AM) {
9155   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
9156   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
9157   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
9158                        Offset, LD->getMask(), LD->getPassThru(),
9159                        LD->getMemoryVT(), LD->getMemOperand(), AM,
9160                        LD->getExtensionType(), LD->isExpandingLoad());
9161 }
9162 
9163 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
9164                                      SDValue Val, SDValue Base, SDValue Offset,
9165                                      SDValue Mask, EVT MemVT,
9166                                      MachineMemOperand *MMO,
9167                                      ISD::MemIndexedMode AM, bool IsTruncating,
9168                                      bool IsCompressing) {
9169   assert(Chain.getValueType() == MVT::Other &&
9170         "Invalid chain type");
9171   bool Indexed = AM != ISD::UNINDEXED;
9172   assert((Indexed || Offset.isUndef()) &&
9173          "Unindexed masked store with an offset!");
9174   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
9175                          : getVTList(MVT::Other);
9176   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
9177   FoldingSetNodeID ID;
9178   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
9179   ID.AddInteger(MemVT.getRawBits());
9180   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
9181       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
9182   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9183   ID.AddInteger(MMO->getFlags());
9184   void *IP = nullptr;
9185   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9186     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
9187     return SDValue(E, 0);
9188   }
9189   auto *N =
9190       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
9191                                    IsTruncating, IsCompressing, MemVT, MMO);
9192   createOperands(N, Ops);
9193 
9194   CSEMap.InsertNode(N, IP);
9195   InsertNode(N);
9196   SDValue V(N, 0);
9197   NewSDValueDbgMsg(V, "Creating new node: ", this);
9198   return V;
9199 }
9200 
9201 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
9202                                             SDValue Base, SDValue Offset,
9203                                             ISD::MemIndexedMode AM) {
9204   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
9205   assert(ST->getOffset().isUndef() &&
9206          "Masked store is already a indexed store!");
9207   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
9208                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
9209                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
9210 }
9211 
9212 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
9213                                       ArrayRef<SDValue> Ops,
9214                                       MachineMemOperand *MMO,
9215                                       ISD::MemIndexType IndexType,
9216                                       ISD::LoadExtType ExtTy) {
9217   assert(Ops.size() == 6 && "Incompatible number of operands");
9218 
9219   FoldingSetNodeID ID;
9220   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
9221   ID.AddInteger(MemVT.getRawBits());
9222   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
9223       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
9224   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9225   ID.AddInteger(MMO->getFlags());
9226   void *IP = nullptr;
9227   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9228     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
9229     return SDValue(E, 0);
9230   }
9231 
9232   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
9233                                           VTs, MemVT, MMO, IndexType, ExtTy);
9234   createOperands(N, Ops);
9235 
9236   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
9237          "Incompatible type of the PassThru value in MaskedGatherSDNode");
9238   assert(N->getMask().getValueType().getVectorElementCount() ==
9239              N->getValueType(0).getVectorElementCount() &&
9240          "Vector width mismatch between mask and data");
9241   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
9242              N->getValueType(0).getVectorElementCount().isScalable() &&
9243          "Scalable flags of index and data do not match");
9244   assert(ElementCount::isKnownGE(
9245              N->getIndex().getValueType().getVectorElementCount(),
9246              N->getValueType(0).getVectorElementCount()) &&
9247          "Vector width mismatch between index and data");
9248   assert(isa<ConstantSDNode>(N->getScale()) &&
9249          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
9250          "Scale should be a constant power of 2");
9251 
9252   CSEMap.InsertNode(N, IP);
9253   InsertNode(N);
9254   SDValue V(N, 0);
9255   NewSDValueDbgMsg(V, "Creating new node: ", this);
9256   return V;
9257 }
9258 
9259 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
9260                                        ArrayRef<SDValue> Ops,
9261                                        MachineMemOperand *MMO,
9262                                        ISD::MemIndexType IndexType,
9263                                        bool IsTrunc) {
9264   assert(Ops.size() == 6 && "Incompatible number of operands");
9265 
9266   FoldingSetNodeID ID;
9267   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
9268   ID.AddInteger(MemVT.getRawBits());
9269   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
9270       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
9271   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9272   ID.AddInteger(MMO->getFlags());
9273   void *IP = nullptr;
9274   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
9275     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
9276     return SDValue(E, 0);
9277   }
9278 
9279   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
9280                                            VTs, MemVT, MMO, IndexType, IsTrunc);
9281   createOperands(N, Ops);
9282 
9283   assert(N->getMask().getValueType().getVectorElementCount() ==
9284              N->getValue().getValueType().getVectorElementCount() &&
9285          "Vector width mismatch between mask and data");
9286   assert(
9287       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
9288           N->getValue().getValueType().getVectorElementCount().isScalable() &&
9289       "Scalable flags of index and data do not match");
9290   assert(ElementCount::isKnownGE(
9291              N->getIndex().getValueType().getVectorElementCount(),
9292              N->getValue().getValueType().getVectorElementCount()) &&
9293          "Vector width mismatch between index and data");
9294   assert(isa<ConstantSDNode>(N->getScale()) &&
9295          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
9296          "Scale should be a constant power of 2");
9297 
9298   CSEMap.InsertNode(N, IP);
9299   InsertNode(N);
9300   SDValue V(N, 0);
9301   NewSDValueDbgMsg(V, "Creating new node: ", this);
9302   return V;
9303 }
9304 
9305 SDValue SelectionDAG::getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr,
9306                                   EVT MemVT, MachineMemOperand *MMO) {
9307   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
9308   SDVTList VTs = getVTList(MVT::Other);
9309   SDValue Ops[] = {Chain, Ptr};
9310   FoldingSetNodeID ID;
9311   AddNodeIDNode(ID, ISD::GET_FPENV_MEM, VTs, Ops);
9312   ID.AddInteger(MemVT.getRawBits());
9313   ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
9314       ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
9315   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9316   ID.AddInteger(MMO->getFlags());
9317   void *IP = nullptr;
9318   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
9319     return SDValue(E, 0);
9320 
9321   auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
9322                                            dl.getDebugLoc(), VTs, MemVT, MMO);
9323   createOperands(N, Ops);
9324 
9325   CSEMap.InsertNode(N, IP);
9326   InsertNode(N);
9327   SDValue V(N, 0);
9328   NewSDValueDbgMsg(V, "Creating new node: ", this);
9329   return V;
9330 }
9331 
9332 SDValue SelectionDAG::getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr,
9333                                   EVT MemVT, MachineMemOperand *MMO) {
9334   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
9335   SDVTList VTs = getVTList(MVT::Other);
9336   SDValue Ops[] = {Chain, Ptr};
9337   FoldingSetNodeID ID;
9338   AddNodeIDNode(ID, ISD::SET_FPENV_MEM, VTs, Ops);
9339   ID.AddInteger(MemVT.getRawBits());
9340   ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
9341       ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
9342   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
9343   ID.AddInteger(MMO->getFlags());
9344   void *IP = nullptr;
9345   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
9346     return SDValue(E, 0);
9347 
9348   auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
9349                                            dl.getDebugLoc(), VTs, MemVT, MMO);
9350   createOperands(N, Ops);
9351 
9352   CSEMap.InsertNode(N, IP);
9353   InsertNode(N);
9354   SDValue V(N, 0);
9355   NewSDValueDbgMsg(V, "Creating new node: ", this);
9356   return V;
9357 }
9358 
9359 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
9360   // select undef, T, F --> T (if T is a constant), otherwise F
9361   // select, ?, undef, F --> F
9362   // select, ?, T, undef --> T
9363   if (Cond.isUndef())
9364     return isConstantValueOfAnyType(T) ? T : F;
9365   if (T.isUndef())
9366     return F;
9367   if (F.isUndef())
9368     return T;
9369 
9370   // select true, T, F --> T
9371   // select false, T, F --> F
9372   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
9373     return CondC->isZero() ? F : T;
9374 
9375   // TODO: This should simplify VSELECT with non-zero constant condition using
9376   // something like this (but check boolean contents to be complete?):
9377   if (ConstantSDNode *CondC = isConstOrConstSplat(Cond, /*AllowUndefs*/ false,
9378                                                   /*AllowTruncation*/ true))
9379     if (CondC->isZero())
9380       return F;
9381 
9382   // select ?, T, T --> T
9383   if (T == F)
9384     return T;
9385 
9386   return SDValue();
9387 }
9388 
9389 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
9390   // shift undef, Y --> 0 (can always assume that the undef value is 0)
9391   if (X.isUndef())
9392     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
9393   // shift X, undef --> undef (because it may shift by the bitwidth)
9394   if (Y.isUndef())
9395     return getUNDEF(X.getValueType());
9396 
9397   // shift 0, Y --> 0
9398   // shift X, 0 --> X
9399   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
9400     return X;
9401 
9402   // shift X, C >= bitwidth(X) --> undef
9403   // All vector elements must be too big (or undef) to avoid partial undefs.
9404   auto isShiftTooBig = [X](ConstantSDNode *Val) {
9405     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
9406   };
9407   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
9408     return getUNDEF(X.getValueType());
9409 
9410   return SDValue();
9411 }
9412 
9413 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
9414                                       SDNodeFlags Flags) {
9415   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
9416   // (an undef operand can be chosen to be Nan/Inf), then the result of this
9417   // operation is poison. That result can be relaxed to undef.
9418   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
9419   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
9420   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
9421                 (YC && YC->getValueAPF().isNaN());
9422   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
9423                 (YC && YC->getValueAPF().isInfinity());
9424 
9425   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
9426     return getUNDEF(X.getValueType());
9427 
9428   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
9429     return getUNDEF(X.getValueType());
9430 
9431   if (!YC)
9432     return SDValue();
9433 
9434   // X + -0.0 --> X
9435   if (Opcode == ISD::FADD)
9436     if (YC->getValueAPF().isNegZero())
9437       return X;
9438 
9439   // X - +0.0 --> X
9440   if (Opcode == ISD::FSUB)
9441     if (YC->getValueAPF().isPosZero())
9442       return X;
9443 
9444   // X * 1.0 --> X
9445   // X / 1.0 --> X
9446   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
9447     if (YC->getValueAPF().isExactlyValue(1.0))
9448       return X;
9449 
9450   // X * 0.0 --> 0.0
9451   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
9452     if (YC->getValueAPF().isZero())
9453       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
9454 
9455   return SDValue();
9456 }
9457 
9458 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
9459                                SDValue Ptr, SDValue SV, unsigned Align) {
9460   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
9461   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
9462 }
9463 
9464 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9465                               ArrayRef<SDUse> Ops) {
9466   switch (Ops.size()) {
9467   case 0: return getNode(Opcode, DL, VT);
9468   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
9469   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
9470   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
9471   default: break;
9472   }
9473 
9474   // Copy from an SDUse array into an SDValue array for use with
9475   // the regular getNode logic.
9476   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
9477   return getNode(Opcode, DL, VT, NewOps);
9478 }
9479 
9480 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9481                               ArrayRef<SDValue> Ops) {
9482   SDNodeFlags Flags;
9483   if (Inserter)
9484     Flags = Inserter->getFlags();
9485   return getNode(Opcode, DL, VT, Ops, Flags);
9486 }
9487 
9488 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9489                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9490   unsigned NumOps = Ops.size();
9491   switch (NumOps) {
9492   case 0: return getNode(Opcode, DL, VT);
9493   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
9494   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
9495   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
9496   default: break;
9497   }
9498 
9499 #ifndef NDEBUG
9500   for (const auto &Op : Ops)
9501     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9502            "Operand is DELETED_NODE!");
9503 #endif
9504 
9505   switch (Opcode) {
9506   default: break;
9507   case ISD::BUILD_VECTOR:
9508     // Attempt to simplify BUILD_VECTOR.
9509     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9510       return V;
9511     break;
9512   case ISD::CONCAT_VECTORS:
9513     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9514       return V;
9515     break;
9516   case ISD::SELECT_CC:
9517     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
9518     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
9519            "LHS and RHS of condition must have same type!");
9520     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
9521            "True and False arms of SelectCC must have same type!");
9522     assert(Ops[2].getValueType() == VT &&
9523            "select_cc node must be of same type as true and false value!");
9524     assert((!Ops[0].getValueType().isVector() ||
9525             Ops[0].getValueType().getVectorElementCount() ==
9526                 VT.getVectorElementCount()) &&
9527            "Expected select_cc with vector result to have the same sized "
9528            "comparison type!");
9529     break;
9530   case ISD::BR_CC:
9531     assert(NumOps == 5 && "BR_CC takes 5 operands!");
9532     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
9533            "LHS/RHS of comparison should match types!");
9534     break;
9535   case ISD::VP_ADD:
9536   case ISD::VP_SUB:
9537     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
9538     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
9539       Opcode = ISD::VP_XOR;
9540     break;
9541   case ISD::VP_MUL:
9542     // If it is VP_MUL mask operation then turn it to VP_AND
9543     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
9544       Opcode = ISD::VP_AND;
9545     break;
9546   case ISD::VP_REDUCE_MUL:
9547     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
9548     if (VT == MVT::i1)
9549       Opcode = ISD::VP_REDUCE_AND;
9550     break;
9551   case ISD::VP_REDUCE_ADD:
9552     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
9553     if (VT == MVT::i1)
9554       Opcode = ISD::VP_REDUCE_XOR;
9555     break;
9556   case ISD::VP_REDUCE_SMAX:
9557   case ISD::VP_REDUCE_UMIN:
9558     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
9559     // VP_REDUCE_AND.
9560     if (VT == MVT::i1)
9561       Opcode = ISD::VP_REDUCE_AND;
9562     break;
9563   case ISD::VP_REDUCE_SMIN:
9564   case ISD::VP_REDUCE_UMAX:
9565     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
9566     // VP_REDUCE_OR.
9567     if (VT == MVT::i1)
9568       Opcode = ISD::VP_REDUCE_OR;
9569     break;
9570   }
9571 
9572   // Memoize nodes.
9573   SDNode *N;
9574   SDVTList VTs = getVTList(VT);
9575 
9576   if (VT != MVT::Glue) {
9577     FoldingSetNodeID ID;
9578     AddNodeIDNode(ID, Opcode, VTs, Ops);
9579     void *IP = nullptr;
9580 
9581     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9582       return SDValue(E, 0);
9583 
9584     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9585     createOperands(N, Ops);
9586 
9587     CSEMap.InsertNode(N, IP);
9588   } else {
9589     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9590     createOperands(N, Ops);
9591   }
9592 
9593   N->setFlags(Flags);
9594   InsertNode(N);
9595   SDValue V(N, 0);
9596   NewSDValueDbgMsg(V, "Creating new node: ", this);
9597   return V;
9598 }
9599 
9600 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9601                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
9602   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
9603 }
9604 
9605 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9606                               ArrayRef<SDValue> Ops) {
9607   SDNodeFlags Flags;
9608   if (Inserter)
9609     Flags = Inserter->getFlags();
9610   return getNode(Opcode, DL, VTList, Ops, Flags);
9611 }
9612 
9613 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9614                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9615   if (VTList.NumVTs == 1)
9616     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9617 
9618 #ifndef NDEBUG
9619   for (const auto &Op : Ops)
9620     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9621            "Operand is DELETED_NODE!");
9622 #endif
9623 
9624   switch (Opcode) {
9625   case ISD::SADDO:
9626   case ISD::UADDO:
9627   case ISD::SSUBO:
9628   case ISD::USUBO: {
9629     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9630            "Invalid add/sub overflow op!");
9631     assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
9632            Ops[0].getValueType() == Ops[1].getValueType() &&
9633            Ops[0].getValueType() == VTList.VTs[0] &&
9634            "Binary operator types must match!");
9635     SDValue N1 = Ops[0], N2 = Ops[1];
9636     canonicalizeCommutativeBinop(Opcode, N1, N2);
9637 
9638     // (X +- 0) -> X with zero-overflow.
9639     ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
9640                                                /*AllowTruncation*/ true);
9641     if (N2CV && N2CV->isZero()) {
9642       SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
9643       return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
9644     }
9645     break;
9646   }
9647   case ISD::SMUL_LOHI:
9648   case ISD::UMUL_LOHI: {
9649     assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
9650     assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
9651            VTList.VTs[0] == Ops[0].getValueType() &&
9652            VTList.VTs[0] == Ops[1].getValueType() &&
9653            "Binary operator types must match!");
9654     break;
9655   }
9656   case ISD::FFREXP: {
9657     assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
9658     assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
9659            VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
9660 
9661     if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Ops[0])) {
9662       int FrexpExp;
9663       APFloat FrexpMant =
9664           frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
9665       SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
9666       SDValue Result1 =
9667           getConstant(FrexpMant.isFinite() ? FrexpExp : 0, DL, VTList.VTs[1]);
9668       return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
9669     }
9670 
9671     break;
9672   }
9673   case ISD::STRICT_FP_EXTEND:
9674     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9675            "Invalid STRICT_FP_EXTEND!");
9676     assert(VTList.VTs[0].isFloatingPoint() &&
9677            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9678     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9679            "STRICT_FP_EXTEND result type should be vector iff the operand "
9680            "type is vector!");
9681     assert((!VTList.VTs[0].isVector() ||
9682             VTList.VTs[0].getVectorElementCount() ==
9683                 Ops[1].getValueType().getVectorElementCount()) &&
9684            "Vector element count mismatch!");
9685     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9686            "Invalid fpext node, dst <= src!");
9687     break;
9688   case ISD::STRICT_FP_ROUND:
9689     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9690     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9691            "STRICT_FP_ROUND result type should be vector iff the operand "
9692            "type is vector!");
9693     assert((!VTList.VTs[0].isVector() ||
9694             VTList.VTs[0].getVectorElementCount() ==
9695                 Ops[1].getValueType().getVectorElementCount()) &&
9696            "Vector element count mismatch!");
9697     assert(VTList.VTs[0].isFloatingPoint() &&
9698            Ops[1].getValueType().isFloatingPoint() &&
9699            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9700            isa<ConstantSDNode>(Ops[2]) &&
9701            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9702             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9703            "Invalid STRICT_FP_ROUND!");
9704     break;
9705 #if 0
9706   // FIXME: figure out how to safely handle things like
9707   // int foo(int x) { return 1 << (x & 255); }
9708   // int bar() { return foo(256); }
9709   case ISD::SRA_PARTS:
9710   case ISD::SRL_PARTS:
9711   case ISD::SHL_PARTS:
9712     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9713         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9714       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9715     else if (N3.getOpcode() == ISD::AND)
9716       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9717         // If the and is only masking out bits that cannot effect the shift,
9718         // eliminate the and.
9719         unsigned NumBits = VT.getScalarSizeInBits()*2;
9720         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9721           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9722       }
9723     break;
9724 #endif
9725   }
9726 
9727   // Memoize the node unless it returns a flag.
9728   SDNode *N;
9729   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9730     FoldingSetNodeID ID;
9731     AddNodeIDNode(ID, Opcode, VTList, Ops);
9732     void *IP = nullptr;
9733     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9734       return SDValue(E, 0);
9735 
9736     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9737     createOperands(N, Ops);
9738     CSEMap.InsertNode(N, IP);
9739   } else {
9740     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9741     createOperands(N, Ops);
9742   }
9743 
9744   N->setFlags(Flags);
9745   InsertNode(N);
9746   SDValue V(N, 0);
9747   NewSDValueDbgMsg(V, "Creating new node: ", this);
9748   return V;
9749 }
9750 
9751 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9752                               SDVTList VTList) {
9753   return getNode(Opcode, DL, VTList, std::nullopt);
9754 }
9755 
9756 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9757                               SDValue N1) {
9758   SDValue Ops[] = { N1 };
9759   return getNode(Opcode, DL, VTList, Ops);
9760 }
9761 
9762 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9763                               SDValue N1, SDValue N2) {
9764   SDValue Ops[] = { N1, N2 };
9765   return getNode(Opcode, DL, VTList, Ops);
9766 }
9767 
9768 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9769                               SDValue N1, SDValue N2, SDValue N3) {
9770   SDValue Ops[] = { N1, N2, N3 };
9771   return getNode(Opcode, DL, VTList, Ops);
9772 }
9773 
9774 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9775                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9776   SDValue Ops[] = { N1, N2, N3, N4 };
9777   return getNode(Opcode, DL, VTList, Ops);
9778 }
9779 
9780 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9781                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9782                               SDValue N5) {
9783   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9784   return getNode(Opcode, DL, VTList, Ops);
9785 }
9786 
9787 SDVTList SelectionDAG::getVTList(EVT VT) {
9788   return makeVTList(SDNode::getValueTypeList(VT), 1);
9789 }
9790 
9791 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9792   FoldingSetNodeID ID;
9793   ID.AddInteger(2U);
9794   ID.AddInteger(VT1.getRawBits());
9795   ID.AddInteger(VT2.getRawBits());
9796 
9797   void *IP = nullptr;
9798   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9799   if (!Result) {
9800     EVT *Array = Allocator.Allocate<EVT>(2);
9801     Array[0] = VT1;
9802     Array[1] = VT2;
9803     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9804     VTListMap.InsertNode(Result, IP);
9805   }
9806   return Result->getSDVTList();
9807 }
9808 
9809 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9810   FoldingSetNodeID ID;
9811   ID.AddInteger(3U);
9812   ID.AddInteger(VT1.getRawBits());
9813   ID.AddInteger(VT2.getRawBits());
9814   ID.AddInteger(VT3.getRawBits());
9815 
9816   void *IP = nullptr;
9817   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9818   if (!Result) {
9819     EVT *Array = Allocator.Allocate<EVT>(3);
9820     Array[0] = VT1;
9821     Array[1] = VT2;
9822     Array[2] = VT3;
9823     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9824     VTListMap.InsertNode(Result, IP);
9825   }
9826   return Result->getSDVTList();
9827 }
9828 
9829 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9830   FoldingSetNodeID ID;
9831   ID.AddInteger(4U);
9832   ID.AddInteger(VT1.getRawBits());
9833   ID.AddInteger(VT2.getRawBits());
9834   ID.AddInteger(VT3.getRawBits());
9835   ID.AddInteger(VT4.getRawBits());
9836 
9837   void *IP = nullptr;
9838   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9839   if (!Result) {
9840     EVT *Array = Allocator.Allocate<EVT>(4);
9841     Array[0] = VT1;
9842     Array[1] = VT2;
9843     Array[2] = VT3;
9844     Array[3] = VT4;
9845     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9846     VTListMap.InsertNode(Result, IP);
9847   }
9848   return Result->getSDVTList();
9849 }
9850 
9851 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9852   unsigned NumVTs = VTs.size();
9853   FoldingSetNodeID ID;
9854   ID.AddInteger(NumVTs);
9855   for (unsigned index = 0; index < NumVTs; index++) {
9856     ID.AddInteger(VTs[index].getRawBits());
9857   }
9858 
9859   void *IP = nullptr;
9860   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9861   if (!Result) {
9862     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9863     llvm::copy(VTs, Array);
9864     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9865     VTListMap.InsertNode(Result, IP);
9866   }
9867   return Result->getSDVTList();
9868 }
9869 
9870 
9871 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9872 /// specified operands.  If the resultant node already exists in the DAG,
9873 /// this does not modify the specified node, instead it returns the node that
9874 /// already exists.  If the resultant node does not exist in the DAG, the
9875 /// input node is returned.  As a degenerate case, if you specify the same
9876 /// input operands as the node already has, the input node is returned.
9877 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9878   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9879 
9880   // Check to see if there is no change.
9881   if (Op == N->getOperand(0)) return N;
9882 
9883   // See if the modified node already exists.
9884   void *InsertPos = nullptr;
9885   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9886     return Existing;
9887 
9888   // Nope it doesn't.  Remove the node from its current place in the maps.
9889   if (InsertPos)
9890     if (!RemoveNodeFromCSEMaps(N))
9891       InsertPos = nullptr;
9892 
9893   // Now we update the operands.
9894   N->OperandList[0].set(Op);
9895 
9896   updateDivergence(N);
9897   // If this gets put into a CSE map, add it.
9898   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9899   return N;
9900 }
9901 
9902 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9903   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9904 
9905   // Check to see if there is no change.
9906   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9907     return N;   // No operands changed, just return the input node.
9908 
9909   // See if the modified node already exists.
9910   void *InsertPos = nullptr;
9911   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9912     return Existing;
9913 
9914   // Nope it doesn't.  Remove the node from its current place in the maps.
9915   if (InsertPos)
9916     if (!RemoveNodeFromCSEMaps(N))
9917       InsertPos = nullptr;
9918 
9919   // Now we update the operands.
9920   if (N->OperandList[0] != Op1)
9921     N->OperandList[0].set(Op1);
9922   if (N->OperandList[1] != Op2)
9923     N->OperandList[1].set(Op2);
9924 
9925   updateDivergence(N);
9926   // If this gets put into a CSE map, add it.
9927   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9928   return N;
9929 }
9930 
9931 SDNode *SelectionDAG::
9932 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9933   SDValue Ops[] = { Op1, Op2, Op3 };
9934   return UpdateNodeOperands(N, Ops);
9935 }
9936 
9937 SDNode *SelectionDAG::
9938 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9939                    SDValue Op3, SDValue Op4) {
9940   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9941   return UpdateNodeOperands(N, Ops);
9942 }
9943 
9944 SDNode *SelectionDAG::
9945 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9946                    SDValue Op3, SDValue Op4, SDValue Op5) {
9947   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9948   return UpdateNodeOperands(N, Ops);
9949 }
9950 
9951 SDNode *SelectionDAG::
9952 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9953   unsigned NumOps = Ops.size();
9954   assert(N->getNumOperands() == NumOps &&
9955          "Update with wrong number of operands");
9956 
9957   // If no operands changed just return the input node.
9958   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9959     return N;
9960 
9961   // See if the modified node already exists.
9962   void *InsertPos = nullptr;
9963   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9964     return Existing;
9965 
9966   // Nope it doesn't.  Remove the node from its current place in the maps.
9967   if (InsertPos)
9968     if (!RemoveNodeFromCSEMaps(N))
9969       InsertPos = nullptr;
9970 
9971   // Now we update the operands.
9972   for (unsigned i = 0; i != NumOps; ++i)
9973     if (N->OperandList[i] != Ops[i])
9974       N->OperandList[i].set(Ops[i]);
9975 
9976   updateDivergence(N);
9977   // If this gets put into a CSE map, add it.
9978   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9979   return N;
9980 }
9981 
9982 /// DropOperands - Release the operands and set this node to have
9983 /// zero operands.
9984 void SDNode::DropOperands() {
9985   // Unlike the code in MorphNodeTo that does this, we don't need to
9986   // watch for dead nodes here.
9987   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9988     SDUse &Use = *I++;
9989     Use.set(SDValue());
9990   }
9991 }
9992 
9993 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9994                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9995   if (NewMemRefs.empty()) {
9996     N->clearMemRefs();
9997     return;
9998   }
9999 
10000   // Check if we can avoid allocating by storing a single reference directly.
10001   if (NewMemRefs.size() == 1) {
10002     N->MemRefs = NewMemRefs[0];
10003     N->NumMemRefs = 1;
10004     return;
10005   }
10006 
10007   MachineMemOperand **MemRefsBuffer =
10008       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
10009   llvm::copy(NewMemRefs, MemRefsBuffer);
10010   N->MemRefs = MemRefsBuffer;
10011   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
10012 }
10013 
10014 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
10015 /// machine opcode.
10016 ///
10017 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10018                                    EVT VT) {
10019   SDVTList VTs = getVTList(VT);
10020   return SelectNodeTo(N, MachineOpc, VTs, std::nullopt);
10021 }
10022 
10023 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10024                                    EVT VT, SDValue Op1) {
10025   SDVTList VTs = getVTList(VT);
10026   SDValue Ops[] = { Op1 };
10027   return SelectNodeTo(N, MachineOpc, VTs, Ops);
10028 }
10029 
10030 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10031                                    EVT VT, SDValue Op1,
10032                                    SDValue Op2) {
10033   SDVTList VTs = getVTList(VT);
10034   SDValue Ops[] = { Op1, Op2 };
10035   return SelectNodeTo(N, MachineOpc, VTs, Ops);
10036 }
10037 
10038 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10039                                    EVT VT, SDValue Op1,
10040                                    SDValue Op2, SDValue Op3) {
10041   SDVTList VTs = getVTList(VT);
10042   SDValue Ops[] = { Op1, Op2, Op3 };
10043   return SelectNodeTo(N, MachineOpc, VTs, Ops);
10044 }
10045 
10046 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10047                                    EVT VT, ArrayRef<SDValue> Ops) {
10048   SDVTList VTs = getVTList(VT);
10049   return SelectNodeTo(N, MachineOpc, VTs, Ops);
10050 }
10051 
10052 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10053                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
10054   SDVTList VTs = getVTList(VT1, VT2);
10055   return SelectNodeTo(N, MachineOpc, VTs, Ops);
10056 }
10057 
10058 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10059                                    EVT VT1, EVT VT2) {
10060   SDVTList VTs = getVTList(VT1, VT2);
10061   return SelectNodeTo(N, MachineOpc, VTs, std::nullopt);
10062 }
10063 
10064 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10065                                    EVT VT1, EVT VT2, EVT VT3,
10066                                    ArrayRef<SDValue> Ops) {
10067   SDVTList VTs = getVTList(VT1, VT2, VT3);
10068   return SelectNodeTo(N, MachineOpc, VTs, Ops);
10069 }
10070 
10071 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10072                                    EVT VT1, EVT VT2,
10073                                    SDValue Op1, SDValue Op2) {
10074   SDVTList VTs = getVTList(VT1, VT2);
10075   SDValue Ops[] = { Op1, Op2 };
10076   return SelectNodeTo(N, MachineOpc, VTs, Ops);
10077 }
10078 
10079 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
10080                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
10081   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
10082   // Reset the NodeID to -1.
10083   New->setNodeId(-1);
10084   if (New != N) {
10085     ReplaceAllUsesWith(N, New);
10086     RemoveDeadNode(N);
10087   }
10088   return New;
10089 }
10090 
10091 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
10092 /// the line number information on the merged node since it is not possible to
10093 /// preserve the information that operation is associated with multiple lines.
10094 /// This will make the debugger working better at -O0, were there is a higher
10095 /// probability having other instructions associated with that line.
10096 ///
10097 /// For IROrder, we keep the smaller of the two
10098 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
10099   DebugLoc NLoc = N->getDebugLoc();
10100   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
10101     N->setDebugLoc(DebugLoc());
10102   }
10103   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
10104   N->setIROrder(Order);
10105   return N;
10106 }
10107 
10108 /// MorphNodeTo - This *mutates* the specified node to have the specified
10109 /// return type, opcode, and operands.
10110 ///
10111 /// Note that MorphNodeTo returns the resultant node.  If there is already a
10112 /// node of the specified opcode and operands, it returns that node instead of
10113 /// the current one.  Note that the SDLoc need not be the same.
10114 ///
10115 /// Using MorphNodeTo is faster than creating a new node and swapping it in
10116 /// with ReplaceAllUsesWith both because it often avoids allocating a new
10117 /// node, and because it doesn't require CSE recalculation for any of
10118 /// the node's users.
10119 ///
10120 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
10121 /// As a consequence it isn't appropriate to use from within the DAG combiner or
10122 /// the legalizer which maintain worklists that would need to be updated when
10123 /// deleting things.
10124 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
10125                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
10126   // If an identical node already exists, use it.
10127   void *IP = nullptr;
10128   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
10129     FoldingSetNodeID ID;
10130     AddNodeIDNode(ID, Opc, VTs, Ops);
10131     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
10132       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
10133   }
10134 
10135   if (!RemoveNodeFromCSEMaps(N))
10136     IP = nullptr;
10137 
10138   // Start the morphing.
10139   N->NodeType = Opc;
10140   N->ValueList = VTs.VTs;
10141   N->NumValues = VTs.NumVTs;
10142 
10143   // Clear the operands list, updating used nodes to remove this from their
10144   // use list.  Keep track of any operands that become dead as a result.
10145   SmallPtrSet<SDNode*, 16> DeadNodeSet;
10146   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
10147     SDUse &Use = *I++;
10148     SDNode *Used = Use.getNode();
10149     Use.set(SDValue());
10150     if (Used->use_empty())
10151       DeadNodeSet.insert(Used);
10152   }
10153 
10154   // For MachineNode, initialize the memory references information.
10155   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
10156     MN->clearMemRefs();
10157 
10158   // Swap for an appropriately sized array from the recycler.
10159   removeOperands(N);
10160   createOperands(N, Ops);
10161 
10162   // Delete any nodes that are still dead after adding the uses for the
10163   // new operands.
10164   if (!DeadNodeSet.empty()) {
10165     SmallVector<SDNode *, 16> DeadNodes;
10166     for (SDNode *N : DeadNodeSet)
10167       if (N->use_empty())
10168         DeadNodes.push_back(N);
10169     RemoveDeadNodes(DeadNodes);
10170   }
10171 
10172   if (IP)
10173     CSEMap.InsertNode(N, IP);   // Memoize the new node.
10174   return N;
10175 }
10176 
10177 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
10178   unsigned OrigOpc = Node->getOpcode();
10179   unsigned NewOpc;
10180   switch (OrigOpc) {
10181   default:
10182     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
10183 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
10184   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
10185 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
10186   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
10187 #include "llvm/IR/ConstrainedOps.def"
10188   }
10189 
10190   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
10191 
10192   // We're taking this node out of the chain, so we need to re-link things.
10193   SDValue InputChain = Node->getOperand(0);
10194   SDValue OutputChain = SDValue(Node, 1);
10195   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
10196 
10197   SmallVector<SDValue, 3> Ops;
10198   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
10199     Ops.push_back(Node->getOperand(i));
10200 
10201   SDVTList VTs = getVTList(Node->getValueType(0));
10202   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
10203 
10204   // MorphNodeTo can operate in two ways: if an existing node with the
10205   // specified operands exists, it can just return it.  Otherwise, it
10206   // updates the node in place to have the requested operands.
10207   if (Res == Node) {
10208     // If we updated the node in place, reset the node ID.  To the isel,
10209     // this should be just like a newly allocated machine node.
10210     Res->setNodeId(-1);
10211   } else {
10212     ReplaceAllUsesWith(Node, Res);
10213     RemoveDeadNode(Node);
10214   }
10215 
10216   return Res;
10217 }
10218 
10219 /// getMachineNode - These are used for target selectors to create a new node
10220 /// with specified return type(s), MachineInstr opcode, and operands.
10221 ///
10222 /// Note that getMachineNode returns the resultant node.  If there is already a
10223 /// node of the specified opcode and operands, it returns that node instead of
10224 /// the current one.
10225 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10226                                             EVT VT) {
10227   SDVTList VTs = getVTList(VT);
10228   return getMachineNode(Opcode, dl, VTs, std::nullopt);
10229 }
10230 
10231 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10232                                             EVT VT, SDValue Op1) {
10233   SDVTList VTs = getVTList(VT);
10234   SDValue Ops[] = { Op1 };
10235   return getMachineNode(Opcode, dl, VTs, Ops);
10236 }
10237 
10238 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10239                                             EVT VT, SDValue Op1, SDValue Op2) {
10240   SDVTList VTs = getVTList(VT);
10241   SDValue Ops[] = { Op1, Op2 };
10242   return getMachineNode(Opcode, dl, VTs, Ops);
10243 }
10244 
10245 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10246                                             EVT VT, SDValue Op1, SDValue Op2,
10247                                             SDValue Op3) {
10248   SDVTList VTs = getVTList(VT);
10249   SDValue Ops[] = { Op1, Op2, Op3 };
10250   return getMachineNode(Opcode, dl, VTs, Ops);
10251 }
10252 
10253 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10254                                             EVT VT, ArrayRef<SDValue> Ops) {
10255   SDVTList VTs = getVTList(VT);
10256   return getMachineNode(Opcode, dl, VTs, Ops);
10257 }
10258 
10259 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10260                                             EVT VT1, EVT VT2, SDValue Op1,
10261                                             SDValue Op2) {
10262   SDVTList VTs = getVTList(VT1, VT2);
10263   SDValue Ops[] = { Op1, Op2 };
10264   return getMachineNode(Opcode, dl, VTs, Ops);
10265 }
10266 
10267 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10268                                             EVT VT1, EVT VT2, SDValue Op1,
10269                                             SDValue Op2, SDValue Op3) {
10270   SDVTList VTs = getVTList(VT1, VT2);
10271   SDValue Ops[] = { Op1, Op2, Op3 };
10272   return getMachineNode(Opcode, dl, VTs, Ops);
10273 }
10274 
10275 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10276                                             EVT VT1, EVT VT2,
10277                                             ArrayRef<SDValue> Ops) {
10278   SDVTList VTs = getVTList(VT1, VT2);
10279   return getMachineNode(Opcode, dl, VTs, Ops);
10280 }
10281 
10282 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10283                                             EVT VT1, EVT VT2, EVT VT3,
10284                                             SDValue Op1, SDValue Op2) {
10285   SDVTList VTs = getVTList(VT1, VT2, VT3);
10286   SDValue Ops[] = { Op1, Op2 };
10287   return getMachineNode(Opcode, dl, VTs, Ops);
10288 }
10289 
10290 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10291                                             EVT VT1, EVT VT2, EVT VT3,
10292                                             SDValue Op1, SDValue Op2,
10293                                             SDValue Op3) {
10294   SDVTList VTs = getVTList(VT1, VT2, VT3);
10295   SDValue Ops[] = { Op1, Op2, Op3 };
10296   return getMachineNode(Opcode, dl, VTs, Ops);
10297 }
10298 
10299 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10300                                             EVT VT1, EVT VT2, EVT VT3,
10301                                             ArrayRef<SDValue> Ops) {
10302   SDVTList VTs = getVTList(VT1, VT2, VT3);
10303   return getMachineNode(Opcode, dl, VTs, Ops);
10304 }
10305 
10306 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
10307                                             ArrayRef<EVT> ResultTys,
10308                                             ArrayRef<SDValue> Ops) {
10309   SDVTList VTs = getVTList(ResultTys);
10310   return getMachineNode(Opcode, dl, VTs, Ops);
10311 }
10312 
10313 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
10314                                             SDVTList VTs,
10315                                             ArrayRef<SDValue> Ops) {
10316   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
10317   MachineSDNode *N;
10318   void *IP = nullptr;
10319 
10320   if (DoCSE) {
10321     FoldingSetNodeID ID;
10322     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
10323     IP = nullptr;
10324     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
10325       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
10326     }
10327   }
10328 
10329   // Allocate a new MachineSDNode.
10330   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
10331   createOperands(N, Ops);
10332 
10333   if (DoCSE)
10334     CSEMap.InsertNode(N, IP);
10335 
10336   InsertNode(N);
10337   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
10338   return N;
10339 }
10340 
10341 /// getTargetExtractSubreg - A convenience function for creating
10342 /// TargetOpcode::EXTRACT_SUBREG nodes.
10343 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
10344                                              SDValue Operand) {
10345   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
10346   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
10347                                   VT, Operand, SRIdxVal);
10348   return SDValue(Subreg, 0);
10349 }
10350 
10351 /// getTargetInsertSubreg - A convenience function for creating
10352 /// TargetOpcode::INSERT_SUBREG nodes.
10353 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
10354                                             SDValue Operand, SDValue Subreg) {
10355   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
10356   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
10357                                   VT, Operand, Subreg, SRIdxVal);
10358   return SDValue(Result, 0);
10359 }
10360 
10361 /// getNodeIfExists - Get the specified node if it's already available, or
10362 /// else return NULL.
10363 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
10364                                       ArrayRef<SDValue> Ops) {
10365   SDNodeFlags Flags;
10366   if (Inserter)
10367     Flags = Inserter->getFlags();
10368   return getNodeIfExists(Opcode, VTList, Ops, Flags);
10369 }
10370 
10371 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
10372                                       ArrayRef<SDValue> Ops,
10373                                       const SDNodeFlags Flags) {
10374   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
10375     FoldingSetNodeID ID;
10376     AddNodeIDNode(ID, Opcode, VTList, Ops);
10377     void *IP = nullptr;
10378     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
10379       E->intersectFlagsWith(Flags);
10380       return E;
10381     }
10382   }
10383   return nullptr;
10384 }
10385 
10386 /// doesNodeExist - Check if a node exists without modifying its flags.
10387 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
10388                                  ArrayRef<SDValue> Ops) {
10389   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
10390     FoldingSetNodeID ID;
10391     AddNodeIDNode(ID, Opcode, VTList, Ops);
10392     void *IP = nullptr;
10393     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
10394       return true;
10395   }
10396   return false;
10397 }
10398 
10399 /// getDbgValue - Creates a SDDbgValue node.
10400 ///
10401 /// SDNode
10402 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
10403                                       SDNode *N, unsigned R, bool IsIndirect,
10404                                       const DebugLoc &DL, unsigned O) {
10405   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
10406          "Expected inlined-at fields to agree");
10407   return new (DbgInfo->getAlloc())
10408       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
10409                  {}, IsIndirect, DL, O,
10410                  /*IsVariadic=*/false);
10411 }
10412 
10413 /// Constant
10414 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
10415                                               DIExpression *Expr,
10416                                               const Value *C,
10417                                               const DebugLoc &DL, unsigned O) {
10418   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
10419          "Expected inlined-at fields to agree");
10420   return new (DbgInfo->getAlloc())
10421       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
10422                  /*IsIndirect=*/false, DL, O,
10423                  /*IsVariadic=*/false);
10424 }
10425 
10426 /// FrameIndex
10427 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
10428                                                 DIExpression *Expr, unsigned FI,
10429                                                 bool IsIndirect,
10430                                                 const DebugLoc &DL,
10431                                                 unsigned O) {
10432   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
10433          "Expected inlined-at fields to agree");
10434   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
10435 }
10436 
10437 /// FrameIndex with dependencies
10438 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
10439                                                 DIExpression *Expr, unsigned FI,
10440                                                 ArrayRef<SDNode *> Dependencies,
10441                                                 bool IsIndirect,
10442                                                 const DebugLoc &DL,
10443                                                 unsigned O) {
10444   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
10445          "Expected inlined-at fields to agree");
10446   return new (DbgInfo->getAlloc())
10447       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
10448                  Dependencies, IsIndirect, DL, O,
10449                  /*IsVariadic=*/false);
10450 }
10451 
10452 /// VReg
10453 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
10454                                           unsigned VReg, bool IsIndirect,
10455                                           const DebugLoc &DL, unsigned O) {
10456   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
10457          "Expected inlined-at fields to agree");
10458   return new (DbgInfo->getAlloc())
10459       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
10460                  {}, IsIndirect, DL, O,
10461                  /*IsVariadic=*/false);
10462 }
10463 
10464 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
10465                                           ArrayRef<SDDbgOperand> Locs,
10466                                           ArrayRef<SDNode *> Dependencies,
10467                                           bool IsIndirect, const DebugLoc &DL,
10468                                           unsigned O, bool IsVariadic) {
10469   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
10470          "Expected inlined-at fields to agree");
10471   return new (DbgInfo->getAlloc())
10472       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
10473                  DL, O, IsVariadic);
10474 }
10475 
10476 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
10477                                      unsigned OffsetInBits, unsigned SizeInBits,
10478                                      bool InvalidateDbg) {
10479   SDNode *FromNode = From.getNode();
10480   SDNode *ToNode = To.getNode();
10481   assert(FromNode && ToNode && "Can't modify dbg values");
10482 
10483   // PR35338
10484   // TODO: assert(From != To && "Redundant dbg value transfer");
10485   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
10486   if (From == To || FromNode == ToNode)
10487     return;
10488 
10489   if (!FromNode->getHasDebugValue())
10490     return;
10491 
10492   SDDbgOperand FromLocOp =
10493       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
10494   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
10495 
10496   SmallVector<SDDbgValue *, 2> ClonedDVs;
10497   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
10498     if (Dbg->isInvalidated())
10499       continue;
10500 
10501     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
10502 
10503     // Create a new location ops vector that is equal to the old vector, but
10504     // with each instance of FromLocOp replaced with ToLocOp.
10505     bool Changed = false;
10506     auto NewLocOps = Dbg->copyLocationOps();
10507     std::replace_if(
10508         NewLocOps.begin(), NewLocOps.end(),
10509         [&Changed, FromLocOp](const SDDbgOperand &Op) {
10510           bool Match = Op == FromLocOp;
10511           Changed |= Match;
10512           return Match;
10513         },
10514         ToLocOp);
10515     // Ignore this SDDbgValue if we didn't find a matching location.
10516     if (!Changed)
10517       continue;
10518 
10519     DIVariable *Var = Dbg->getVariable();
10520     auto *Expr = Dbg->getExpression();
10521     // If a fragment is requested, update the expression.
10522     if (SizeInBits) {
10523       // When splitting a larger (e.g., sign-extended) value whose
10524       // lower bits are described with an SDDbgValue, do not attempt
10525       // to transfer the SDDbgValue to the upper bits.
10526       if (auto FI = Expr->getFragmentInfo())
10527         if (OffsetInBits + SizeInBits > FI->SizeInBits)
10528           continue;
10529       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
10530                                                              SizeInBits);
10531       if (!Fragment)
10532         continue;
10533       Expr = *Fragment;
10534     }
10535 
10536     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
10537     // Clone the SDDbgValue and move it to To.
10538     SDDbgValue *Clone = getDbgValueList(
10539         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
10540         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
10541         Dbg->isVariadic());
10542     ClonedDVs.push_back(Clone);
10543 
10544     if (InvalidateDbg) {
10545       // Invalidate value and indicate the SDDbgValue should not be emitted.
10546       Dbg->setIsInvalidated();
10547       Dbg->setIsEmitted();
10548     }
10549   }
10550 
10551   for (SDDbgValue *Dbg : ClonedDVs) {
10552     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
10553            "Transferred DbgValues should depend on the new SDNode");
10554     AddDbgValue(Dbg, false);
10555   }
10556 }
10557 
10558 void SelectionDAG::salvageDebugInfo(SDNode &N) {
10559   if (!N.getHasDebugValue())
10560     return;
10561 
10562   SmallVector<SDDbgValue *, 2> ClonedDVs;
10563   for (auto *DV : GetDbgValues(&N)) {
10564     if (DV->isInvalidated())
10565       continue;
10566     switch (N.getOpcode()) {
10567     default:
10568       break;
10569     case ISD::ADD:
10570       SDValue N0 = N.getOperand(0);
10571       SDValue N1 = N.getOperand(1);
10572       if (!isa<ConstantSDNode>(N0) && isa<ConstantSDNode>(N1)) {
10573         uint64_t Offset = N.getConstantOperandVal(1);
10574 
10575         // Rewrite an ADD constant node into a DIExpression. Since we are
10576         // performing arithmetic to compute the variable's *value* in the
10577         // DIExpression, we need to mark the expression with a
10578         // DW_OP_stack_value.
10579         auto *DIExpr = DV->getExpression();
10580         auto NewLocOps = DV->copyLocationOps();
10581         bool Changed = false;
10582         for (size_t i = 0; i < NewLocOps.size(); ++i) {
10583           // We're not given a ResNo to compare against because the whole
10584           // node is going away. We know that any ISD::ADD only has one
10585           // result, so we can assume any node match is using the result.
10586           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
10587               NewLocOps[i].getSDNode() != &N)
10588             continue;
10589           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
10590           SmallVector<uint64_t, 3> ExprOps;
10591           DIExpression::appendOffset(ExprOps, Offset);
10592           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
10593           Changed = true;
10594         }
10595         (void)Changed;
10596         assert(Changed && "Salvage target doesn't use N");
10597 
10598         auto AdditionalDependencies = DV->getAdditionalDependencies();
10599         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
10600                                             NewLocOps, AdditionalDependencies,
10601                                             DV->isIndirect(), DV->getDebugLoc(),
10602                                             DV->getOrder(), DV->isVariadic());
10603         ClonedDVs.push_back(Clone);
10604         DV->setIsInvalidated();
10605         DV->setIsEmitted();
10606         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
10607                    N0.getNode()->dumprFull(this);
10608                    dbgs() << " into " << *DIExpr << '\n');
10609       }
10610     }
10611   }
10612 
10613   for (SDDbgValue *Dbg : ClonedDVs) {
10614     assert(!Dbg->getSDNodes().empty() &&
10615            "Salvaged DbgValue should depend on a new SDNode");
10616     AddDbgValue(Dbg, false);
10617   }
10618 }
10619 
10620 /// Creates a SDDbgLabel node.
10621 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
10622                                       const DebugLoc &DL, unsigned O) {
10623   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
10624          "Expected inlined-at fields to agree");
10625   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
10626 }
10627 
10628 namespace {
10629 
10630 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
10631 /// pointed to by a use iterator is deleted, increment the use iterator
10632 /// so that it doesn't dangle.
10633 ///
10634 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
10635   SDNode::use_iterator &UI;
10636   SDNode::use_iterator &UE;
10637 
10638   void NodeDeleted(SDNode *N, SDNode *E) override {
10639     // Increment the iterator as needed.
10640     while (UI != UE && N == *UI)
10641       ++UI;
10642   }
10643 
10644 public:
10645   RAUWUpdateListener(SelectionDAG &d,
10646                      SDNode::use_iterator &ui,
10647                      SDNode::use_iterator &ue)
10648     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
10649 };
10650 
10651 } // end anonymous namespace
10652 
10653 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10654 /// This can cause recursive merging of nodes in the DAG.
10655 ///
10656 /// This version assumes From has a single result value.
10657 ///
10658 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10659   SDNode *From = FromN.getNode();
10660   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10661          "Cannot replace with this method!");
10662   assert(From != To.getNode() && "Cannot replace uses of with self");
10663 
10664   // Preserve Debug Values
10665   transferDbgValues(FromN, To);
10666   // Preserve extra info.
10667   copyExtraInfo(From, To.getNode());
10668 
10669   // Iterate over all the existing uses of From. New uses will be added
10670   // to the beginning of the use list, which we avoid visiting.
10671   // This specifically avoids visiting uses of From that arise while the
10672   // replacement is happening, because any such uses would be the result
10673   // of CSE: If an existing node looks like From after one of its operands
10674   // is replaced by To, we don't want to replace of all its users with To
10675   // too. See PR3018 for more info.
10676   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10677   RAUWUpdateListener Listener(*this, UI, UE);
10678   while (UI != UE) {
10679     SDNode *User = *UI;
10680 
10681     // This node is about to morph, remove its old self from the CSE maps.
10682     RemoveNodeFromCSEMaps(User);
10683 
10684     // A user can appear in a use list multiple times, and when this
10685     // happens the uses are usually next to each other in the list.
10686     // To help reduce the number of CSE recomputations, process all
10687     // the uses of this user that we can find this way.
10688     do {
10689       SDUse &Use = UI.getUse();
10690       ++UI;
10691       Use.set(To);
10692       if (To->isDivergent() != From->isDivergent())
10693         updateDivergence(User);
10694     } while (UI != UE && *UI == User);
10695     // Now that we have modified User, add it back to the CSE maps.  If it
10696     // already exists there, recursively merge the results together.
10697     AddModifiedNodeToCSEMaps(User);
10698   }
10699 
10700   // If we just RAUW'd the root, take note.
10701   if (FromN == getRoot())
10702     setRoot(To);
10703 }
10704 
10705 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10706 /// This can cause recursive merging of nodes in the DAG.
10707 ///
10708 /// This version assumes that for each value of From, there is a
10709 /// corresponding value in To in the same position with the same type.
10710 ///
10711 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10712 #ifndef NDEBUG
10713   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10714     assert((!From->hasAnyUseOfValue(i) ||
10715             From->getValueType(i) == To->getValueType(i)) &&
10716            "Cannot use this version of ReplaceAllUsesWith!");
10717 #endif
10718 
10719   // Handle the trivial case.
10720   if (From == To)
10721     return;
10722 
10723   // Preserve Debug Info. Only do this if there's a use.
10724   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10725     if (From->hasAnyUseOfValue(i)) {
10726       assert((i < To->getNumValues()) && "Invalid To location");
10727       transferDbgValues(SDValue(From, i), SDValue(To, i));
10728     }
10729   // Preserve extra info.
10730   copyExtraInfo(From, To);
10731 
10732   // Iterate over just the existing users of From. See the comments in
10733   // the ReplaceAllUsesWith above.
10734   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10735   RAUWUpdateListener Listener(*this, UI, UE);
10736   while (UI != UE) {
10737     SDNode *User = *UI;
10738 
10739     // This node is about to morph, remove its old self from the CSE maps.
10740     RemoveNodeFromCSEMaps(User);
10741 
10742     // A user can appear in a use list multiple times, and when this
10743     // happens the uses are usually next to each other in the list.
10744     // To help reduce the number of CSE recomputations, process all
10745     // the uses of this user that we can find this way.
10746     do {
10747       SDUse &Use = UI.getUse();
10748       ++UI;
10749       Use.setNode(To);
10750       if (To->isDivergent() != From->isDivergent())
10751         updateDivergence(User);
10752     } while (UI != UE && *UI == User);
10753 
10754     // Now that we have modified User, add it back to the CSE maps.  If it
10755     // already exists there, recursively merge the results together.
10756     AddModifiedNodeToCSEMaps(User);
10757   }
10758 
10759   // If we just RAUW'd the root, take note.
10760   if (From == getRoot().getNode())
10761     setRoot(SDValue(To, getRoot().getResNo()));
10762 }
10763 
10764 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10765 /// This can cause recursive merging of nodes in the DAG.
10766 ///
10767 /// This version can replace From with any result values.  To must match the
10768 /// number and types of values returned by From.
10769 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10770   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10771     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10772 
10773   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
10774     // Preserve Debug Info.
10775     transferDbgValues(SDValue(From, i), To[i]);
10776     // Preserve extra info.
10777     copyExtraInfo(From, To[i].getNode());
10778   }
10779 
10780   // Iterate over just the existing users of From. See the comments in
10781   // the ReplaceAllUsesWith above.
10782   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10783   RAUWUpdateListener Listener(*this, UI, UE);
10784   while (UI != UE) {
10785     SDNode *User = *UI;
10786 
10787     // This node is about to morph, remove its old self from the CSE maps.
10788     RemoveNodeFromCSEMaps(User);
10789 
10790     // A user can appear in a use list multiple times, and when this happens the
10791     // uses are usually next to each other in the list.  To help reduce the
10792     // number of CSE and divergence recomputations, process all the uses of this
10793     // user that we can find this way.
10794     bool To_IsDivergent = false;
10795     do {
10796       SDUse &Use = UI.getUse();
10797       const SDValue &ToOp = To[Use.getResNo()];
10798       ++UI;
10799       Use.set(ToOp);
10800       To_IsDivergent |= ToOp->isDivergent();
10801     } while (UI != UE && *UI == User);
10802 
10803     if (To_IsDivergent != From->isDivergent())
10804       updateDivergence(User);
10805 
10806     // Now that we have modified User, add it back to the CSE maps.  If it
10807     // already exists there, recursively merge the results together.
10808     AddModifiedNodeToCSEMaps(User);
10809   }
10810 
10811   // If we just RAUW'd the root, take note.
10812   if (From == getRoot().getNode())
10813     setRoot(SDValue(To[getRoot().getResNo()]));
10814 }
10815 
10816 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10817 /// uses of other values produced by From.getNode() alone.  The Deleted
10818 /// vector is handled the same way as for ReplaceAllUsesWith.
10819 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10820   // Handle the really simple, really trivial case efficiently.
10821   if (From == To) return;
10822 
10823   // Handle the simple, trivial, case efficiently.
10824   if (From.getNode()->getNumValues() == 1) {
10825     ReplaceAllUsesWith(From, To);
10826     return;
10827   }
10828 
10829   // Preserve Debug Info.
10830   transferDbgValues(From, To);
10831   copyExtraInfo(From.getNode(), To.getNode());
10832 
10833   // Iterate over just the existing users of From. See the comments in
10834   // the ReplaceAllUsesWith above.
10835   SDNode::use_iterator UI = From.getNode()->use_begin(),
10836                        UE = From.getNode()->use_end();
10837   RAUWUpdateListener Listener(*this, UI, UE);
10838   while (UI != UE) {
10839     SDNode *User = *UI;
10840     bool UserRemovedFromCSEMaps = false;
10841 
10842     // A user can appear in a use list multiple times, and when this
10843     // happens the uses are usually next to each other in the list.
10844     // To help reduce the number of CSE recomputations, process all
10845     // the uses of this user that we can find this way.
10846     do {
10847       SDUse &Use = UI.getUse();
10848 
10849       // Skip uses of different values from the same node.
10850       if (Use.getResNo() != From.getResNo()) {
10851         ++UI;
10852         continue;
10853       }
10854 
10855       // If this node hasn't been modified yet, it's still in the CSE maps,
10856       // so remove its old self from the CSE maps.
10857       if (!UserRemovedFromCSEMaps) {
10858         RemoveNodeFromCSEMaps(User);
10859         UserRemovedFromCSEMaps = true;
10860       }
10861 
10862       ++UI;
10863       Use.set(To);
10864       if (To->isDivergent() != From->isDivergent())
10865         updateDivergence(User);
10866     } while (UI != UE && *UI == User);
10867     // We are iterating over all uses of the From node, so if a use
10868     // doesn't use the specific value, no changes are made.
10869     if (!UserRemovedFromCSEMaps)
10870       continue;
10871 
10872     // Now that we have modified User, add it back to the CSE maps.  If it
10873     // already exists there, recursively merge the results together.
10874     AddModifiedNodeToCSEMaps(User);
10875   }
10876 
10877   // If we just RAUW'd the root, take note.
10878   if (From == getRoot())
10879     setRoot(To);
10880 }
10881 
10882 namespace {
10883 
10884 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10885 /// to record information about a use.
10886 struct UseMemo {
10887   SDNode *User;
10888   unsigned Index;
10889   SDUse *Use;
10890 };
10891 
10892 /// operator< - Sort Memos by User.
10893 bool operator<(const UseMemo &L, const UseMemo &R) {
10894   return (intptr_t)L.User < (intptr_t)R.User;
10895 }
10896 
10897 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10898 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10899 /// the node already has been taken care of recursively.
10900 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10901   SmallVector<UseMemo, 4> &Uses;
10902 
10903   void NodeDeleted(SDNode *N, SDNode *E) override {
10904     for (UseMemo &Memo : Uses)
10905       if (Memo.User == N)
10906         Memo.User = nullptr;
10907   }
10908 
10909 public:
10910   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10911       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10912 };
10913 
10914 } // end anonymous namespace
10915 
10916 bool SelectionDAG::calculateDivergence(SDNode *N) {
10917   if (TLI->isSDNodeAlwaysUniform(N)) {
10918     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
10919            "Conflicting divergence information!");
10920     return false;
10921   }
10922   if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
10923     return true;
10924   for (const auto &Op : N->ops()) {
10925     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10926       return true;
10927   }
10928   return false;
10929 }
10930 
10931 void SelectionDAG::updateDivergence(SDNode *N) {
10932   SmallVector<SDNode *, 16> Worklist(1, N);
10933   do {
10934     N = Worklist.pop_back_val();
10935     bool IsDivergent = calculateDivergence(N);
10936     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10937       N->SDNodeBits.IsDivergent = IsDivergent;
10938       llvm::append_range(Worklist, N->uses());
10939     }
10940   } while (!Worklist.empty());
10941 }
10942 
10943 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10944   DenseMap<SDNode *, unsigned> Degree;
10945   Order.reserve(AllNodes.size());
10946   for (auto &N : allnodes()) {
10947     unsigned NOps = N.getNumOperands();
10948     Degree[&N] = NOps;
10949     if (0 == NOps)
10950       Order.push_back(&N);
10951   }
10952   for (size_t I = 0; I != Order.size(); ++I) {
10953     SDNode *N = Order[I];
10954     for (auto *U : N->uses()) {
10955       unsigned &UnsortedOps = Degree[U];
10956       if (0 == --UnsortedOps)
10957         Order.push_back(U);
10958     }
10959   }
10960 }
10961 
10962 #ifndef NDEBUG
10963 void SelectionDAG::VerifyDAGDivergence() {
10964   std::vector<SDNode *> TopoOrder;
10965   CreateTopologicalOrder(TopoOrder);
10966   for (auto *N : TopoOrder) {
10967     assert(calculateDivergence(N) == N->isDivergent() &&
10968            "Divergence bit inconsistency detected");
10969   }
10970 }
10971 #endif
10972 
10973 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10974 /// uses of other values produced by From.getNode() alone.  The same value
10975 /// may appear in both the From and To list.  The Deleted vector is
10976 /// handled the same way as for ReplaceAllUsesWith.
10977 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10978                                               const SDValue *To,
10979                                               unsigned Num){
10980   // Handle the simple, trivial case efficiently.
10981   if (Num == 1)
10982     return ReplaceAllUsesOfValueWith(*From, *To);
10983 
10984   transferDbgValues(*From, *To);
10985   copyExtraInfo(From->getNode(), To->getNode());
10986 
10987   // Read up all the uses and make records of them. This helps
10988   // processing new uses that are introduced during the
10989   // replacement process.
10990   SmallVector<UseMemo, 4> Uses;
10991   for (unsigned i = 0; i != Num; ++i) {
10992     unsigned FromResNo = From[i].getResNo();
10993     SDNode *FromNode = From[i].getNode();
10994     for (SDNode::use_iterator UI = FromNode->use_begin(),
10995          E = FromNode->use_end(); UI != E; ++UI) {
10996       SDUse &Use = UI.getUse();
10997       if (Use.getResNo() == FromResNo) {
10998         UseMemo Memo = { *UI, i, &Use };
10999         Uses.push_back(Memo);
11000       }
11001     }
11002   }
11003 
11004   // Sort the uses, so that all the uses from a given User are together.
11005   llvm::sort(Uses);
11006   RAUOVWUpdateListener Listener(*this, Uses);
11007 
11008   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
11009        UseIndex != UseIndexEnd; ) {
11010     // We know that this user uses some value of From.  If it is the right
11011     // value, update it.
11012     SDNode *User = Uses[UseIndex].User;
11013     // If the node has been deleted by recursive CSE updates when updating
11014     // another node, then just skip this entry.
11015     if (User == nullptr) {
11016       ++UseIndex;
11017       continue;
11018     }
11019 
11020     // This node is about to morph, remove its old self from the CSE maps.
11021     RemoveNodeFromCSEMaps(User);
11022 
11023     // The Uses array is sorted, so all the uses for a given User
11024     // are next to each other in the list.
11025     // To help reduce the number of CSE recomputations, process all
11026     // the uses of this user that we can find this way.
11027     do {
11028       unsigned i = Uses[UseIndex].Index;
11029       SDUse &Use = *Uses[UseIndex].Use;
11030       ++UseIndex;
11031 
11032       Use.set(To[i]);
11033     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
11034 
11035     // Now that we have modified User, add it back to the CSE maps.  If it
11036     // already exists there, recursively merge the results together.
11037     AddModifiedNodeToCSEMaps(User);
11038   }
11039 }
11040 
11041 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
11042 /// based on their topological order. It returns the maximum id and a vector
11043 /// of the SDNodes* in assigned order by reference.
11044 unsigned SelectionDAG::AssignTopologicalOrder() {
11045   unsigned DAGSize = 0;
11046 
11047   // SortedPos tracks the progress of the algorithm. Nodes before it are
11048   // sorted, nodes after it are unsorted. When the algorithm completes
11049   // it is at the end of the list.
11050   allnodes_iterator SortedPos = allnodes_begin();
11051 
11052   // Visit all the nodes. Move nodes with no operands to the front of
11053   // the list immediately. Annotate nodes that do have operands with their
11054   // operand count. Before we do this, the Node Id fields of the nodes
11055   // may contain arbitrary values. After, the Node Id fields for nodes
11056   // before SortedPos will contain the topological sort index, and the
11057   // Node Id fields for nodes At SortedPos and after will contain the
11058   // count of outstanding operands.
11059   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
11060     checkForCycles(&N, this);
11061     unsigned Degree = N.getNumOperands();
11062     if (Degree == 0) {
11063       // A node with no uses, add it to the result array immediately.
11064       N.setNodeId(DAGSize++);
11065       allnodes_iterator Q(&N);
11066       if (Q != SortedPos)
11067         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
11068       assert(SortedPos != AllNodes.end() && "Overran node list");
11069       ++SortedPos;
11070     } else {
11071       // Temporarily use the Node Id as scratch space for the degree count.
11072       N.setNodeId(Degree);
11073     }
11074   }
11075 
11076   // Visit all the nodes. As we iterate, move nodes into sorted order,
11077   // such that by the time the end is reached all nodes will be sorted.
11078   for (SDNode &Node : allnodes()) {
11079     SDNode *N = &Node;
11080     checkForCycles(N, this);
11081     // N is in sorted position, so all its uses have one less operand
11082     // that needs to be sorted.
11083     for (SDNode *P : N->uses()) {
11084       unsigned Degree = P->getNodeId();
11085       assert(Degree != 0 && "Invalid node degree");
11086       --Degree;
11087       if (Degree == 0) {
11088         // All of P's operands are sorted, so P may sorted now.
11089         P->setNodeId(DAGSize++);
11090         if (P->getIterator() != SortedPos)
11091           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
11092         assert(SortedPos != AllNodes.end() && "Overran node list");
11093         ++SortedPos;
11094       } else {
11095         // Update P's outstanding operand count.
11096         P->setNodeId(Degree);
11097       }
11098     }
11099     if (Node.getIterator() == SortedPos) {
11100 #ifndef NDEBUG
11101       allnodes_iterator I(N);
11102       SDNode *S = &*++I;
11103       dbgs() << "Overran sorted position:\n";
11104       S->dumprFull(this); dbgs() << "\n";
11105       dbgs() << "Checking if this is due to cycles\n";
11106       checkForCycles(this, true);
11107 #endif
11108       llvm_unreachable(nullptr);
11109     }
11110   }
11111 
11112   assert(SortedPos == AllNodes.end() &&
11113          "Topological sort incomplete!");
11114   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
11115          "First node in topological sort is not the entry token!");
11116   assert(AllNodes.front().getNodeId() == 0 &&
11117          "First node in topological sort has non-zero id!");
11118   assert(AllNodes.front().getNumOperands() == 0 &&
11119          "First node in topological sort has operands!");
11120   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
11121          "Last node in topologic sort has unexpected id!");
11122   assert(AllNodes.back().use_empty() &&
11123          "Last node in topologic sort has users!");
11124   assert(DAGSize == allnodes_size() && "Node count mismatch!");
11125   return DAGSize;
11126 }
11127 
11128 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
11129 /// value is produced by SD.
11130 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
11131   for (SDNode *SD : DB->getSDNodes()) {
11132     if (!SD)
11133       continue;
11134     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
11135     SD->setHasDebugValue(true);
11136   }
11137   DbgInfo->add(DB, isParameter);
11138 }
11139 
11140 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
11141 
11142 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
11143                                                    SDValue NewMemOpChain) {
11144   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
11145   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
11146   // The new memory operation must have the same position as the old load in
11147   // terms of memory dependency. Create a TokenFactor for the old load and new
11148   // memory operation and update uses of the old load's output chain to use that
11149   // TokenFactor.
11150   if (OldChain == NewMemOpChain || OldChain.use_empty())
11151     return NewMemOpChain;
11152 
11153   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
11154                                 OldChain, NewMemOpChain);
11155   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
11156   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
11157   return TokenFactor;
11158 }
11159 
11160 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
11161                                                    SDValue NewMemOp) {
11162   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
11163   SDValue OldChain = SDValue(OldLoad, 1);
11164   SDValue NewMemOpChain = NewMemOp.getValue(1);
11165   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
11166 }
11167 
11168 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
11169                                                      Function **OutFunction) {
11170   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
11171 
11172   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11173   auto *Module = MF->getFunction().getParent();
11174   auto *Function = Module->getFunction(Symbol);
11175 
11176   if (OutFunction != nullptr)
11177       *OutFunction = Function;
11178 
11179   if (Function != nullptr) {
11180     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
11181     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
11182   }
11183 
11184   std::string ErrorStr;
11185   raw_string_ostream ErrorFormatter(ErrorStr);
11186   ErrorFormatter << "Undefined external symbol ";
11187   ErrorFormatter << '"' << Symbol << '"';
11188   report_fatal_error(Twine(ErrorFormatter.str()));
11189 }
11190 
11191 //===----------------------------------------------------------------------===//
11192 //                              SDNode Class
11193 //===----------------------------------------------------------------------===//
11194 
11195 bool llvm::isNullConstant(SDValue V) {
11196   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
11197   return Const != nullptr && Const->isZero();
11198 }
11199 
11200 bool llvm::isNullFPConstant(SDValue V) {
11201   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
11202   return Const != nullptr && Const->isZero() && !Const->isNegative();
11203 }
11204 
11205 bool llvm::isAllOnesConstant(SDValue V) {
11206   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
11207   return Const != nullptr && Const->isAllOnes();
11208 }
11209 
11210 bool llvm::isOneConstant(SDValue V) {
11211   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
11212   return Const != nullptr && Const->isOne();
11213 }
11214 
11215 bool llvm::isMinSignedConstant(SDValue V) {
11216   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
11217   return Const != nullptr && Const->isMinSignedValue();
11218 }
11219 
11220 bool llvm::isNeutralConstant(unsigned Opcode, SDNodeFlags Flags, SDValue V,
11221                              unsigned OperandNo) {
11222   // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
11223   // TODO: Target-specific opcodes could be added.
11224   if (auto *Const = isConstOrConstSplat(V)) {
11225     switch (Opcode) {
11226     case ISD::ADD:
11227     case ISD::OR:
11228     case ISD::XOR:
11229     case ISD::UMAX:
11230       return Const->isZero();
11231     case ISD::MUL:
11232       return Const->isOne();
11233     case ISD::AND:
11234     case ISD::UMIN:
11235       return Const->isAllOnes();
11236     case ISD::SMAX:
11237       return Const->isMinSignedValue();
11238     case ISD::SMIN:
11239       return Const->isMaxSignedValue();
11240     case ISD::SUB:
11241     case ISD::SHL:
11242     case ISD::SRA:
11243     case ISD::SRL:
11244       return OperandNo == 1 && Const->isZero();
11245     case ISD::UDIV:
11246     case ISD::SDIV:
11247       return OperandNo == 1 && Const->isOne();
11248     }
11249   } else if (auto *ConstFP = isConstOrConstSplatFP(V)) {
11250     switch (Opcode) {
11251     case ISD::FADD:
11252       return ConstFP->isZero() &&
11253              (Flags.hasNoSignedZeros() || ConstFP->isNegative());
11254     case ISD::FSUB:
11255       return OperandNo == 1 && ConstFP->isZero() &&
11256              (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
11257     case ISD::FMUL:
11258       return ConstFP->isExactlyValue(1.0);
11259     case ISD::FDIV:
11260       return OperandNo == 1 && ConstFP->isExactlyValue(1.0);
11261     case ISD::FMINNUM:
11262     case ISD::FMAXNUM: {
11263       // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11264       EVT VT = V.getValueType();
11265       const fltSemantics &Semantics = SelectionDAG::EVTToAPFloatSemantics(VT);
11266       APFloat NeutralAF = !Flags.hasNoNaNs()
11267                               ? APFloat::getQNaN(Semantics)
11268                               : !Flags.hasNoInfs()
11269                                     ? APFloat::getInf(Semantics)
11270                                     : APFloat::getLargest(Semantics);
11271       if (Opcode == ISD::FMAXNUM)
11272         NeutralAF.changeSign();
11273 
11274       return ConstFP->isExactlyValue(NeutralAF);
11275     }
11276     }
11277   }
11278   return false;
11279 }
11280 
11281 SDValue llvm::peekThroughBitcasts(SDValue V) {
11282   while (V.getOpcode() == ISD::BITCAST)
11283     V = V.getOperand(0);
11284   return V;
11285 }
11286 
11287 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
11288   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
11289     V = V.getOperand(0);
11290   return V;
11291 }
11292 
11293 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
11294   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11295     V = V.getOperand(0);
11296   return V;
11297 }
11298 
11299 SDValue llvm::peekThroughTruncates(SDValue V) {
11300   while (V.getOpcode() == ISD::TRUNCATE)
11301     V = V.getOperand(0);
11302   return V;
11303 }
11304 
11305 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
11306   if (V.getOpcode() != ISD::XOR)
11307     return false;
11308   V = peekThroughBitcasts(V.getOperand(1));
11309   unsigned NumBits = V.getScalarValueSizeInBits();
11310   ConstantSDNode *C =
11311       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
11312   return C && (C->getAPIntValue().countr_one() >= NumBits);
11313 }
11314 
11315 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
11316                                           bool AllowTruncation) {
11317   EVT VT = N.getValueType();
11318   APInt DemandedElts = VT.isFixedLengthVector()
11319                            ? APInt::getAllOnes(VT.getVectorMinNumElements())
11320                            : APInt(1, 1);
11321   return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
11322 }
11323 
11324 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
11325                                           bool AllowUndefs,
11326                                           bool AllowTruncation) {
11327   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
11328     return CN;
11329 
11330   // SplatVectors can truncate their operands. Ignore that case here unless
11331   // AllowTruncation is set.
11332   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
11333     EVT VecEltVT = N->getValueType(0).getVectorElementType();
11334     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11335       EVT CVT = CN->getValueType(0);
11336       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
11337       if (AllowTruncation || CVT == VecEltVT)
11338         return CN;
11339     }
11340   }
11341 
11342   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
11343     BitVector UndefElements;
11344     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
11345 
11346     // BuildVectors can truncate their operands. Ignore that case here unless
11347     // AllowTruncation is set.
11348     // TODO: Look into whether we should allow UndefElements in non-DemandedElts
11349     if (CN && (UndefElements.none() || AllowUndefs)) {
11350       EVT CVT = CN->getValueType(0);
11351       EVT NSVT = N.getValueType().getScalarType();
11352       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
11353       if (AllowTruncation || (CVT == NSVT))
11354         return CN;
11355     }
11356   }
11357 
11358   return nullptr;
11359 }
11360 
11361 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
11362   EVT VT = N.getValueType();
11363   APInt DemandedElts = VT.isFixedLengthVector()
11364                            ? APInt::getAllOnes(VT.getVectorMinNumElements())
11365                            : APInt(1, 1);
11366   return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
11367 }
11368 
11369 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
11370                                               const APInt &DemandedElts,
11371                                               bool AllowUndefs) {
11372   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
11373     return CN;
11374 
11375   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
11376     BitVector UndefElements;
11377     ConstantFPSDNode *CN =
11378         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
11379     // TODO: Look into whether we should allow UndefElements in non-DemandedElts
11380     if (CN && (UndefElements.none() || AllowUndefs))
11381       return CN;
11382   }
11383 
11384   if (N.getOpcode() == ISD::SPLAT_VECTOR)
11385     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
11386       return CN;
11387 
11388   return nullptr;
11389 }
11390 
11391 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
11392   // TODO: may want to use peekThroughBitcast() here.
11393   ConstantSDNode *C =
11394       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
11395   return C && C->isZero();
11396 }
11397 
11398 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
11399   ConstantSDNode *C =
11400       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
11401   return C && C->isOne();
11402 }
11403 
11404 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
11405   N = peekThroughBitcasts(N);
11406   unsigned BitWidth = N.getScalarValueSizeInBits();
11407   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
11408   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
11409 }
11410 
11411 HandleSDNode::~HandleSDNode() {
11412   DropOperands();
11413 }
11414 
11415 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
11416                                          const DebugLoc &DL,
11417                                          const GlobalValue *GA, EVT VT,
11418                                          int64_t o, unsigned TF)
11419     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
11420   TheGlobal = GA;
11421 }
11422 
11423 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
11424                                          EVT VT, unsigned SrcAS,
11425                                          unsigned DestAS)
11426     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
11427       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
11428 
11429 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
11430                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
11431     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
11432   MemSDNodeBits.IsVolatile = MMO->isVolatile();
11433   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
11434   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
11435   MemSDNodeBits.IsInvariant = MMO->isInvariant();
11436 
11437   // We check here that the size of the memory operand fits within the size of
11438   // the MMO. This is because the MMO might indicate only a possible address
11439   // range instead of specifying the affected memory addresses precisely.
11440   // TODO: Make MachineMemOperands aware of scalable vectors.
11441   assert(memvt.getStoreSize().getKnownMinValue() <= MMO->getSize() &&
11442          "Size mismatch!");
11443 }
11444 
11445 /// Profile - Gather unique data for the node.
11446 ///
11447 void SDNode::Profile(FoldingSetNodeID &ID) const {
11448   AddNodeIDNode(ID, this);
11449 }
11450 
11451 namespace {
11452 
11453   struct EVTArray {
11454     std::vector<EVT> VTs;
11455 
11456     EVTArray() {
11457       VTs.reserve(MVT::VALUETYPE_SIZE);
11458       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
11459         VTs.push_back(MVT((MVT::SimpleValueType)i));
11460     }
11461   };
11462 
11463 } // end anonymous namespace
11464 
11465 /// getValueTypeList - Return a pointer to the specified value type.
11466 ///
11467 const EVT *SDNode::getValueTypeList(EVT VT) {
11468   static std::set<EVT, EVT::compareRawBits> EVTs;
11469   static EVTArray SimpleVTArray;
11470   static sys::SmartMutex<true> VTMutex;
11471 
11472   if (VT.isExtended()) {
11473     sys::SmartScopedLock<true> Lock(VTMutex);
11474     return &(*EVTs.insert(VT).first);
11475   }
11476   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
11477   return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
11478 }
11479 
11480 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
11481 /// indicated value.  This method ignores uses of other values defined by this
11482 /// operation.
11483 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
11484   assert(Value < getNumValues() && "Bad value!");
11485 
11486   // TODO: Only iterate over uses of a given value of the node
11487   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
11488     if (UI.getUse().getResNo() == Value) {
11489       if (NUses == 0)
11490         return false;
11491       --NUses;
11492     }
11493   }
11494 
11495   // Found exactly the right number of uses?
11496   return NUses == 0;
11497 }
11498 
11499 /// hasAnyUseOfValue - Return true if there are any use of the indicated
11500 /// value. This method ignores uses of other values defined by this operation.
11501 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
11502   assert(Value < getNumValues() && "Bad value!");
11503 
11504   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
11505     if (UI.getUse().getResNo() == Value)
11506       return true;
11507 
11508   return false;
11509 }
11510 
11511 /// isOnlyUserOf - Return true if this node is the only use of N.
11512 bool SDNode::isOnlyUserOf(const SDNode *N) const {
11513   bool Seen = false;
11514   for (const SDNode *User : N->uses()) {
11515     if (User == this)
11516       Seen = true;
11517     else
11518       return false;
11519   }
11520 
11521   return Seen;
11522 }
11523 
11524 /// Return true if the only users of N are contained in Nodes.
11525 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
11526   bool Seen = false;
11527   for (const SDNode *User : N->uses()) {
11528     if (llvm::is_contained(Nodes, User))
11529       Seen = true;
11530     else
11531       return false;
11532   }
11533 
11534   return Seen;
11535 }
11536 
11537 /// isOperand - Return true if this node is an operand of N.
11538 bool SDValue::isOperandOf(const SDNode *N) const {
11539   return is_contained(N->op_values(), *this);
11540 }
11541 
11542 bool SDNode::isOperandOf(const SDNode *N) const {
11543   return any_of(N->op_values(),
11544                 [this](SDValue Op) { return this == Op.getNode(); });
11545 }
11546 
11547 /// reachesChainWithoutSideEffects - Return true if this operand (which must
11548 /// be a chain) reaches the specified operand without crossing any
11549 /// side-effecting instructions on any chain path.  In practice, this looks
11550 /// through token factors and non-volatile loads.  In order to remain efficient,
11551 /// this only looks a couple of nodes in, it does not do an exhaustive search.
11552 ///
11553 /// Note that we only need to examine chains when we're searching for
11554 /// side-effects; SelectionDAG requires that all side-effects are represented
11555 /// by chains, even if another operand would force a specific ordering. This
11556 /// constraint is necessary to allow transformations like splitting loads.
11557 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
11558                                              unsigned Depth) const {
11559   if (*this == Dest) return true;
11560 
11561   // Don't search too deeply, we just want to be able to see through
11562   // TokenFactor's etc.
11563   if (Depth == 0) return false;
11564 
11565   // If this is a token factor, all inputs to the TF happen in parallel.
11566   if (getOpcode() == ISD::TokenFactor) {
11567     // First, try a shallow search.
11568     if (is_contained((*this)->ops(), Dest)) {
11569       // We found the chain we want as an operand of this TokenFactor.
11570       // Essentially, we reach the chain without side-effects if we could
11571       // serialize the TokenFactor into a simple chain of operations with
11572       // Dest as the last operation. This is automatically true if the
11573       // chain has one use: there are no other ordering constraints.
11574       // If the chain has more than one use, we give up: some other
11575       // use of Dest might force a side-effect between Dest and the current
11576       // node.
11577       if (Dest.hasOneUse())
11578         return true;
11579     }
11580     // Next, try a deep search: check whether every operand of the TokenFactor
11581     // reaches Dest.
11582     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
11583       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
11584     });
11585   }
11586 
11587   // Loads don't have side effects, look through them.
11588   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
11589     if (Ld->isUnordered())
11590       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
11591   }
11592   return false;
11593 }
11594 
11595 bool SDNode::hasPredecessor(const SDNode *N) const {
11596   SmallPtrSet<const SDNode *, 32> Visited;
11597   SmallVector<const SDNode *, 16> Worklist;
11598   Worklist.push_back(this);
11599   return hasPredecessorHelper(N, Visited, Worklist);
11600 }
11601 
11602 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
11603   this->Flags.intersectWith(Flags);
11604 }
11605 
11606 SDValue
11607 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
11608                                   ArrayRef<ISD::NodeType> CandidateBinOps,
11609                                   bool AllowPartials) {
11610   // The pattern must end in an extract from index 0.
11611   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11612       !isNullConstant(Extract->getOperand(1)))
11613     return SDValue();
11614 
11615   // Match against one of the candidate binary ops.
11616   SDValue Op = Extract->getOperand(0);
11617   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
11618         return Op.getOpcode() == unsigned(BinOp);
11619       }))
11620     return SDValue();
11621 
11622   // Floating-point reductions may require relaxed constraints on the final step
11623   // of the reduction because they may reorder intermediate operations.
11624   unsigned CandidateBinOp = Op.getOpcode();
11625   if (Op.getValueType().isFloatingPoint()) {
11626     SDNodeFlags Flags = Op->getFlags();
11627     switch (CandidateBinOp) {
11628     case ISD::FADD:
11629       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
11630         return SDValue();
11631       break;
11632     default:
11633       llvm_unreachable("Unhandled FP opcode for binop reduction");
11634     }
11635   }
11636 
11637   // Matching failed - attempt to see if we did enough stages that a partial
11638   // reduction from a subvector is possible.
11639   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
11640     if (!AllowPartials || !Op)
11641       return SDValue();
11642     EVT OpVT = Op.getValueType();
11643     EVT OpSVT = OpVT.getScalarType();
11644     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
11645     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
11646       return SDValue();
11647     BinOp = (ISD::NodeType)CandidateBinOp;
11648     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
11649                    getVectorIdxConstant(0, SDLoc(Op)));
11650   };
11651 
11652   // At each stage, we're looking for something that looks like:
11653   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
11654   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
11655   //                               i32 undef, i32 undef, i32 undef, i32 undef>
11656   // %a = binop <8 x i32> %op, %s
11657   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
11658   // we expect something like:
11659   // <4,5,6,7,u,u,u,u>
11660   // <2,3,u,u,u,u,u,u>
11661   // <1,u,u,u,u,u,u,u>
11662   // While a partial reduction match would be:
11663   // <2,3,u,u,u,u,u,u>
11664   // <1,u,u,u,u,u,u,u>
11665   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
11666   SDValue PrevOp;
11667   for (unsigned i = 0; i < Stages; ++i) {
11668     unsigned MaskEnd = (1 << i);
11669 
11670     if (Op.getOpcode() != CandidateBinOp)
11671       return PartialReduction(PrevOp, MaskEnd);
11672 
11673     SDValue Op0 = Op.getOperand(0);
11674     SDValue Op1 = Op.getOperand(1);
11675 
11676     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
11677     if (Shuffle) {
11678       Op = Op1;
11679     } else {
11680       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
11681       Op = Op0;
11682     }
11683 
11684     // The first operand of the shuffle should be the same as the other operand
11685     // of the binop.
11686     if (!Shuffle || Shuffle->getOperand(0) != Op)
11687       return PartialReduction(PrevOp, MaskEnd);
11688 
11689     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
11690     for (int Index = 0; Index < (int)MaskEnd; ++Index)
11691       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
11692         return PartialReduction(PrevOp, MaskEnd);
11693 
11694     PrevOp = Op;
11695   }
11696 
11697   // Handle subvector reductions, which tend to appear after the shuffle
11698   // reduction stages.
11699   while (Op.getOpcode() == CandidateBinOp) {
11700     unsigned NumElts = Op.getValueType().getVectorNumElements();
11701     SDValue Op0 = Op.getOperand(0);
11702     SDValue Op1 = Op.getOperand(1);
11703     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11704         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11705         Op0.getOperand(0) != Op1.getOperand(0))
11706       break;
11707     SDValue Src = Op0.getOperand(0);
11708     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11709     if (NumSrcElts != (2 * NumElts))
11710       break;
11711     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11712           Op1.getConstantOperandAPInt(1) == NumElts) &&
11713         !(Op1.getConstantOperandAPInt(1) == 0 &&
11714           Op0.getConstantOperandAPInt(1) == NumElts))
11715       break;
11716     Op = Src;
11717   }
11718 
11719   BinOp = (ISD::NodeType)CandidateBinOp;
11720   return Op;
11721 }
11722 
11723 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11724   EVT VT = N->getValueType(0);
11725   EVT EltVT = VT.getVectorElementType();
11726   unsigned NE = VT.getVectorNumElements();
11727 
11728   SDLoc dl(N);
11729 
11730   // If ResNE is 0, fully unroll the vector op.
11731   if (ResNE == 0)
11732     ResNE = NE;
11733   else if (NE > ResNE)
11734     NE = ResNE;
11735 
11736   if (N->getNumValues() == 2) {
11737     SmallVector<SDValue, 8> Scalars0, Scalars1;
11738     SmallVector<SDValue, 4> Operands(N->getNumOperands());
11739     EVT VT1 = N->getValueType(1);
11740     EVT EltVT1 = VT1.getVectorElementType();
11741 
11742     unsigned i;
11743     for (i = 0; i != NE; ++i) {
11744       for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11745         SDValue Operand = N->getOperand(j);
11746         EVT OperandVT = Operand.getValueType();
11747 
11748         // A vector operand; extract a single element.
11749         EVT OperandEltVT = OperandVT.getVectorElementType();
11750         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11751                               Operand, getVectorIdxConstant(i, dl));
11752       }
11753 
11754       SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
11755       Scalars0.push_back(EltOp);
11756       Scalars1.push_back(EltOp.getValue(1));
11757     }
11758 
11759     SDValue Vec0 = getBuildVector(VT, dl, Scalars0);
11760     SDValue Vec1 = getBuildVector(VT1, dl, Scalars1);
11761     return getMergeValues({Vec0, Vec1}, dl);
11762   }
11763 
11764   assert(N->getNumValues() == 1 &&
11765          "Can't unroll a vector with multiple results!");
11766 
11767   SmallVector<SDValue, 8> Scalars;
11768   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11769 
11770   unsigned i;
11771   for (i= 0; i != NE; ++i) {
11772     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11773       SDValue Operand = N->getOperand(j);
11774       EVT OperandVT = Operand.getValueType();
11775       if (OperandVT.isVector()) {
11776         // A vector operand; extract a single element.
11777         EVT OperandEltVT = OperandVT.getVectorElementType();
11778         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11779                               Operand, getVectorIdxConstant(i, dl));
11780       } else {
11781         // A scalar operand; just use it as is.
11782         Operands[j] = Operand;
11783       }
11784     }
11785 
11786     switch (N->getOpcode()) {
11787     default: {
11788       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11789                                 N->getFlags()));
11790       break;
11791     }
11792     case ISD::VSELECT:
11793       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11794       break;
11795     case ISD::SHL:
11796     case ISD::SRA:
11797     case ISD::SRL:
11798     case ISD::ROTL:
11799     case ISD::ROTR:
11800       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11801                                getShiftAmountOperand(Operands[0].getValueType(),
11802                                                      Operands[1])));
11803       break;
11804     case ISD::SIGN_EXTEND_INREG: {
11805       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11806       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11807                                 Operands[0],
11808                                 getValueType(ExtVT)));
11809     }
11810     }
11811   }
11812 
11813   for (; i < ResNE; ++i)
11814     Scalars.push_back(getUNDEF(EltVT));
11815 
11816   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11817   return getBuildVector(VecVT, dl, Scalars);
11818 }
11819 
11820 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11821     SDNode *N, unsigned ResNE) {
11822   unsigned Opcode = N->getOpcode();
11823   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11824           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11825           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11826          "Expected an overflow opcode");
11827 
11828   EVT ResVT = N->getValueType(0);
11829   EVT OvVT = N->getValueType(1);
11830   EVT ResEltVT = ResVT.getVectorElementType();
11831   EVT OvEltVT = OvVT.getVectorElementType();
11832   SDLoc dl(N);
11833 
11834   // If ResNE is 0, fully unroll the vector op.
11835   unsigned NE = ResVT.getVectorNumElements();
11836   if (ResNE == 0)
11837     ResNE = NE;
11838   else if (NE > ResNE)
11839     NE = ResNE;
11840 
11841   SmallVector<SDValue, 8> LHSScalars;
11842   SmallVector<SDValue, 8> RHSScalars;
11843   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11844   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11845 
11846   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11847   SDVTList VTs = getVTList(ResEltVT, SVT);
11848   SmallVector<SDValue, 8> ResScalars;
11849   SmallVector<SDValue, 8> OvScalars;
11850   for (unsigned i = 0; i < NE; ++i) {
11851     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11852     SDValue Ov =
11853         getSelect(dl, OvEltVT, Res.getValue(1),
11854                   getBoolConstant(true, dl, OvEltVT, ResVT),
11855                   getConstant(0, dl, OvEltVT));
11856 
11857     ResScalars.push_back(Res);
11858     OvScalars.push_back(Ov);
11859   }
11860 
11861   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11862   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11863 
11864   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11865   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11866   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11867                         getBuildVector(NewOvVT, dl, OvScalars));
11868 }
11869 
11870 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11871                                                   LoadSDNode *Base,
11872                                                   unsigned Bytes,
11873                                                   int Dist) const {
11874   if (LD->isVolatile() || Base->isVolatile())
11875     return false;
11876   // TODO: probably too restrictive for atomics, revisit
11877   if (!LD->isSimple())
11878     return false;
11879   if (LD->isIndexed() || Base->isIndexed())
11880     return false;
11881   if (LD->getChain() != Base->getChain())
11882     return false;
11883   EVT VT = LD->getMemoryVT();
11884   if (VT.getSizeInBits() / 8 != Bytes)
11885     return false;
11886 
11887   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11888   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11889 
11890   int64_t Offset = 0;
11891   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11892     return (Dist * (int64_t)Bytes == Offset);
11893   return false;
11894 }
11895 
11896 /// InferPtrAlignment - Infer alignment of a load / store address. Return
11897 /// std::nullopt if it cannot be inferred.
11898 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11899   // If this is a GlobalAddress + cst, return the alignment.
11900   const GlobalValue *GV = nullptr;
11901   int64_t GVOffset = 0;
11902   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11903     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11904     KnownBits Known(PtrWidth);
11905     llvm::computeKnownBits(GV, Known, getDataLayout());
11906     unsigned AlignBits = Known.countMinTrailingZeros();
11907     if (AlignBits)
11908       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11909   }
11910 
11911   // If this is a direct reference to a stack slot, use information about the
11912   // stack slot's alignment.
11913   int FrameIdx = INT_MIN;
11914   int64_t FrameOffset = 0;
11915   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11916     FrameIdx = FI->getIndex();
11917   } else if (isBaseWithConstantOffset(Ptr) &&
11918              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11919     // Handle FI+Cst
11920     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11921     FrameOffset = Ptr.getConstantOperandVal(1);
11922   }
11923 
11924   if (FrameIdx != INT_MIN) {
11925     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11926     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11927   }
11928 
11929   return std::nullopt;
11930 }
11931 
11932 /// Split the scalar node with EXTRACT_ELEMENT using the provided
11933 /// VTs and return the low/high part.
11934 std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
11935                                                       const SDLoc &DL,
11936                                                       const EVT &LoVT,
11937                                                       const EVT &HiVT) {
11938   assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
11939          "Split node must be a scalar type");
11940   SDValue Lo =
11941       getNode(ISD::EXTRACT_ELEMENT, DL, LoVT, N, getIntPtrConstant(0, DL));
11942   SDValue Hi =
11943       getNode(ISD::EXTRACT_ELEMENT, DL, HiVT, N, getIntPtrConstant(1, DL));
11944   return std::make_pair(Lo, Hi);
11945 }
11946 
11947 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11948 /// which is split (or expanded) into two not necessarily identical pieces.
11949 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11950   // Currently all types are split in half.
11951   EVT LoVT, HiVT;
11952   if (!VT.isVector())
11953     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11954   else
11955     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11956 
11957   return std::make_pair(LoVT, HiVT);
11958 }
11959 
11960 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11961 /// type, dependent on an enveloping VT that has been split into two identical
11962 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11963 std::pair<EVT, EVT>
11964 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11965                                        bool *HiIsEmpty) const {
11966   EVT EltTp = VT.getVectorElementType();
11967   // Examples:
11968   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11969   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11970   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11971   //   etc.
11972   ElementCount VTNumElts = VT.getVectorElementCount();
11973   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11974   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11975          "Mixing fixed width and scalable vectors when enveloping a type");
11976   EVT LoVT, HiVT;
11977   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11978     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11979     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11980     *HiIsEmpty = false;
11981   } else {
11982     // Flag that hi type has zero storage size, but return split envelop type
11983     // (this would be easier if vector types with zero elements were allowed).
11984     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11985     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11986     *HiIsEmpty = true;
11987   }
11988   return std::make_pair(LoVT, HiVT);
11989 }
11990 
11991 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11992 /// low/high part.
11993 std::pair<SDValue, SDValue>
11994 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11995                           const EVT &HiVT) {
11996   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11997          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11998          "Splitting vector with an invalid mixture of fixed and scalable "
11999          "vector types");
12000   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
12001              N.getValueType().getVectorMinNumElements() &&
12002          "More vector elements requested than available!");
12003   SDValue Lo, Hi;
12004   Lo =
12005       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
12006   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
12007   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
12008   // IDX with the runtime scaling factor of the result vector type. For
12009   // fixed-width result vectors, that runtime scaling factor is 1.
12010   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
12011                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
12012   return std::make_pair(Lo, Hi);
12013 }
12014 
12015 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
12016                                                    const SDLoc &DL) {
12017   // Split the vector length parameter.
12018   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
12019   EVT VT = N.getValueType();
12020   assert(VecVT.getVectorElementCount().isKnownEven() &&
12021          "Expecting the mask to be an evenly-sized vector");
12022   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
12023   SDValue HalfNumElts =
12024       VecVT.isFixedLengthVector()
12025           ? getConstant(HalfMinNumElts, DL, VT)
12026           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
12027   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
12028   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
12029   return std::make_pair(Lo, Hi);
12030 }
12031 
12032 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
12033 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
12034   EVT VT = N.getValueType();
12035   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
12036                                 NextPowerOf2(VT.getVectorNumElements()));
12037   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
12038                  getVectorIdxConstant(0, DL));
12039 }
12040 
12041 void SelectionDAG::ExtractVectorElements(SDValue Op,
12042                                          SmallVectorImpl<SDValue> &Args,
12043                                          unsigned Start, unsigned Count,
12044                                          EVT EltVT) {
12045   EVT VT = Op.getValueType();
12046   if (Count == 0)
12047     Count = VT.getVectorNumElements();
12048   if (EltVT == EVT())
12049     EltVT = VT.getVectorElementType();
12050   SDLoc SL(Op);
12051   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
12052     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
12053                            getVectorIdxConstant(i, SL)));
12054   }
12055 }
12056 
12057 // getAddressSpace - Return the address space this GlobalAddress belongs to.
12058 unsigned GlobalAddressSDNode::getAddressSpace() const {
12059   return getGlobal()->getType()->getAddressSpace();
12060 }
12061 
12062 Type *ConstantPoolSDNode::getType() const {
12063   if (isMachineConstantPoolEntry())
12064     return Val.MachineCPVal->getType();
12065   return Val.ConstVal->getType();
12066 }
12067 
12068 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
12069                                         unsigned &SplatBitSize,
12070                                         bool &HasAnyUndefs,
12071                                         unsigned MinSplatBits,
12072                                         bool IsBigEndian) const {
12073   EVT VT = getValueType(0);
12074   assert(VT.isVector() && "Expected a vector type");
12075   unsigned VecWidth = VT.getSizeInBits();
12076   if (MinSplatBits > VecWidth)
12077     return false;
12078 
12079   // FIXME: The widths are based on this node's type, but build vectors can
12080   // truncate their operands.
12081   SplatValue = APInt(VecWidth, 0);
12082   SplatUndef = APInt(VecWidth, 0);
12083 
12084   // Get the bits. Bits with undefined values (when the corresponding element
12085   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
12086   // in SplatValue. If any of the values are not constant, give up and return
12087   // false.
12088   unsigned int NumOps = getNumOperands();
12089   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
12090   unsigned EltWidth = VT.getScalarSizeInBits();
12091 
12092   for (unsigned j = 0; j < NumOps; ++j) {
12093     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
12094     SDValue OpVal = getOperand(i);
12095     unsigned BitPos = j * EltWidth;
12096 
12097     if (OpVal.isUndef())
12098       SplatUndef.setBits(BitPos, BitPos + EltWidth);
12099     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
12100       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
12101     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
12102       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
12103     else
12104       return false;
12105   }
12106 
12107   // The build_vector is all constants or undefs. Find the smallest element
12108   // size that splats the vector.
12109   HasAnyUndefs = (SplatUndef != 0);
12110 
12111   // FIXME: This does not work for vectors with elements less than 8 bits.
12112   while (VecWidth > 8) {
12113     unsigned HalfSize = VecWidth / 2;
12114     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
12115     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
12116     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
12117     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
12118 
12119     // If the two halves do not match (ignoring undef bits), stop here.
12120     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
12121         MinSplatBits > HalfSize)
12122       break;
12123 
12124     SplatValue = HighValue | LowValue;
12125     SplatUndef = HighUndef & LowUndef;
12126 
12127     VecWidth = HalfSize;
12128   }
12129 
12130   SplatBitSize = VecWidth;
12131   return true;
12132 }
12133 
12134 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
12135                                          BitVector *UndefElements) const {
12136   unsigned NumOps = getNumOperands();
12137   if (UndefElements) {
12138     UndefElements->clear();
12139     UndefElements->resize(NumOps);
12140   }
12141   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
12142   if (!DemandedElts)
12143     return SDValue();
12144   SDValue Splatted;
12145   for (unsigned i = 0; i != NumOps; ++i) {
12146     if (!DemandedElts[i])
12147       continue;
12148     SDValue Op = getOperand(i);
12149     if (Op.isUndef()) {
12150       if (UndefElements)
12151         (*UndefElements)[i] = true;
12152     } else if (!Splatted) {
12153       Splatted = Op;
12154     } else if (Splatted != Op) {
12155       return SDValue();
12156     }
12157   }
12158 
12159   if (!Splatted) {
12160     unsigned FirstDemandedIdx = DemandedElts.countr_zero();
12161     assert(getOperand(FirstDemandedIdx).isUndef() &&
12162            "Can only have a splat without a constant for all undefs.");
12163     return getOperand(FirstDemandedIdx);
12164   }
12165 
12166   return Splatted;
12167 }
12168 
12169 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
12170   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
12171   return getSplatValue(DemandedElts, UndefElements);
12172 }
12173 
12174 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
12175                                             SmallVectorImpl<SDValue> &Sequence,
12176                                             BitVector *UndefElements) const {
12177   unsigned NumOps = getNumOperands();
12178   Sequence.clear();
12179   if (UndefElements) {
12180     UndefElements->clear();
12181     UndefElements->resize(NumOps);
12182   }
12183   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
12184   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
12185     return false;
12186 
12187   // Set the undefs even if we don't find a sequence (like getSplatValue).
12188   if (UndefElements)
12189     for (unsigned I = 0; I != NumOps; ++I)
12190       if (DemandedElts[I] && getOperand(I).isUndef())
12191         (*UndefElements)[I] = true;
12192 
12193   // Iteratively widen the sequence length looking for repetitions.
12194   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
12195     Sequence.append(SeqLen, SDValue());
12196     for (unsigned I = 0; I != NumOps; ++I) {
12197       if (!DemandedElts[I])
12198         continue;
12199       SDValue &SeqOp = Sequence[I % SeqLen];
12200       SDValue Op = getOperand(I);
12201       if (Op.isUndef()) {
12202         if (!SeqOp)
12203           SeqOp = Op;
12204         continue;
12205       }
12206       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
12207         Sequence.clear();
12208         break;
12209       }
12210       SeqOp = Op;
12211     }
12212     if (!Sequence.empty())
12213       return true;
12214   }
12215 
12216   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
12217   return false;
12218 }
12219 
12220 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
12221                                             BitVector *UndefElements) const {
12222   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
12223   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
12224 }
12225 
12226 ConstantSDNode *
12227 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
12228                                         BitVector *UndefElements) const {
12229   return dyn_cast_or_null<ConstantSDNode>(
12230       getSplatValue(DemandedElts, UndefElements));
12231 }
12232 
12233 ConstantSDNode *
12234 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
12235   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
12236 }
12237 
12238 ConstantFPSDNode *
12239 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
12240                                           BitVector *UndefElements) const {
12241   return dyn_cast_or_null<ConstantFPSDNode>(
12242       getSplatValue(DemandedElts, UndefElements));
12243 }
12244 
12245 ConstantFPSDNode *
12246 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
12247   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
12248 }
12249 
12250 int32_t
12251 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
12252                                                    uint32_t BitWidth) const {
12253   if (ConstantFPSDNode *CN =
12254           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
12255     bool IsExact;
12256     APSInt IntVal(BitWidth);
12257     const APFloat &APF = CN->getValueAPF();
12258     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
12259             APFloat::opOK ||
12260         !IsExact)
12261       return -1;
12262 
12263     return IntVal.exactLogBase2();
12264   }
12265   return -1;
12266 }
12267 
12268 bool BuildVectorSDNode::getConstantRawBits(
12269     bool IsLittleEndian, unsigned DstEltSizeInBits,
12270     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
12271   // Early-out if this contains anything but Undef/Constant/ConstantFP.
12272   if (!isConstant())
12273     return false;
12274 
12275   unsigned NumSrcOps = getNumOperands();
12276   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
12277   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
12278          "Invalid bitcast scale");
12279 
12280   // Extract raw src bits.
12281   SmallVector<APInt> SrcBitElements(NumSrcOps,
12282                                     APInt::getZero(SrcEltSizeInBits));
12283   BitVector SrcUndeElements(NumSrcOps, false);
12284 
12285   for (unsigned I = 0; I != NumSrcOps; ++I) {
12286     SDValue Op = getOperand(I);
12287     if (Op.isUndef()) {
12288       SrcUndeElements.set(I);
12289       continue;
12290     }
12291     auto *CInt = dyn_cast<ConstantSDNode>(Op);
12292     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
12293     assert((CInt || CFP) && "Unknown constant");
12294     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
12295                              : CFP->getValueAPF().bitcastToAPInt();
12296   }
12297 
12298   // Recast to dst width.
12299   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
12300                 SrcBitElements, UndefElements, SrcUndeElements);
12301   return true;
12302 }
12303 
12304 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
12305                                       unsigned DstEltSizeInBits,
12306                                       SmallVectorImpl<APInt> &DstBitElements,
12307                                       ArrayRef<APInt> SrcBitElements,
12308                                       BitVector &DstUndefElements,
12309                                       const BitVector &SrcUndefElements) {
12310   unsigned NumSrcOps = SrcBitElements.size();
12311   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
12312   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
12313          "Invalid bitcast scale");
12314   assert(NumSrcOps == SrcUndefElements.size() &&
12315          "Vector size mismatch");
12316 
12317   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
12318   DstUndefElements.clear();
12319   DstUndefElements.resize(NumDstOps, false);
12320   DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
12321 
12322   // Concatenate src elements constant bits together into dst element.
12323   if (SrcEltSizeInBits <= DstEltSizeInBits) {
12324     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
12325     for (unsigned I = 0; I != NumDstOps; ++I) {
12326       DstUndefElements.set(I);
12327       APInt &DstBits = DstBitElements[I];
12328       for (unsigned J = 0; J != Scale; ++J) {
12329         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
12330         if (SrcUndefElements[Idx])
12331           continue;
12332         DstUndefElements.reset(I);
12333         const APInt &SrcBits = SrcBitElements[Idx];
12334         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
12335                "Illegal constant bitwidths");
12336         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
12337       }
12338     }
12339     return;
12340   }
12341 
12342   // Split src element constant bits into dst elements.
12343   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
12344   for (unsigned I = 0; I != NumSrcOps; ++I) {
12345     if (SrcUndefElements[I]) {
12346       DstUndefElements.set(I * Scale, (I + 1) * Scale);
12347       continue;
12348     }
12349     const APInt &SrcBits = SrcBitElements[I];
12350     for (unsigned J = 0; J != Scale; ++J) {
12351       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
12352       APInt &DstBits = DstBitElements[Idx];
12353       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
12354     }
12355   }
12356 }
12357 
12358 bool BuildVectorSDNode::isConstant() const {
12359   for (const SDValue &Op : op_values()) {
12360     unsigned Opc = Op.getOpcode();
12361     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
12362       return false;
12363   }
12364   return true;
12365 }
12366 
12367 std::optional<std::pair<APInt, APInt>>
12368 BuildVectorSDNode::isConstantSequence() const {
12369   unsigned NumOps = getNumOperands();
12370   if (NumOps < 2)
12371     return std::nullopt;
12372 
12373   if (!isa<ConstantSDNode>(getOperand(0)) ||
12374       !isa<ConstantSDNode>(getOperand(1)))
12375     return std::nullopt;
12376 
12377   unsigned EltSize = getValueType(0).getScalarSizeInBits();
12378   APInt Start = getConstantOperandAPInt(0).trunc(EltSize);
12379   APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start;
12380 
12381   if (Stride.isZero())
12382     return std::nullopt;
12383 
12384   for (unsigned i = 2; i < NumOps; ++i) {
12385     if (!isa<ConstantSDNode>(getOperand(i)))
12386       return std::nullopt;
12387 
12388     APInt Val = getConstantOperandAPInt(i).trunc(EltSize);
12389     if (Val != (Start + (Stride * i)))
12390       return std::nullopt;
12391   }
12392 
12393   return std::make_pair(Start, Stride);
12394 }
12395 
12396 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
12397   // Find the first non-undef value in the shuffle mask.
12398   unsigned i, e;
12399   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
12400     /* search */;
12401 
12402   // If all elements are undefined, this shuffle can be considered a splat
12403   // (although it should eventually get simplified away completely).
12404   if (i == e)
12405     return true;
12406 
12407   // Make sure all remaining elements are either undef or the same as the first
12408   // non-undef value.
12409   for (int Idx = Mask[i]; i != e; ++i)
12410     if (Mask[i] >= 0 && Mask[i] != Idx)
12411       return false;
12412   return true;
12413 }
12414 
12415 // Returns the SDNode if it is a constant integer BuildVector
12416 // or constant integer.
12417 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
12418   if (isa<ConstantSDNode>(N))
12419     return N.getNode();
12420   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
12421     return N.getNode();
12422   // Treat a GlobalAddress supporting constant offset folding as a
12423   // constant integer.
12424   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
12425     if (GA->getOpcode() == ISD::GlobalAddress &&
12426         TLI->isOffsetFoldingLegal(GA))
12427       return GA;
12428   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
12429       isa<ConstantSDNode>(N.getOperand(0)))
12430     return N.getNode();
12431   return nullptr;
12432 }
12433 
12434 // Returns the SDNode if it is a constant float BuildVector
12435 // or constant float.
12436 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
12437   if (isa<ConstantFPSDNode>(N))
12438     return N.getNode();
12439 
12440   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
12441     return N.getNode();
12442 
12443   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
12444       isa<ConstantFPSDNode>(N.getOperand(0)))
12445     return N.getNode();
12446 
12447   return nullptr;
12448 }
12449 
12450 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
12451   assert(!Node->OperandList && "Node already has operands");
12452   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
12453          "too many operands to fit into SDNode");
12454   SDUse *Ops = OperandRecycler.allocate(
12455       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
12456 
12457   bool IsDivergent = false;
12458   for (unsigned I = 0; I != Vals.size(); ++I) {
12459     Ops[I].setUser(Node);
12460     Ops[I].setInitial(Vals[I]);
12461     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
12462       IsDivergent |= Ops[I].getNode()->isDivergent();
12463   }
12464   Node->NumOperands = Vals.size();
12465   Node->OperandList = Ops;
12466   if (!TLI->isSDNodeAlwaysUniform(Node)) {
12467     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
12468     Node->SDNodeBits.IsDivergent = IsDivergent;
12469   }
12470   checkForCycles(Node);
12471 }
12472 
12473 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
12474                                      SmallVectorImpl<SDValue> &Vals) {
12475   size_t Limit = SDNode::getMaxNumOperands();
12476   while (Vals.size() > Limit) {
12477     unsigned SliceIdx = Vals.size() - Limit;
12478     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
12479     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
12480     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
12481     Vals.emplace_back(NewTF);
12482   }
12483   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
12484 }
12485 
12486 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
12487                                         EVT VT, SDNodeFlags Flags) {
12488   switch (Opcode) {
12489   default:
12490     return SDValue();
12491   case ISD::ADD:
12492   case ISD::OR:
12493   case ISD::XOR:
12494   case ISD::UMAX:
12495     return getConstant(0, DL, VT);
12496   case ISD::MUL:
12497     return getConstant(1, DL, VT);
12498   case ISD::AND:
12499   case ISD::UMIN:
12500     return getAllOnesConstant(DL, VT);
12501   case ISD::SMAX:
12502     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
12503   case ISD::SMIN:
12504     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
12505   case ISD::FADD:
12506     return getConstantFP(-0.0, DL, VT);
12507   case ISD::FMUL:
12508     return getConstantFP(1.0, DL, VT);
12509   case ISD::FMINNUM:
12510   case ISD::FMAXNUM: {
12511     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
12512     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
12513     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
12514                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
12515                         APFloat::getLargest(Semantics);
12516     if (Opcode == ISD::FMAXNUM)
12517       NeutralAF.changeSign();
12518 
12519     return getConstantFP(NeutralAF, DL, VT);
12520   }
12521   case ISD::FMINIMUM:
12522   case ISD::FMAXIMUM: {
12523     // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
12524     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
12525     APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
12526                                            : APFloat::getLargest(Semantics);
12527     if (Opcode == ISD::FMAXIMUM)
12528       NeutralAF.changeSign();
12529 
12530     return getConstantFP(NeutralAF, DL, VT);
12531   }
12532 
12533   }
12534 }
12535 
12536 /// Helper used to make a call to a library function that has one argument of
12537 /// pointer type.
12538 ///
12539 /// Such functions include 'fegetmode', 'fesetenv' and some others, which are
12540 /// used to get or set floating-point state. They have one argument of pointer
12541 /// type, which points to the memory region containing bits of the
12542 /// floating-point state. The value returned by such function is ignored in the
12543 /// created call.
12544 ///
12545 /// \param LibFunc Reference to library function (value of RTLIB::Libcall).
12546 /// \param Ptr Pointer used to save/load state.
12547 /// \param InChain Ingoing token chain.
12548 /// \returns Outgoing chain token.
12549 SDValue SelectionDAG::makeStateFunctionCall(unsigned LibFunc, SDValue Ptr,
12550                                             SDValue InChain,
12551                                             const SDLoc &DLoc) {
12552   assert(InChain.getValueType() == MVT::Other && "Expected token chain");
12553   TargetLowering::ArgListTy Args;
12554   TargetLowering::ArgListEntry Entry;
12555   Entry.Node = Ptr;
12556   Entry.Ty = Ptr.getValueType().getTypeForEVT(*getContext());
12557   Args.push_back(Entry);
12558   RTLIB::Libcall LC = static_cast<RTLIB::Libcall>(LibFunc);
12559   SDValue Callee = getExternalSymbol(TLI->getLibcallName(LC),
12560                                      TLI->getPointerTy(getDataLayout()));
12561   TargetLowering::CallLoweringInfo CLI(*this);
12562   CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
12563       TLI->getLibcallCallingConv(LC), Type::getVoidTy(*getContext()), Callee,
12564       std::move(Args));
12565   return TLI->LowerCallTo(CLI).second;
12566 }
12567 
12568 void SelectionDAG::copyExtraInfo(SDNode *From, SDNode *To) {
12569   assert(From && To && "Invalid SDNode; empty source SDValue?");
12570   auto I = SDEI.find(From);
12571   if (I == SDEI.end())
12572     return;
12573 
12574   // Use of operator[] on the DenseMap may cause an insertion, which invalidates
12575   // the iterator, hence the need to make a copy to prevent a use-after-free.
12576   NodeExtraInfo NEI = I->second;
12577   if (LLVM_LIKELY(!NEI.PCSections)) {
12578     // No deep copy required for the types of extra info set.
12579     //
12580     // FIXME: Investigate if other types of extra info also need deep copy. This
12581     // depends on the types of nodes they can be attached to: if some extra info
12582     // is only ever attached to nodes where a replacement To node is always the
12583     // node where later use and propagation of the extra info has the intended
12584     // semantics, no deep copy is required.
12585     SDEI[To] = std::move(NEI);
12586     return;
12587   }
12588 
12589   // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
12590   // through the replacement of From with To. Otherwise, replacements of a node
12591   // (From) with more complex nodes (To and its operands) may result in lost
12592   // extra info where the root node (To) is insignificant in further propagating
12593   // and using extra info when further lowering to MIR.
12594   //
12595   // In the first step pre-populate the visited set with the nodes reachable
12596   // from the old From node. This avoids copying NodeExtraInfo to parts of the
12597   // DAG that is not new and should be left untouched.
12598   SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
12599   DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
12600   auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
12601     if (MaxDepth == 0) {
12602       // Remember this node in case we need to increase MaxDepth and continue
12603       // populating FromReach from this node.
12604       Leafs.emplace_back(N);
12605       return;
12606     }
12607     if (!FromReach.insert(N).second)
12608       return;
12609     for (const SDValue &Op : N->op_values())
12610       Self(Self, Op.getNode(), MaxDepth - 1);
12611   };
12612 
12613   // Copy extra info to To and all its transitive operands (that are new).
12614   SmallPtrSet<const SDNode *, 8> Visited;
12615   auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
12616     if (FromReach.contains(N))
12617       return true;
12618     if (!Visited.insert(N).second)
12619       return true;
12620     if (getEntryNode().getNode() == N)
12621       return false;
12622     for (const SDValue &Op : N->op_values()) {
12623       if (!Self(Self, Op.getNode()))
12624         return false;
12625     }
12626     // Copy only if entry node was not reached.
12627     SDEI[N] = NEI;
12628     return true;
12629   };
12630 
12631   // We first try with a lower MaxDepth, assuming that the path to common
12632   // operands between From and To is relatively short. This significantly
12633   // improves performance in the common case. The initial MaxDepth is big
12634   // enough to avoid retry in the common case; the last MaxDepth is large
12635   // enough to avoid having to use the fallback below (and protects from
12636   // potential stack exhaustion from recursion).
12637   for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
12638        PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
12639     // StartFrom is the previous (or initial) set of leafs reachable at the
12640     // previous maximum depth.
12641     SmallVector<const SDNode *> StartFrom;
12642     std::swap(StartFrom, Leafs);
12643     for (const SDNode *N : StartFrom)
12644       VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
12645     if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
12646       return;
12647     // This should happen very rarely (reached the entry node).
12648     LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
12649     assert(!Leafs.empty());
12650   }
12651 
12652   // This should not happen - but if it did, that means the subgraph reachable
12653   // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
12654   // could not visit all reachable common operands. Consequently, we were able
12655   // to reach the entry node.
12656   errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
12657   assert(false && "From subgraph too complex - increase max. MaxDepth?");
12658   // Best-effort fallback if assertions disabled.
12659   SDEI[To] = std::move(NEI);
12660 }
12661 
12662 #ifndef NDEBUG
12663 static void checkForCyclesHelper(const SDNode *N,
12664                                  SmallPtrSetImpl<const SDNode*> &Visited,
12665                                  SmallPtrSetImpl<const SDNode*> &Checked,
12666                                  const llvm::SelectionDAG *DAG) {
12667   // If this node has already been checked, don't check it again.
12668   if (Checked.count(N))
12669     return;
12670 
12671   // If a node has already been visited on this depth-first walk, reject it as
12672   // a cycle.
12673   if (!Visited.insert(N).second) {
12674     errs() << "Detected cycle in SelectionDAG\n";
12675     dbgs() << "Offending node:\n";
12676     N->dumprFull(DAG); dbgs() << "\n";
12677     abort();
12678   }
12679 
12680   for (const SDValue &Op : N->op_values())
12681     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
12682 
12683   Checked.insert(N);
12684   Visited.erase(N);
12685 }
12686 #endif
12687 
12688 void llvm::checkForCycles(const llvm::SDNode *N,
12689                           const llvm::SelectionDAG *DAG,
12690                           bool force) {
12691 #ifndef NDEBUG
12692   bool check = force;
12693 #ifdef EXPENSIVE_CHECKS
12694   check = true;
12695 #endif  // EXPENSIVE_CHECKS
12696   if (check) {
12697     assert(N && "Checking nonexistent SDNode");
12698     SmallPtrSet<const SDNode*, 32> visited;
12699     SmallPtrSet<const SDNode*, 32> checked;
12700     checkForCyclesHelper(N, visited, checked, DAG);
12701   }
12702 #endif  // !NDEBUG
12703 }
12704 
12705 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
12706   checkForCycles(DAG->getRoot().getNode(), DAG, force);
12707 }
12708